blob: 84ab23e584c1c6642896b5afa576cd61e686f6f4 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Steve Narofff8ecff22008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
John McCall66884dd2011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattnera9196812009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnera9196812009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000055
Eli Friedman42a84652009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000062 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner0cb78032009-02-24 22:27:37 +000064 return 0;
65}
66
John McCall66884dd2011-02-21 07:22:22 +000067static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
68 const ArrayType *arrayType = Context.getAsArrayType(declType);
69 if (!arrayType) return 0;
70
71 return IsStringInit(init, arrayType, Context);
72}
73
John McCall5decec92011-02-21 07:57:55 +000074static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
75 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000076 // Get the length of the string as parsed.
77 uint64_t StrLength =
78 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
79
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner0cb78032009-02-24 22:27:37 +000081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000082 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000083 // being initialized to a string literal.
84 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000085 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000086 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000087 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
88 ConstVal,
89 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000090 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000091 }
Mike Stump11289f42009-09-09 15:08:12 +000092
Eli Friedman893abe42009-05-29 18:22:49 +000093 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000094
Eli Friedman554eba92011-04-11 00:23:45 +000095 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +000096 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +000098 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +000099 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
100 // For Pascal strings it's OK to strip off the terminating null character,
101 // so the example below is valid:
102 //
103 // unsigned char a[2] = "\pa";
104 if (SL->isPascal())
105 StrLength--;
106 }
107
Eli Friedman554eba92011-04-11 00:23:45 +0000108 // [dcl.init.string]p2
109 if (StrLength > CAT->getSize().getZExtValue())
110 S.Diag(Str->getSourceRange().getBegin(),
111 diag::err_initializer_string_for_char_array_too_long)
112 << Str->getSourceRange();
113 } else {
114 // C99 6.7.8p14.
115 if (StrLength-1 > CAT->getSize().getZExtValue())
116 S.Diag(Str->getSourceRange().getBegin(),
117 diag::warn_initializer_string_for_char_array_too_long)
118 << Str->getSourceRange();
119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Eli Friedman893abe42009-05-29 18:22:49 +0000121 // Set the type to the actual size that we are initializing. If we have
122 // something like:
123 // char x[1] = "foo";
124 // then this will set the string literal's type to char[1].
125 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000126}
127
Chris Lattner0cb78032009-02-24 22:27:37 +0000128//===----------------------------------------------------------------------===//
129// Semantic checking for initializer lists.
130//===----------------------------------------------------------------------===//
131
Douglas Gregorcde232f2009-01-29 01:05:33 +0000132/// @brief Semantic checking for initializer lists.
133///
134/// The InitListChecker class contains a set of routines that each
135/// handle the initialization of a certain kind of entity, e.g.,
136/// arrays, vectors, struct/union types, scalars, etc. The
137/// InitListChecker itself performs a recursive walk of the subobject
138/// structure of the type to be initialized, while stepping through
139/// the initializer list one element at a time. The IList and Index
140/// parameters to each of the Check* routines contain the active
141/// (syntactic) initializer list and the index into that initializer
142/// list that represents the current initializer. Each routine is
143/// responsible for moving that Index forward as it consumes elements.
144///
145/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000146/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000147/// initializer list and the index into that initializer list where we
148/// are copying initializers as we map them over to the semantic
149/// list. Once we have completed our recursive walk of the subobject
150/// structure, we will have constructed a full semantic initializer
151/// list.
152///
153/// C99 designators cause changes in the initializer list traversal,
154/// because they make the initialization "jump" into a specific
155/// subobject and then continue the initialization from that
156/// point. CheckDesignatedInitializer() recursively steps into the
157/// designated subobject and manages backing out the recursion to
158/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000159namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000160class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000161 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000162 bool hadError;
163 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
164 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000165
Anders Carlsson6cabf312010-01-23 23:23:01 +0000166 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000167 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000168 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000169 unsigned &StructuredIndex,
170 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000171 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000172 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000173 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000174 unsigned &StructuredIndex,
175 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000178 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000179 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000180 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000181 unsigned &StructuredIndex,
182 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000185 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000186 InitListExpr *StructuredList,
187 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckReferenceType(const InitializedEntity &Entity,
194 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000195 unsigned &Index,
196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000198 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000202 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000203 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000204 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000209 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000210 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000211 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000212 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000216 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
227 QualType CurrentObjectType,
228 InitListExpr *StructuredList,
229 unsigned StructuredIndex,
230 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000236
Douglas Gregor2bb07652009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000245 bool HadError() { return hadError; }
246
247 // @brief Retrieves the fully-structured initializer list used for
248 // semantic analysis and code generation.
249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
250};
Chris Lattner9ececce2009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000252
Douglas Gregor2bb07652009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000260 = InitializedEntity::InitializeMember(Field, &ParentEntity);
261 if (Init >= NumInits || !ILE->getInit(Init)) {
262 // FIXME: We probably don't need to handle references
263 // specially here, since value-initialization of references is
264 // handled in InitializationSequence.
265 if (Field->getType()->isReferenceType()) {
266 // C++ [dcl.init.aggr]p9:
267 // If an incomplete or empty initializer-list leaves a
268 // member of reference type uninitialized, the program is
269 // ill-formed.
270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
271 << Field->getType()
272 << ILE->getSyntacticForm()->getSourceRange();
273 SemaRef.Diag(Field->getLocation(),
274 diag::note_uninit_reference_member);
275 hadError = true;
276 return;
277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
Douglas Gregor2bb07652009-12-22 00:05:34 +0000279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
282 if (!InitSeq) {
283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
284 hadError = true;
285 return;
286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
John McCalldadc5752010-08-24 06:29:42 +0000288 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000290 if (MemberInit.isInvalid()) {
291 hadError = true;
292 return;
293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 if (hadError) {
296 // Do nothing
297 } else if (Init < NumInits) {
298 ILE->setInit(Init, MemberInit.takeAs<Expr>());
299 } else if (InitSeq.getKind()
300 == InitializationSequence::ConstructorInitialization) {
301 // Value-initialization requires a constructor call, so
302 // extend the initializer list to include the constructor
303 // call and make a note that we'll need to take another pass
304 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000305 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000306 RequiresSecondPass = true;
307 }
308 } else if (InitListExpr *InnerILE
309 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310 FillInValueInitializations(MemberEntity, InnerILE,
311 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000312}
313
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000314/// Recursively replaces NULL values within the given initializer list
315/// with expressions that perform value-initialization of the
316/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317void
Douglas Gregor723796a2009-12-16 06:35:08 +0000318InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
319 InitListExpr *ILE,
320 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000321 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000322 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000323 SourceLocation Loc = ILE->getSourceRange().getBegin();
324 if (ILE->getSyntacticForm())
325 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000326
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000327 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 if (RType->getDecl()->isUnion() &&
329 ILE->getInitializedFieldInUnion())
330 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
331 Entity, ILE, RequiresSecondPass);
332 else {
333 unsigned Init = 0;
334 for (RecordDecl::field_iterator
335 Field = RType->getDecl()->field_begin(),
336 FieldEnd = RType->getDecl()->field_end();
337 Field != FieldEnd; ++Field) {
338 if (Field->isUnnamedBitfield())
339 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000340
Douglas Gregor2bb07652009-12-22 00:05:34 +0000341 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000342 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000343
344 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
345 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000346 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000347
Douglas Gregor2bb07652009-12-22 00:05:34 +0000348 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000349
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 // Only look at the first initialization of a union.
351 if (RType->getDecl()->isUnion())
352 break;
353 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000354 }
355
356 return;
Mike Stump11289f42009-09-09 15:08:12 +0000357 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000358
359 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000360
Douglas Gregor723796a2009-12-16 06:35:08 +0000361 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000362 unsigned NumInits = ILE->getNumInits();
363 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000364 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000365 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
367 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000369 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000370 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000371 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000373 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000374 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000375 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000376 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000377
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000378
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000380 if (hadError)
381 return;
382
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000383 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
384 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000385 ElementEntity.setElementIndex(Init);
386
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000387 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000388 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
389 true);
390 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
391 if (!InitSeq) {
392 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000393 hadError = true;
394 return;
395 }
396
John McCalldadc5752010-08-24 06:29:42 +0000397 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000398 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000399 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000400 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000401 return;
402 }
403
404 if (hadError) {
405 // Do nothing
406 } else if (Init < NumInits) {
407 ILE->setInit(Init, ElementInit.takeAs<Expr>());
408 } else if (InitSeq.getKind()
409 == InitializationSequence::ConstructorInitialization) {
410 // Value-initialization requires a constructor call, so
411 // extend the initializer list to include the constructor
412 // call and make a note that we'll need to take another pass
413 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000414 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000415 RequiresSecondPass = true;
416 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000417 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000418 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
419 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000420 }
421}
422
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000423
Douglas Gregor723796a2009-12-16 06:35:08 +0000424InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
425 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000426 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000427 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000428
Eli Friedman23a9e312008-05-19 19:16:24 +0000429 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000430 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000431 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000432 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000434 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000435 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000436
Douglas Gregor723796a2009-12-16 06:35:08 +0000437 if (!hadError) {
438 bool RequiresSecondPass = false;
439 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000440 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000442 RequiresSecondPass);
443 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000444}
445
446int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000447 // FIXME: use a proper constant
448 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000449 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000450 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000451 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
452 }
453 return maxElements;
454}
455
456int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000457 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000458 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000459 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000460 Field = structDecl->field_begin(),
461 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000462 Field != FieldEnd; ++Field) {
463 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
464 ++InitializableMembers;
465 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000466 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000467 return std::min(InitializableMembers, 1);
468 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000469}
470
Anders Carlsson6cabf312010-01-23 23:23:01 +0000471void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000472 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000473 QualType T, unsigned &Index,
474 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000475 unsigned &StructuredIndex,
476 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000477 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000478
Steve Narofff8ecff22008-05-01 22:18:59 +0000479 if (T->isArrayType())
480 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000481 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000482 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000483 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000484 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000485 else
486 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000487
Eli Friedmane0f832b2008-05-25 13:49:22 +0000488 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000489 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000490 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000491 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000492 hadError = true;
493 return;
494 }
495
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000496 // Build a structured initializer list corresponding to this subobject.
497 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000498 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
499 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000500 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
501 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000502 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000503
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000504 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000505 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000507 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000508 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000509 StructuredSubobjectInitIndex,
510 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000511 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000512 StructuredSubobjectInitList->setType(T);
513
Douglas Gregor5741efb2009-03-01 17:12:46 +0000514 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000515 // range corresponds with the end of the last initializer it used.
516 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000517 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000518 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
519 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000521
Tanya Lattner5029d562010-03-07 04:17:15 +0000522 // Warn about missing braces.
523 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000524 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
525 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000526 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000528 "{")
529 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000530 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000531 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000532 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000533}
534
Anders Carlsson6cabf312010-01-23 23:23:01 +0000535void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000536 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000537 unsigned &Index,
538 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000539 unsigned &StructuredIndex,
540 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000541 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000542 SyntacticToSemantic[IList] = StructuredList;
543 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000544 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000545 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000546 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
547 IList->setType(ExprTy);
548 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000549 if (hadError)
550 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000551
Eli Friedman85f54972008-05-25 13:22:35 +0000552 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000553 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000554 if (StructuredIndex == 1 &&
555 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000556 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000557 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000558 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000559 hadError = true;
560 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000561 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000562 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000563 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000564 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000565 // Don't complain for incomplete types, since we'll get an error
566 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000567 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000568 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000569 CurrentObjectType->isArrayType()? 0 :
570 CurrentObjectType->isVectorType()? 1 :
571 CurrentObjectType->isScalarType()? 2 :
572 CurrentObjectType->isUnionType()? 3 :
573 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000574
575 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000576 if (SemaRef.getLangOptions().CPlusPlus) {
577 DK = diag::err_excess_initializers;
578 hadError = true;
579 }
Nate Begeman425038c2009-07-07 21:53:06 +0000580 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
581 DK = diag::err_excess_initializers;
582 hadError = true;
583 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000584
Chris Lattnerb0912a52009-02-24 22:50:46 +0000585 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000586 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000587 }
588 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000589
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000590 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000591 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000592 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000593 << FixItHint::CreateRemoval(IList->getLocStart())
594 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000595}
596
Anders Carlsson6cabf312010-01-23 23:23:01 +0000597void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000598 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000599 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000600 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000601 unsigned &Index,
602 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000603 unsigned &StructuredIndex,
604 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000605 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000606 CheckScalarType(Entity, IList, DeclType, Index,
607 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000608 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000610 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000611 } else if (DeclType->isAggregateType()) {
612 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000613 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000614 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000615 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000616 StructuredList, StructuredIndex,
617 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000618 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000619 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000620 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000621 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000623 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000624 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000625 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000626 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000627 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
628 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000629 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000630 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000631 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000632 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000633 } else if (DeclType->isRecordType()) {
634 // C++ [dcl.init]p14:
635 // [...] If the class is an aggregate (8.5.1), and the initializer
636 // is a brace-enclosed list, see 8.5.1.
637 //
638 // Note: 8.5.1 is handled below; here, we diagnose the case where
639 // we have an initializer list and a destination type that is not
640 // an aggregate.
641 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000642 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000643 << DeclType << IList->getSourceRange();
644 hadError = true;
645 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000646 CheckReferenceType(Entity, IList, DeclType, Index,
647 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000648 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000649 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
650 << DeclType;
651 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000652 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000653 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
654 << DeclType;
655 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000656 }
657}
658
Anders Carlsson6cabf312010-01-23 23:23:01 +0000659void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000660 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000661 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000662 unsigned &Index,
663 InitListExpr *StructuredList,
664 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000665 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000666 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
667 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000668 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000669 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000670 = getStructuredSubobjectInit(IList, Index, ElemType,
671 StructuredList, StructuredIndex,
672 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000673 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000674 newStructuredList, newStructuredIndex);
675 ++StructuredIndex;
676 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000677 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000678 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000679 return CheckScalarType(Entity, IList, ElemType, Index,
680 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000681 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000682 return CheckReferenceType(Entity, IList, ElemType, Index,
683 StructuredList, StructuredIndex);
684 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000685
John McCall5decec92011-02-21 07:57:55 +0000686 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
687 // arrayType can be incomplete if we're initializing a flexible
688 // array member. There's nothing we can do with the completed
689 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
John McCall5decec92011-02-21 07:57:55 +0000691 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
692 CheckStringInit(Str, ElemType, arrayType, SemaRef);
693 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000694 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000695 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000696 }
John McCall5decec92011-02-21 07:57:55 +0000697
698 // Fall through for subaggregate initialization.
699
700 } else if (SemaRef.getLangOptions().CPlusPlus) {
701 // C++ [dcl.init.aggr]p12:
702 // All implicit type conversions (clause 4) are considered when
703 // initializing the aggregate member with an ini- tializer from
704 // an initializer-list. If the initializer can initialize a
705 // member, the member is initialized. [...]
706
707 // FIXME: Better EqualLoc?
708 InitializationKind Kind =
709 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
710 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
711
712 if (Seq) {
713 ExprResult Result =
714 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
715 if (Result.isInvalid())
716 hadError = true;
717
718 UpdateStructuredListElement(StructuredList, StructuredIndex,
719 Result.takeAs<Expr>());
720 ++Index;
721 return;
722 }
723
724 // Fall through for subaggregate initialization
725 } else {
726 // C99 6.7.8p13:
727 //
728 // The initializer for a structure or union object that has
729 // automatic storage duration shall be either an initializer
730 // list as described below, or a single expression that has
731 // compatible structure or union type. In the latter case, the
732 // initial value of the object, including unnamed members, is
733 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000734 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000735 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000736 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000737 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000738 if (ExprRes.isInvalid())
739 hadError = true;
740 else {
741 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
742 if (ExprRes.isInvalid())
743 hadError = true;
744 }
745 UpdateStructuredListElement(StructuredList, StructuredIndex,
746 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000747 ++Index;
748 return;
749 }
John Wiegley01296292011-04-08 18:41:53 +0000750 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000751 // Fall through for subaggregate initialization
752 }
753
754 // C++ [dcl.init.aggr]p12:
755 //
756 // [...] Otherwise, if the member is itself a non-empty
757 // subaggregate, brace elision is assumed and the initializer is
758 // considered for the initialization of the first member of
759 // the subaggregate.
760 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
761 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
762 StructuredIndex);
763 ++StructuredIndex;
764 } else {
765 // We cannot initialize this element, so let
766 // PerformCopyInitialization produce the appropriate diagnostic.
767 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
768 SemaRef.Owned(expr));
769 hadError = true;
770 ++Index;
771 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000772 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000773}
774
Anders Carlsson6cabf312010-01-23 23:23:01 +0000775void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000776 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000777 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000778 InitListExpr *StructuredList,
779 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000780 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000781 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000782 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000783 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000784 ++Index;
785 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000786 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000787 }
John McCall643169b2010-11-11 00:46:36 +0000788
789 Expr *expr = IList->getInit(Index);
790 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
791 SemaRef.Diag(SubIList->getLocStart(),
792 diag::warn_many_braces_around_scalar_init)
793 << SubIList->getSourceRange();
794
795 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
796 StructuredIndex);
797 return;
798 } else if (isa<DesignatedInitExpr>(expr)) {
799 SemaRef.Diag(expr->getSourceRange().getBegin(),
800 diag::err_designator_for_scalar_init)
801 << DeclType << expr->getSourceRange();
802 hadError = true;
803 ++Index;
804 ++StructuredIndex;
805 return;
806 }
807
808 ExprResult Result =
809 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
810 SemaRef.Owned(expr));
811
812 Expr *ResultExpr = 0;
813
814 if (Result.isInvalid())
815 hadError = true; // types weren't compatible.
816 else {
817 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818
John McCall643169b2010-11-11 00:46:36 +0000819 if (ResultExpr != expr) {
820 // The type was promoted, update initializer list.
821 IList->setInit(Index, ResultExpr);
822 }
823 }
824 if (hadError)
825 ++StructuredIndex;
826 else
827 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
828 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000829}
830
Anders Carlsson6cabf312010-01-23 23:23:01 +0000831void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
832 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000833 unsigned &Index,
834 InitListExpr *StructuredList,
835 unsigned &StructuredIndex) {
836 if (Index < IList->getNumInits()) {
837 Expr *expr = IList->getInit(Index);
838 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000839 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000840 << DeclType << IList->getSourceRange();
841 hadError = true;
842 ++Index;
843 ++StructuredIndex;
844 return;
Mike Stump11289f42009-09-09 15:08:12 +0000845 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000846
John McCalldadc5752010-08-24 06:29:42 +0000847 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000848 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
849 SemaRef.Owned(expr));
850
851 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000852 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000853
854 expr = Result.takeAs<Expr>();
855 IList->setInit(Index, expr);
856
Douglas Gregord14247a2009-01-30 22:09:00 +0000857 if (hadError)
858 ++StructuredIndex;
859 else
860 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
861 ++Index;
862 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000863 // FIXME: It would be wonderful if we could point at the actual member. In
864 // general, it would be useful to pass location information down the stack,
865 // so that we know the location (or decl) of the "current object" being
866 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000867 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000868 diag::err_init_reference_member_uninitialized)
869 << DeclType
870 << IList->getSourceRange();
871 hadError = true;
872 ++Index;
873 ++StructuredIndex;
874 return;
875 }
876}
877
Anders Carlsson6cabf312010-01-23 23:23:01 +0000878void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000879 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000880 unsigned &Index,
881 InitListExpr *StructuredList,
882 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000883 if (Index >= IList->getNumInits())
884 return;
Mike Stump11289f42009-09-09 15:08:12 +0000885
John McCall6a16b2f2010-10-30 00:11:39 +0000886 const VectorType *VT = DeclType->getAs<VectorType>();
887 unsigned maxElements = VT->getNumElements();
888 unsigned numEltsInit = 0;
889 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000890
John McCall6a16b2f2010-10-30 00:11:39 +0000891 if (!SemaRef.getLangOptions().OpenCL) {
892 // If the initializing element is a vector, try to copy-initialize
893 // instead of breaking it apart (which is doomed to failure anyway).
894 Expr *Init = IList->getInit(Index);
895 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
896 ExprResult Result =
897 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
898 SemaRef.Owned(Init));
899
900 Expr *ResultExpr = 0;
901 if (Result.isInvalid())
902 hadError = true; // types weren't compatible.
903 else {
904 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000905
John McCall6a16b2f2010-10-30 00:11:39 +0000906 if (ResultExpr != Init) {
907 // The type was promoted, update initializer list.
908 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000909 }
910 }
John McCall6a16b2f2010-10-30 00:11:39 +0000911 if (hadError)
912 ++StructuredIndex;
913 else
914 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
915 ++Index;
916 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000917 }
Mike Stump11289f42009-09-09 15:08:12 +0000918
John McCall6a16b2f2010-10-30 00:11:39 +0000919 InitializedEntity ElementEntity =
920 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000921
John McCall6a16b2f2010-10-30 00:11:39 +0000922 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
923 // Don't attempt to go past the end of the init list
924 if (Index >= IList->getNumInits())
925 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000926
John McCall6a16b2f2010-10-30 00:11:39 +0000927 ElementEntity.setElementIndex(Index);
928 CheckSubElementType(ElementEntity, IList, elementType, Index,
929 StructuredList, StructuredIndex);
930 }
931 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000932 }
John McCall6a16b2f2010-10-30 00:11:39 +0000933
934 InitializedEntity ElementEntity =
935 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936
John McCall6a16b2f2010-10-30 00:11:39 +0000937 // OpenCL initializers allows vectors to be constructed from vectors.
938 for (unsigned i = 0; i < maxElements; ++i) {
939 // Don't attempt to go past the end of the init list
940 if (Index >= IList->getNumInits())
941 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000942
John McCall6a16b2f2010-10-30 00:11:39 +0000943 ElementEntity.setElementIndex(Index);
944
945 QualType IType = IList->getInit(Index)->getType();
946 if (!IType->isVectorType()) {
947 CheckSubElementType(ElementEntity, IList, elementType, Index,
948 StructuredList, StructuredIndex);
949 ++numEltsInit;
950 } else {
951 QualType VecType;
952 const VectorType *IVT = IType->getAs<VectorType>();
953 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954
John McCall6a16b2f2010-10-30 00:11:39 +0000955 if (IType->isExtVectorType())
956 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
957 else
958 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000959 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000960 CheckSubElementType(ElementEntity, IList, VecType, Index,
961 StructuredList, StructuredIndex);
962 numEltsInit += numIElts;
963 }
964 }
965
966 // OpenCL requires all elements to be initialized.
967 if (numEltsInit != maxElements)
968 if (SemaRef.getLangOptions().OpenCL)
969 SemaRef.Diag(IList->getSourceRange().getBegin(),
970 diag::err_vector_incorrect_num_initializers)
971 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000972}
973
Anders Carlsson6cabf312010-01-23 23:23:01 +0000974void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000975 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000976 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000977 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000978 unsigned &Index,
979 InitListExpr *StructuredList,
980 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000981 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
982
Steve Narofff8ecff22008-05-01 22:18:59 +0000983 // Check for the special-case of initializing an array with a string.
984 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +0000985 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000986 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +0000987 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000988 // We place the string literal directly into the resulting
989 // initializer list. This is the only place where the structure
990 // of the structured initializer list doesn't match exactly,
991 // because doing so would involve allocating one character
992 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000993 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000994 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000995 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000996 return;
997 }
998 }
John McCall66884dd2011-02-21 07:22:22 +0000999 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001000 // Check for VLAs; in standard C it would be possible to check this
1001 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1002 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001003 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001004 diag::err_variable_object_no_init)
1005 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001006 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001007 ++Index;
1008 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001009 return;
1010 }
1011
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001012 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001013 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1014 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001015 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001016 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001017 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001018 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001019 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001020 maxElementsKnown = true;
1021 }
1022
John McCall66884dd2011-02-21 07:22:22 +00001023 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001024 while (Index < IList->getNumInits()) {
1025 Expr *Init = IList->getInit(Index);
1026 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001027 // If we're not the subobject that matches up with the '{' for
1028 // the designator, we shouldn't be handling the
1029 // designator. Return immediately.
1030 if (!SubobjectIsDesignatorContext)
1031 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001032
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001033 // Handle this designated initializer. elementIndex will be
1034 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001035 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001036 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001037 StructuredList, StructuredIndex, true,
1038 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001039 hadError = true;
1040 continue;
1041 }
1042
Douglas Gregor033d1252009-01-23 16:54:12 +00001043 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001044 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001045 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001046 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001047 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001048
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001049 // If the array is of incomplete type, keep track of the number of
1050 // elements in the initializer.
1051 if (!maxElementsKnown && elementIndex > maxElements)
1052 maxElements = elementIndex;
1053
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001054 continue;
1055 }
1056
1057 // If we know the maximum number of elements, and we've already
1058 // hit it, stop consuming elements in the initializer list.
1059 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001060 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001061
Anders Carlsson6cabf312010-01-23 23:23:01 +00001062 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001063 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001064 Entity);
1065 // Check this element.
1066 CheckSubElementType(ElementEntity, IList, elementType, Index,
1067 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001068 ++elementIndex;
1069
1070 // If the array is of incomplete type, keep track of the number of
1071 // elements in the initializer.
1072 if (!maxElementsKnown && elementIndex > maxElements)
1073 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001074 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001075 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001076 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001077 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001078 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001079 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001080 // Sizing an array implicitly to zero is not allowed by ISO C,
1081 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001082 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001083 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001084 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001085
Mike Stump11289f42009-09-09 15:08:12 +00001086 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001087 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001088 }
1089}
1090
Anders Carlsson6cabf312010-01-23 23:23:01 +00001091void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001092 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001093 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001094 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001095 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001096 unsigned &Index,
1097 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001098 unsigned &StructuredIndex,
1099 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001100 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001101
Eli Friedman23a9e312008-05-19 19:16:24 +00001102 // If the record is invalid, some of it's members are invalid. To avoid
1103 // confusion, we forgo checking the intializer for the entire record.
1104 if (structDecl->isInvalidDecl()) {
1105 hadError = true;
1106 return;
Mike Stump11289f42009-09-09 15:08:12 +00001107 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001108
1109 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1110 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001111 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001112 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001113 Field != FieldEnd; ++Field) {
1114 if (Field->getDeclName()) {
1115 StructuredList->setInitializedFieldInUnion(*Field);
1116 break;
1117 }
1118 }
1119 return;
1120 }
1121
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001122 // If structDecl is a forward declaration, this loop won't do
1123 // anything except look at designated initializers; That's okay,
1124 // because an error should get printed out elsewhere. It might be
1125 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001126 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001127 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001128 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001129 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001130 while (Index < IList->getNumInits()) {
1131 Expr *Init = IList->getInit(Index);
1132
1133 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001134 // If we're not the subobject that matches up with the '{' for
1135 // the designator, we shouldn't be handling the
1136 // designator. Return immediately.
1137 if (!SubobjectIsDesignatorContext)
1138 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001139
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001140 // Handle this designated initializer. Field will be updated to
1141 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001142 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001143 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001144 StructuredList, StructuredIndex,
1145 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 hadError = true;
1147
Douglas Gregora9add4e2009-02-12 19:00:39 +00001148 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001149
1150 // Disable check for missing fields when designators are used.
1151 // This matches gcc behaviour.
1152 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001153 continue;
1154 }
1155
1156 if (Field == FieldEnd) {
1157 // We've run out of fields. We're done.
1158 break;
1159 }
1160
Douglas Gregora9add4e2009-02-12 19:00:39 +00001161 // We've already initialized a member of a union. We're done.
1162 if (InitializedSomething && DeclType->isUnionType())
1163 break;
1164
Douglas Gregor91f84212008-12-11 16:49:14 +00001165 // If we've hit the flexible array member at the end, we're done.
1166 if (Field->getType()->isIncompleteArrayType())
1167 break;
1168
Douglas Gregor51695702009-01-29 16:53:55 +00001169 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001170 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001171 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001172 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001173 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001174
Anders Carlsson6cabf312010-01-23 23:23:01 +00001175 InitializedEntity MemberEntity =
1176 InitializedEntity::InitializeMember(*Field, &Entity);
1177 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1178 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001179 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001180
1181 if (DeclType->isUnionType()) {
1182 // Initialize the first field within the union.
1183 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001184 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185
1186 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001187 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001188
John McCalle40b58e2010-03-11 19:32:38 +00001189 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001190 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001191 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1192 // It is possible we have one or more unnamed bitfields remaining.
1193 // Find first (if any) named field and emit warning.
1194 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1195 it != end; ++it) {
1196 if (!it->isUnnamedBitfield()) {
1197 SemaRef.Diag(IList->getSourceRange().getEnd(),
1198 diag::warn_missing_field_initializers) << it->getName();
1199 break;
1200 }
1201 }
1202 }
1203
Mike Stump11289f42009-09-09 15:08:12 +00001204 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001205 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001206 return;
1207
1208 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001209 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001210 (!isa<InitListExpr>(IList->getInit(Index)) ||
1211 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001212 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001213 diag::err_flexible_array_init_nonempty)
1214 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001215 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001216 << *Field;
1217 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001218 ++Index;
1219 return;
1220 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001221 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001222 diag::ext_flexible_array_init)
1223 << IList->getInit(Index)->getSourceRange().getBegin();
1224 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1225 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001226 }
1227
Anders Carlsson6cabf312010-01-23 23:23:01 +00001228 InitializedEntity MemberEntity =
1229 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230
Anders Carlsson6cabf312010-01-23 23:23:01 +00001231 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001232 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001233 StructuredList, StructuredIndex);
1234 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001235 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001236 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001237}
Steve Narofff8ecff22008-05-01 22:18:59 +00001238
Douglas Gregord5846a12009-04-15 06:41:24 +00001239/// \brief Expand a field designator that refers to a member of an
1240/// anonymous struct or union into a series of field designators that
1241/// refers to the field within the appropriate subobject.
1242///
Douglas Gregord5846a12009-04-15 06:41:24 +00001243static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001244 DesignatedInitExpr *DIE,
1245 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001246 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001247 typedef DesignatedInitExpr::Designator Designator;
1248
Douglas Gregord5846a12009-04-15 06:41:24 +00001249 // Build the replacement designators.
1250 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001251 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1252 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1253 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001254 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001255 DIE->getDesignator(DesigIdx)->getDotLoc(),
1256 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1257 else
1258 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1259 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001260 assert(isa<FieldDecl>(*PI));
1261 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001262 }
1263
1264 // Expand the current designator into the set of replacement
1265 // designators, so we have a full subobject path down to where the
1266 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001267 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001268 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001269}
Mike Stump11289f42009-09-09 15:08:12 +00001270
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001271/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001272/// corresponds to FieldName.
1273static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1274 IdentifierInfo *FieldName) {
1275 assert(AnonField->isAnonymousStructOrUnion());
1276 Decl *NextDecl = AnonField->getNextDeclInContext();
1277 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1278 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1279 return IF;
1280 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001281 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001282 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001283}
1284
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001285/// @brief Check the well-formedness of a C99 designated initializer.
1286///
1287/// Determines whether the designated initializer @p DIE, which
1288/// resides at the given @p Index within the initializer list @p
1289/// IList, is well-formed for a current object of type @p DeclType
1290/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001291/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001292/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001293///
1294/// @param IList The initializer list in which this designated
1295/// initializer occurs.
1296///
Douglas Gregora5324162009-04-15 04:56:10 +00001297/// @param DIE The designated initializer expression.
1298///
1299/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001300///
1301/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1302/// into which the designation in @p DIE should refer.
1303///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001304/// @param NextField If non-NULL and the first designator in @p DIE is
1305/// a field, this will be set to the field declaration corresponding
1306/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001307///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001308/// @param NextElementIndex If non-NULL and the first designator in @p
1309/// DIE is an array designator or GNU array-range designator, this
1310/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001311///
1312/// @param Index Index into @p IList where the designated initializer
1313/// @p DIE occurs.
1314///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001315/// @param StructuredList The initializer list expression that
1316/// describes all of the subobject initializers in the order they'll
1317/// actually be initialized.
1318///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001319/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001320bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001321InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001322 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001323 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001324 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001325 QualType &CurrentObjectType,
1326 RecordDecl::field_iterator *NextField,
1327 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001328 unsigned &Index,
1329 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001330 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001331 bool FinishSubobjectInit,
1332 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001333 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001334 // Check the actual initialization for the designated object type.
1335 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001336
1337 // Temporarily remove the designator expression from the
1338 // initializer list that the child calls see, so that we don't try
1339 // to re-process the designator.
1340 unsigned OldIndex = Index;
1341 IList->setInit(OldIndex, DIE->getInit());
1342
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001343 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001344 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001345
1346 // Restore the designated initializer expression in the syntactic
1347 // form of the initializer list.
1348 if (IList->getInit(OldIndex) != DIE->getInit())
1349 DIE->setInit(IList->getInit(OldIndex));
1350 IList->setInit(OldIndex, DIE);
1351
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001352 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001353 }
1354
Douglas Gregora5324162009-04-15 04:56:10 +00001355 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001356 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001357 "Need a non-designated initializer list to start from");
1358
Douglas Gregora5324162009-04-15 04:56:10 +00001359 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001360 // Determine the structural initializer list that corresponds to the
1361 // current subobject.
1362 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001363 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001364 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001365 SourceRange(D->getStartLocation(),
1366 DIE->getSourceRange().getEnd()));
1367 assert(StructuredList && "Expected a structured initializer list");
1368
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001369 if (D->isFieldDesignator()) {
1370 // C99 6.7.8p7:
1371 //
1372 // If a designator has the form
1373 //
1374 // . identifier
1375 //
1376 // then the current object (defined below) shall have
1377 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001378 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001379 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001380 if (!RT) {
1381 SourceLocation Loc = D->getDotLoc();
1382 if (Loc.isInvalid())
1383 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001384 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1385 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001386 ++Index;
1387 return true;
1388 }
1389
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001390 // Note: we perform a linear search of the fields here, despite
1391 // the fact that we have a faster lookup method, because we always
1392 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001393 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001394 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001395 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001396 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001397 Field = RT->getDecl()->field_begin(),
1398 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001399 for (; Field != FieldEnd; ++Field) {
1400 if (Field->isUnnamedBitfield())
1401 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001402
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001403 // If we find a field representing an anonymous field, look in the
1404 // IndirectFieldDecl that follow for the designated initializer.
1405 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1406 if (IndirectFieldDecl *IF =
1407 FindIndirectFieldDesignator(*Field, FieldName)) {
1408 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1409 D = DIE->getDesignator(DesigIdx);
1410 break;
1411 }
1412 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001413 if (KnownField && KnownField == *Field)
1414 break;
1415 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001416 break;
1417
1418 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001419 }
1420
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001421 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001422 // There was no normal field in the struct with the designated
1423 // name. Perform another lookup for this name, which may find
1424 // something that we can't designate (e.g., a member function),
1425 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001426 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001427 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001428 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001429 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001430 // Name lookup didn't find anything. Determine whether this
1431 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001432 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001433 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001434 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001436 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001437 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001438 ->Equals(RT->getDecl())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001439 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001440 diag::err_field_designator_unknown_suggest)
1441 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001442 << FixItHint::CreateReplacement(D->getFieldLoc(),
1443 R.getLookupName().getAsString());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001444 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregor6da83622010-01-07 00:17:44 +00001445 diag::note_previous_decl)
1446 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001447 } else {
1448 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1449 << FieldName << CurrentObjectType;
1450 ++Index;
1451 return true;
1452 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001454
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001455 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001456 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001457 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001458 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001459 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001460 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001461 ++Index;
1462 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001463 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001464
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001465 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001466 // The replacement field comes from typo correction; find it
1467 // in the list of fields.
1468 FieldIndex = 0;
1469 Field = RT->getDecl()->field_begin();
1470 for (; Field != FieldEnd; ++Field) {
1471 if (Field->isUnnamedBitfield())
1472 continue;
1473
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001474 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001475 Field->getIdentifier() == ReplacementField->getIdentifier())
1476 break;
1477
1478 ++FieldIndex;
1479 }
1480 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001481 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001482
1483 // All of the fields of a union are located at the same place in
1484 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001485 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001486 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001487 StructuredList->setInitializedFieldInUnion(*Field);
1488 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001489
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001490 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001491 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001492
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001493 // Make sure that our non-designated initializer list has space
1494 // for a subobject corresponding to this field.
1495 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001496 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001497
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001498 // This designator names a flexible array member.
1499 if (Field->getType()->isIncompleteArrayType()) {
1500 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001501 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001502 // We can't designate an object within the flexible array
1503 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001504 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001505 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001506 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001507 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001508 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001509 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001510 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001511 << *Field;
1512 Invalid = true;
1513 }
1514
Chris Lattner001b29c2010-10-10 17:49:49 +00001515 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1516 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001517 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001518 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001519 diag::err_flexible_array_init_needs_braces)
1520 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001521 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001522 << *Field;
1523 Invalid = true;
1524 }
1525
1526 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001527 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001528 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001529 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001530 diag::err_flexible_array_init_nonempty)
1531 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001532 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001533 << *Field;
1534 Invalid = true;
1535 }
1536
1537 if (Invalid) {
1538 ++Index;
1539 return true;
1540 }
1541
1542 // Initialize the array.
1543 bool prevHadError = hadError;
1544 unsigned newStructuredIndex = FieldIndex;
1545 unsigned OldIndex = Index;
1546 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001547
1548 InitializedEntity MemberEntity =
1549 InitializedEntity::InitializeMember(*Field, &Entity);
1550 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001551 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001552
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001553 IList->setInit(OldIndex, DIE);
1554 if (hadError && !prevHadError) {
1555 ++Field;
1556 ++FieldIndex;
1557 if (NextField)
1558 *NextField = Field;
1559 StructuredIndex = FieldIndex;
1560 return true;
1561 }
1562 } else {
1563 // Recurse to check later designated subobjects.
1564 QualType FieldType = (*Field)->getType();
1565 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001567 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001568 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001569 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1570 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001571 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001572 true, false))
1573 return true;
1574 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001575
1576 // Find the position of the next field to be initialized in this
1577 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001578 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001579 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001580
1581 // If this the first designator, our caller will continue checking
1582 // the rest of this struct/class/union subobject.
1583 if (IsFirstDesignator) {
1584 if (NextField)
1585 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001586 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001587 return false;
1588 }
1589
Douglas Gregor17bd0942009-01-28 23:36:17 +00001590 if (!FinishSubobjectInit)
1591 return false;
1592
Douglas Gregord5846a12009-04-15 06:41:24 +00001593 // We've already initialized something in the union; we're done.
1594 if (RT->getDecl()->isUnion())
1595 return hadError;
1596
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001597 // Check the remaining fields within this class/struct/union subobject.
1598 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599
Anders Carlsson6cabf312010-01-23 23:23:01 +00001600 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001601 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001602 return hadError && !prevHadError;
1603 }
1604
1605 // C99 6.7.8p6:
1606 //
1607 // If a designator has the form
1608 //
1609 // [ constant-expression ]
1610 //
1611 // then the current object (defined below) shall have array
1612 // type and the expression shall be an integer constant
1613 // expression. If the array is of unknown size, any
1614 // nonnegative value is valid.
1615 //
1616 // Additionally, cope with the GNU extension that permits
1617 // designators of the form
1618 //
1619 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001620 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001621 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001622 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001623 << CurrentObjectType;
1624 ++Index;
1625 return true;
1626 }
1627
1628 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001629 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1630 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001631 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001632 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001633 DesignatedEndIndex = DesignatedStartIndex;
1634 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001635 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001636
Mike Stump11289f42009-09-09 15:08:12 +00001637 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001638 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001639 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001640 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001641 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001642
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001643 // Codegen can't handle evaluating array range designators that have side
1644 // effects, because we replicate the AST value for each initialized element.
1645 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1646 // elements with something that has a side effect, so codegen can emit an
1647 // "error unsupported" error instead of miscompiling the app.
1648 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1649 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001650 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001651 }
1652
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001653 if (isa<ConstantArrayType>(AT)) {
1654 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001655 DesignatedStartIndex
1656 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001657 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001658 DesignatedEndIndex
1659 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001660 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1661 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001662 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001663 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001664 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001665 << IndexExpr->getSourceRange();
1666 ++Index;
1667 return true;
1668 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001669 } else {
1670 // Make sure the bit-widths and signedness match.
1671 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001672 DesignatedEndIndex
1673 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001674 else if (DesignatedStartIndex.getBitWidth() <
1675 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001676 DesignatedStartIndex
1677 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001678 DesignatedStartIndex.setIsUnsigned(true);
1679 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001680 }
Mike Stump11289f42009-09-09 15:08:12 +00001681
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001682 // Make sure that our non-designated initializer list has space
1683 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001684 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001685 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001686 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001687
Douglas Gregor17bd0942009-01-28 23:36:17 +00001688 // Repeatedly perform subobject initializations in the range
1689 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001690
Douglas Gregor17bd0942009-01-28 23:36:17 +00001691 // Move to the next designator
1692 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1693 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001694
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001695 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001696 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001697
Douglas Gregor17bd0942009-01-28 23:36:17 +00001698 while (DesignatedStartIndex <= DesignatedEndIndex) {
1699 // Recurse to check later designated subobjects.
1700 QualType ElementType = AT->getElementType();
1701 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001703 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1705 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001706 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001707 (DesignatedStartIndex == DesignatedEndIndex),
1708 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001709 return true;
1710
1711 // Move to the next index in the array that we'll be initializing.
1712 ++DesignatedStartIndex;
1713 ElementIndex = DesignatedStartIndex.getZExtValue();
1714 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001715
1716 // If this the first designator, our caller will continue checking
1717 // the rest of this array subobject.
1718 if (IsFirstDesignator) {
1719 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001720 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001721 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001722 return false;
1723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
Douglas Gregor17bd0942009-01-28 23:36:17 +00001725 if (!FinishSubobjectInit)
1726 return false;
1727
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001728 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001729 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001730 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001731 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001732 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001733 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001734}
1735
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001736// Get the structured initializer list for a subobject of type
1737// @p CurrentObjectType.
1738InitListExpr *
1739InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1740 QualType CurrentObjectType,
1741 InitListExpr *StructuredList,
1742 unsigned StructuredIndex,
1743 SourceRange InitRange) {
1744 Expr *ExistingInit = 0;
1745 if (!StructuredList)
1746 ExistingInit = SyntacticToSemantic[IList];
1747 else if (StructuredIndex < StructuredList->getNumInits())
1748 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001749
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001750 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1751 return Result;
1752
1753 if (ExistingInit) {
1754 // We are creating an initializer list that initializes the
1755 // subobjects of the current object, but there was already an
1756 // initialization that completely initialized the current
1757 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001758 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001759 // struct X { int a, b; };
1760 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001761 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001762 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1763 // designated initializer re-initializes the whole
1764 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001765 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001766 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001767 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001768 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001770 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001771 << ExistingInit->getSourceRange();
1772 }
1773
Mike Stump11289f42009-09-09 15:08:12 +00001774 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001775 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1776 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001777 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001778
Douglas Gregora8a089b2010-07-13 18:40:04 +00001779 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001780
Douglas Gregor6d00c992009-03-20 23:58:33 +00001781 // Pre-allocate storage for the structured initializer list.
1782 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001783 unsigned NumInits = 0;
1784 if (!StructuredList)
1785 NumInits = IList->getNumInits();
1786 else if (Index < IList->getNumInits()) {
1787 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1788 NumInits = SubList->getNumInits();
1789 }
1790
Mike Stump11289f42009-09-09 15:08:12 +00001791 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001792 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1793 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1794 NumElements = CAType->getSize().getZExtValue();
1795 // Simple heuristic so that we don't allocate a very large
1796 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001797 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001798 NumElements = 0;
1799 }
John McCall9dd450b2009-09-21 23:43:11 +00001800 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001801 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001802 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001803 RecordDecl *RDecl = RType->getDecl();
1804 if (RDecl->isUnion())
1805 NumElements = 1;
1806 else
Mike Stump11289f42009-09-09 15:08:12 +00001807 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001808 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001809 }
1810
Douglas Gregor221c9a52009-03-21 18:13:52 +00001811 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001812 NumElements = IList->getNumInits();
1813
Ted Kremenekac034612010-04-13 23:39:13 +00001814 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001815
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001816 // Link this new initializer list into the structured initializer
1817 // lists.
1818 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001819 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001820 else {
1821 Result->setSyntacticForm(IList);
1822 SyntacticToSemantic[IList] = Result;
1823 }
1824
1825 return Result;
1826}
1827
1828/// Update the initializer at index @p StructuredIndex within the
1829/// structured initializer list to the value @p expr.
1830void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1831 unsigned &StructuredIndex,
1832 Expr *expr) {
1833 // No structured initializer list to update
1834 if (!StructuredList)
1835 return;
1836
Ted Kremenekac034612010-04-13 23:39:13 +00001837 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1838 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001839 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001840 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001841 diag::warn_initializer_overrides)
1842 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001843 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001844 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001845 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001846 << PrevInit->getSourceRange();
1847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001849 ++StructuredIndex;
1850}
1851
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001852/// Check that the given Index expression is a valid array designator
1853/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001854/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001855/// and produces a reasonable diagnostic if there is a
1856/// failure. Returns true if there was an error, false otherwise. If
1857/// everything went okay, Value will receive the value of the constant
1858/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001859static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001860CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001861 SourceLocation Loc = Index->getSourceRange().getBegin();
1862
1863 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001864 if (S.VerifyIntegerConstantExpression(Index, &Value))
1865 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001866
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001867 if (Value.isSigned() && Value.isNegative())
1868 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001869 << Value.toString(10) << Index->getSourceRange();
1870
Douglas Gregor51650d32009-01-23 21:04:18 +00001871 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001872 return false;
1873}
1874
John McCalldadc5752010-08-24 06:29:42 +00001875ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001876 SourceLocation Loc,
1877 bool GNUSyntax,
1878 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001879 typedef DesignatedInitExpr::Designator ASTDesignator;
1880
1881 bool Invalid = false;
1882 llvm::SmallVector<ASTDesignator, 32> Designators;
1883 llvm::SmallVector<Expr *, 32> InitExpressions;
1884
1885 // Build designators and check array designator expressions.
1886 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1887 const Designator &D = Desig.getDesignator(Idx);
1888 switch (D.getKind()) {
1889 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001890 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001891 D.getFieldLoc()));
1892 break;
1893
1894 case Designator::ArrayDesignator: {
1895 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1896 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001897 if (!Index->isTypeDependent() &&
1898 !Index->isValueDependent() &&
1899 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001900 Invalid = true;
1901 else {
1902 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001903 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001904 D.getRBracketLoc()));
1905 InitExpressions.push_back(Index);
1906 }
1907 break;
1908 }
1909
1910 case Designator::ArrayRangeDesignator: {
1911 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1912 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1913 llvm::APSInt StartValue;
1914 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001915 bool StartDependent = StartIndex->isTypeDependent() ||
1916 StartIndex->isValueDependent();
1917 bool EndDependent = EndIndex->isTypeDependent() ||
1918 EndIndex->isValueDependent();
1919 if ((!StartDependent &&
1920 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1921 (!EndDependent &&
1922 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001923 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001924 else {
1925 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001926 if (StartDependent || EndDependent) {
1927 // Nothing to compute.
1928 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001929 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001930 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001931 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001932
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001933 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001934 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001935 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001936 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1937 Invalid = true;
1938 } else {
1939 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001940 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001941 D.getEllipsisLoc(),
1942 D.getRBracketLoc()));
1943 InitExpressions.push_back(StartIndex);
1944 InitExpressions.push_back(EndIndex);
1945 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001946 }
1947 break;
1948 }
1949 }
1950 }
1951
1952 if (Invalid || Init.isInvalid())
1953 return ExprError();
1954
1955 // Clear out the expressions within the designation.
1956 Desig.ClearExprs(*this);
1957
1958 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001959 = DesignatedInitExpr::Create(Context,
1960 Designators.data(), Designators.size(),
1961 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001962 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
Douglas Gregorc124e592011-01-16 16:13:16 +00001964 if (getLangOptions().CPlusPlus)
1965 Diag(DIE->getLocStart(), diag::ext_designated_init)
1966 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001968 return Owned(DIE);
1969}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001970
Douglas Gregor723796a2009-12-16 06:35:08 +00001971bool Sema::CheckInitList(const InitializedEntity &Entity,
1972 InitListExpr *&InitList, QualType &DeclType) {
1973 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001974 if (!CheckInitList.HadError())
1975 InitList = CheckInitList.getFullyStructuredList();
1976
1977 return CheckInitList.HadError();
1978}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001979
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001980//===----------------------------------------------------------------------===//
1981// Initialization entity
1982//===----------------------------------------------------------------------===//
1983
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00001985 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001987{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001988 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1989 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001990 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001991 } else {
1992 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001993 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001994 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001995}
1996
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001997InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001998 CXXBaseSpecifier *Base,
1999 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002000{
2001 InitializedEntity Result;
2002 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002003 Result.Base = reinterpret_cast<uintptr_t>(Base);
2004 if (IsInheritedVirtualBase)
2005 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006
Douglas Gregor1b303932009-12-22 15:35:07 +00002007 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002008 return Result;
2009}
2010
Douglas Gregor85dabae2009-12-16 01:38:02 +00002011DeclarationName InitializedEntity::getName() const {
2012 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00002013 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002014 if (!VariableOrMember)
2015 return DeclarationName();
2016 // Fall through
2017
2018 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002019 case EK_Member:
2020 return VariableOrMember->getDeclName();
2021
2022 case EK_Result:
2023 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002024 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002025 case EK_Temporary:
2026 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002027 case EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002028 case EK_ArrayElement:
2029 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002030 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002031 return DeclarationName();
2032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033
Douglas Gregor85dabae2009-12-16 01:38:02 +00002034 // Silence GCC warning
2035 return DeclarationName();
2036}
2037
Douglas Gregora4b592a2009-12-19 03:01:41 +00002038DeclaratorDecl *InitializedEntity::getDecl() const {
2039 switch (getKind()) {
2040 case EK_Variable:
2041 case EK_Parameter:
2042 case EK_Member:
2043 return VariableOrMember;
2044
2045 case EK_Result:
2046 case EK_Exception:
2047 case EK_New:
2048 case EK_Temporary:
2049 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002050 case EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002051 case EK_ArrayElement:
2052 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002053 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002054 return 0;
2055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056
Douglas Gregora4b592a2009-12-19 03:01:41 +00002057 // Silence GCC warning
2058 return 0;
2059}
2060
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002061bool InitializedEntity::allowsNRVO() const {
2062 switch (getKind()) {
2063 case EK_Result:
2064 case EK_Exception:
2065 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002067 case EK_Variable:
2068 case EK_Parameter:
2069 case EK_Member:
2070 case EK_New:
2071 case EK_Temporary:
2072 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002073 case EK_Delegation:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002074 case EK_ArrayElement:
2075 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002076 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002077 break;
2078 }
2079
2080 return false;
2081}
2082
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002083//===----------------------------------------------------------------------===//
2084// Initialization sequence
2085//===----------------------------------------------------------------------===//
2086
2087void InitializationSequence::Step::Destroy() {
2088 switch (Kind) {
2089 case SK_ResolveAddressOfOverloadedFunction:
2090 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002091 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002092 case SK_CastDerivedToBaseLValue:
2093 case SK_BindReference:
2094 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002095 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002096 case SK_UserConversion:
2097 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002098 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002099 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002100 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002101 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002102 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002103 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002104 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002105 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002106 case SK_ArrayInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002109 case SK_ConversionSequence:
2110 delete ICS;
2111 }
2112}
2113
Douglas Gregor838fcc32010-03-26 20:14:36 +00002114bool InitializationSequence::isDirectReferenceBinding() const {
2115 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2116}
2117
2118bool InitializationSequence::isAmbiguous() const {
2119 if (getKind() != FailedSequence)
2120 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Douglas Gregor838fcc32010-03-26 20:14:36 +00002122 switch (getFailureKind()) {
2123 case FK_TooManyInitsForReference:
2124 case FK_ArrayNeedsInitList:
2125 case FK_ArrayNeedsInitListOrStringLiteral:
2126 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2127 case FK_NonConstLValueReferenceBindingToTemporary:
2128 case FK_NonConstLValueReferenceBindingToUnrelated:
2129 case FK_RValueReferenceBindingToLValue:
2130 case FK_ReferenceInitDropsQualifiers:
2131 case FK_ReferenceInitFailed:
2132 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002133 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002134 case FK_TooManyInitsForScalar:
2135 case FK_ReferenceBindingToInitList:
2136 case FK_InitListBadDestinationType:
2137 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002138 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002139 case FK_ArrayTypeMismatch:
2140 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002141 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002142
Douglas Gregor838fcc32010-03-26 20:14:36 +00002143 case FK_ReferenceInitOverloadFailed:
2144 case FK_UserConversionOverloadFailed:
2145 case FK_ConstructorOverloadFailed:
2146 return FailedOverloadResult == OR_Ambiguous;
2147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148
Douglas Gregor838fcc32010-03-26 20:14:36 +00002149 return false;
2150}
2151
Douglas Gregorb33eed02010-04-16 22:09:46 +00002152bool InitializationSequence::isConstructorInitialization() const {
2153 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2154}
2155
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002156void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002157 FunctionDecl *Function,
2158 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002159 Step S;
2160 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2161 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002162 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002163 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002164 Steps.push_back(S);
2165}
2166
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002168 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002169 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002170 switch (VK) {
2171 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2172 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2173 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002174 default: llvm_unreachable("No such category");
2175 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002176 S.Type = BaseType;
2177 Steps.push_back(S);
2178}
2179
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002181 bool BindingTemporary) {
2182 Step S;
2183 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2184 S.Type = T;
2185 Steps.push_back(S);
2186}
2187
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002188void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2189 Step S;
2190 S.Kind = SK_ExtraneousCopyToTemporary;
2191 S.Type = T;
2192 Steps.push_back(S);
2193}
2194
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002195void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002196 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002197 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002198 Step S;
2199 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002200 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002201 S.Function.Function = Function;
2202 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002203 Steps.push_back(S);
2204}
2205
2206void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002207 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002208 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002209 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002210 switch (VK) {
2211 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002212 S.Kind = SK_QualificationConversionRValue;
2213 break;
John McCall2536c6d2010-08-25 10:28:54 +00002214 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002215 S.Kind = SK_QualificationConversionXValue;
2216 break;
John McCall2536c6d2010-08-25 10:28:54 +00002217 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002218 S.Kind = SK_QualificationConversionLValue;
2219 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002220 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002221 S.Type = Ty;
2222 Steps.push_back(S);
2223}
2224
2225void InitializationSequence::AddConversionSequenceStep(
2226 const ImplicitConversionSequence &ICS,
2227 QualType T) {
2228 Step S;
2229 S.Kind = SK_ConversionSequence;
2230 S.Type = T;
2231 S.ICS = new ImplicitConversionSequence(ICS);
2232 Steps.push_back(S);
2233}
2234
Douglas Gregor51e77d52009-12-10 17:56:55 +00002235void InitializationSequence::AddListInitializationStep(QualType T) {
2236 Step S;
2237 S.Kind = SK_ListInitialization;
2238 S.Type = T;
2239 Steps.push_back(S);
2240}
2241
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002243InitializationSequence::AddConstructorInitializationStep(
2244 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002245 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002246 QualType T) {
2247 Step S;
2248 S.Kind = SK_ConstructorInitialization;
2249 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002250 S.Function.Function = Constructor;
2251 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002252 Steps.push_back(S);
2253}
2254
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002255void InitializationSequence::AddZeroInitializationStep(QualType T) {
2256 Step S;
2257 S.Kind = SK_ZeroInitialization;
2258 S.Type = T;
2259 Steps.push_back(S);
2260}
2261
Douglas Gregore1314a62009-12-18 05:02:21 +00002262void InitializationSequence::AddCAssignmentStep(QualType T) {
2263 Step S;
2264 S.Kind = SK_CAssignment;
2265 S.Type = T;
2266 Steps.push_back(S);
2267}
2268
Eli Friedman78275202009-12-19 08:11:05 +00002269void InitializationSequence::AddStringInitStep(QualType T) {
2270 Step S;
2271 S.Kind = SK_StringInit;
2272 S.Type = T;
2273 Steps.push_back(S);
2274}
2275
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002276void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2277 Step S;
2278 S.Kind = SK_ObjCObjectConversion;
2279 S.Type = T;
2280 Steps.push_back(S);
2281}
2282
Douglas Gregore2f943b2011-02-22 18:29:51 +00002283void InitializationSequence::AddArrayInitStep(QualType T) {
2284 Step S;
2285 S.Kind = SK_ArrayInit;
2286 S.Type = T;
2287 Steps.push_back(S);
2288}
2289
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002291 OverloadingResult Result) {
2292 SequenceKind = FailedSequence;
2293 this->Failure = Failure;
2294 this->FailedOverloadResult = Result;
2295}
2296
2297//===----------------------------------------------------------------------===//
2298// Attempt initialization
2299//===----------------------------------------------------------------------===//
2300
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301/// \brief Attempt list initialization (C++0x [dcl.init.list])
2302static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002303 const InitializedEntity &Entity,
2304 const InitializationKind &Kind,
2305 InitListExpr *InitList,
2306 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002307 // FIXME: We only perform rudimentary checking of list
2308 // initializations at this point, then assume that any list
2309 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002310 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002311 // do all of the necessary checking. C++0x initializer lists will
2312 // force us to perform more checking here.
2313 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2314
Douglas Gregor1b303932009-12-22 15:35:07 +00002315 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002316
2317 // C++ [dcl.init]p13:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002318 // If T is a scalar type, then a declaration of the form
Douglas Gregor51e77d52009-12-10 17:56:55 +00002319 //
2320 // T x = { a };
2321 //
2322 // is equivalent to
2323 //
2324 // T x = a;
2325 if (DestType->isScalarType()) {
2326 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2327 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2328 return;
2329 }
2330
2331 // Assume scalar initialization from a single value works.
2332 } else if (DestType->isAggregateType()) {
2333 // Assume aggregate initialization works.
2334 } else if (DestType->isVectorType()) {
2335 // Assume vector initialization works.
2336 } else if (DestType->isReferenceType()) {
2337 // FIXME: C++0x defines behavior for this.
2338 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2339 return;
2340 } else if (DestType->isRecordType()) {
2341 // FIXME: C++0x defines behavior for this
2342 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2343 }
2344
2345 // Add a general "list initialization" step.
2346 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002347}
2348
2349/// \brief Try a reference initialization that involves calling a conversion
2350/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002351static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2352 const InitializedEntity &Entity,
2353 const InitializationKind &Kind,
2354 Expr *Initializer,
2355 bool AllowRValues,
2356 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002357 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002358 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2359 QualType T1 = cv1T1.getUnqualifiedType();
2360 QualType cv2T2 = Initializer->getType();
2361 QualType T2 = cv2T2.getUnqualifiedType();
2362
2363 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002364 bool ObjCConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002365 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002366 T1, T2, DerivedToBase,
2367 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002368 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002369 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002370 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002371
2372 // Build the candidate set directly in the initialization sequence
2373 // structure, so that it will persist if we fail.
2374 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2375 CandidateSet.clear();
2376
2377 // Determine whether we are allowed to call explicit constructors or
2378 // explicit conversion operators.
2379 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002380
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002381 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002382 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2383 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002384 // The type we're converting to is a class type. Enumerate its constructors
2385 // to see if there is a suitable conversion.
2386 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002387
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002388 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002389 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002390 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002391 NamedDecl *D = *Con;
2392 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2393
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002394 // Find the constructor (which may be a template).
2395 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002396 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002397 if (ConstructorTmpl)
2398 Constructor = cast<CXXConstructorDecl>(
2399 ConstructorTmpl->getTemplatedDecl());
2400 else
John McCalla0296f72010-03-19 07:35:19 +00002401 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002402
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002403 if (!Constructor->isInvalidDecl() &&
2404 Constructor->isConvertingConstructor(AllowExplicit)) {
2405 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002406 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002407 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002408 &Initializer, 1, CandidateSet,
2409 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002410 else
John McCalla0296f72010-03-19 07:35:19 +00002411 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002412 &Initializer, 1, CandidateSet,
2413 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002415 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002416 }
John McCall3696dcb2010-08-17 07:23:57 +00002417 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2418 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419
Douglas Gregor496e8b342010-05-07 19:42:26 +00002420 const RecordType *T2RecordType = 0;
2421 if ((T2RecordType = T2->getAs<RecordType>()) &&
2422 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002423 // The type we're converting from is a class type, enumerate its conversion
2424 // functions.
2425 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2426
John McCallad371252010-01-20 00:46:10 +00002427 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002428 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002429 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2430 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002431 NamedDecl *D = *I;
2432 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2433 if (isa<UsingShadowDecl>(D))
2434 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002435
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002436 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2437 CXXConversionDecl *Conv;
2438 if (ConvTemplate)
2439 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2440 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002441 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002442
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002443 // If the conversion function doesn't return a reference type,
2444 // it can't be considered for this conversion unless we're allowed to
2445 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002446 // FIXME: Do we need to make sure that we only consider conversion
2447 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002448 // break recursion.
2449 if ((AllowExplicit || !Conv->isExplicit()) &&
2450 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2451 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002452 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002453 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002454 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002455 else
John McCalla0296f72010-03-19 07:35:19 +00002456 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002457 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002458 }
2459 }
2460 }
John McCall3696dcb2010-08-17 07:23:57 +00002461 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2462 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002464 SourceLocation DeclLoc = Initializer->getLocStart();
2465
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002466 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002467 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002469 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002470 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002471
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002472 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002473
Chandler Carruth30141632011-02-25 19:41:05 +00002474 // This is the overload that will actually be used for the initialization, so
2475 // mark it as used.
2476 S.MarkDeclarationReferenced(DeclLoc, Function);
2477
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002478 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002479 if (isa<CXXConversionDecl>(Function))
2480 T2 = Function->getResultType();
2481 else
2482 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002483
2484 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002485 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002486 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002487
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002488 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002489 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002490 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002491 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002492 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002493 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002494 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002495
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002496 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002497 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002498 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002499 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002500 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002501 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002502 if (NewRefRelationship == Sema::Ref_Incompatible) {
2503 // If the type we've converted to is not reference-related to the
2504 // type we're looking for, then there is another conversion step
2505 // we need to perform to produce a temporary of the right type
2506 // that we'll be binding to.
2507 ImplicitConversionSequence ICS;
2508 ICS.setStandard();
2509 ICS.Standard = Best->FinalConversion;
2510 T2 = ICS.Standard.getToType(2);
2511 Sequence.AddConversionSequenceStep(ICS, T2);
2512 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002513 Sequence.AddDerivedToBaseCastStep(
2514 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002516 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002517 else if (NewObjCConversion)
2518 Sequence.AddObjCObjectConversionStep(
2519 S.Context.getQualifiedType(T1,
2520 T2.getNonReferenceType().getQualifiers()));
2521
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002522 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002523 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002525 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2526 return OR_Success;
2527}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002528
2529/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2530static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002531 const InitializedEntity &Entity,
2532 const InitializationKind &Kind,
2533 Expr *Initializer,
2534 InitializationSequence &Sequence) {
2535 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002536
Douglas Gregor1b303932009-12-22 15:35:07 +00002537 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002538 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002539 Qualifiers T1Quals;
2540 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002541 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002542 Qualifiers T2Quals;
2543 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002544 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002545
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002546 // If the initializer is the address of an overloaded function, try
2547 // to resolve the overloaded function. If all goes well, T2 is the
2548 // type of the resulting function.
2549 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002550 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002551 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002552 T1,
2553 false,
2554 Found)) {
2555 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2556 cv2T2 = Fn->getType();
2557 T2 = cv2T2.getUnqualifiedType();
2558 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002559 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2560 return;
2561 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002562 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002563
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002564 // Compute some basic properties of the types and the initializer.
2565 bool isLValueRef = DestType->isLValueReferenceType();
2566 bool isRValueRef = !isLValueRef;
2567 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002568 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002569 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002570 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002571 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2572 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002573
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002574 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002575 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002576 // "cv2 T2" as follows:
2577 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002578 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002579 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002580 // Note the analogous bullet points for rvlaue refs to functions. Because
2581 // there are no function rvalues in C++, rvalue refs to functions are treated
2582 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002583 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002584 bool T1Function = T1->isFunctionType();
2585 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002586 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002587 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002588 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002589 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002590 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002591 // reference-compatible with "cv2 T2," or
2592 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002593 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002594 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002595 // can occur. However, we do pay attention to whether it is a bit-field
2596 // to decide whether we're actually binding to a temporary created from
2597 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002598 if (DerivedToBase)
2599 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002600 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002601 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002602 else if (ObjCConversion)
2603 Sequence.AddObjCObjectConversionStep(
2604 S.Context.getQualifiedType(T1, T2Quals));
2605
Chandler Carruth04bdce62010-01-12 20:32:25 +00002606 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002607 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002608 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002609 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002610 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002611 return;
2612 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002613
2614 // - has a class type (i.e., T2 is a class type), where T1 is not
2615 // reference-related to T2, and can be implicitly converted to an
2616 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2617 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002618 // applicable conversion functions (13.3.1.6) and choosing the best
2619 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002620 // If we have an rvalue ref to function type here, the rhs must be
2621 // an rvalue.
2622 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2623 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002624 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002625 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002626 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002627 Sequence);
2628 if (ConvOvlResult == OR_Success)
2629 return;
John McCall0d1da222010-01-12 00:44:57 +00002630 if (ConvOvlResult != OR_No_Viable_Function) {
2631 Sequence.SetOverloadFailure(
2632 InitializationSequence::FK_ReferenceInitOverloadFailed,
2633 ConvOvlResult);
2634 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002635 }
2636 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002639 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002640 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002641 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002642 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2643 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2644 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002645 Sequence.SetOverloadFailure(
2646 InitializationSequence::FK_ReferenceInitOverloadFailed,
2647 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002648 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002649 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002650 ? (RefRelationship == Sema::Ref_Related
2651 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2652 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2653 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002654
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002655 return;
2656 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002657
Douglas Gregor92e460e2011-01-20 16:44:54 +00002658 // - If the initializer expression
2659 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2660 // "cv1 T1" is reference-compatible with "cv2 T2"
2661 // Note: functions are handled below.
2662 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002663 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002665 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002666 (InitCategory.isXValue() ||
2667 (InitCategory.isPRValue() && T2->isRecordType()) ||
2668 (InitCategory.isPRValue() && T2->isArrayType()))) {
2669 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2670 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002671 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2672 // compiler the freedom to perform a copy here or bind to the
2673 // object, while C++0x requires that we bind directly to the
2674 // object. Hence, we always bind to the object without making an
2675 // extra copy. However, in C++03 requires that we check for the
2676 // presence of a suitable copy constructor:
2677 //
2678 // The constructor that would be used to make the copy shall
2679 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002680 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002681 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002683
Douglas Gregor92e460e2011-01-20 16:44:54 +00002684 if (DerivedToBase)
2685 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2686 ValueKind);
2687 else if (ObjCConversion)
2688 Sequence.AddObjCObjectConversionStep(
2689 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002690
Douglas Gregor92e460e2011-01-20 16:44:54 +00002691 if (T1Quals != T2Quals)
2692 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002694 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002697
2698 // - has a class type (i.e., T2 is a class type), where T1 is not
2699 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002700 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2701 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002702 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002703 if (RefRelationship == Sema::Ref_Incompatible) {
2704 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2705 Kind, Initializer,
2706 /*AllowRValues=*/true,
2707 Sequence);
2708 if (ConvOvlResult)
2709 Sequence.SetOverloadFailure(
2710 InitializationSequence::FK_ReferenceInitOverloadFailed,
2711 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002712
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002713 return;
2714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002716 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2717 return;
2718 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002719
2720 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002721 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002722 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002723 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002724
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002725 // Determine whether we are allowed to call explicit constructors or
2726 // explicit conversion operators.
2727 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002728
2729 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2730
2731 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2732 /*SuppressUserConversions*/ false,
2733 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002734 /*FIXME:InOverloadResolution=*/false,
2735 /*CStyle=*/Kind.isCStyleOrFunctionalCast())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002736 // FIXME: Use the conversion function set stored in ICS to turn
2737 // this into an overloading ambiguity diagnostic. However, we need
2738 // to keep that set as an OverloadCandidateSet rather than as some
2739 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002740 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2741 Sequence.SetOverloadFailure(
2742 InitializationSequence::FK_ReferenceInitOverloadFailed,
2743 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002744 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2745 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002746 else
2747 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002748 return;
2749 }
2750
2751 // [...] If T1 is reference-related to T2, cv1 must be the
2752 // same cv-qualification as, or greater cv-qualification
2753 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002754 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2755 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002756 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002757 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002758 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2759 return;
2760 }
2761
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002762 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002763 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002764 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002765 InitCategory.isLValue()) {
2766 Sequence.SetFailed(
2767 InitializationSequence::FK_RValueReferenceBindingToLValue);
2768 return;
2769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002770
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002771 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2772 return;
2773}
2774
2775/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002776/// (C++ [dcl.init.string], C99 6.7.8).
2777static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002778 const InitializedEntity &Entity,
2779 const InitializationKind &Kind,
2780 Expr *Initializer,
2781 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002782 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002783 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002784}
2785
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002786/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2787/// enumerates the constructors of the initialized entity and performs overload
2788/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002789static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002790 const InitializedEntity &Entity,
2791 const InitializationKind &Kind,
2792 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002793 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002794 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002795 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002796
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002797 // Build the candidate set directly in the initialization sequence
2798 // structure, so that it will persist if we fail.
2799 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2800 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002802 // Determine whether we are allowed to call explicit constructors or
2803 // explicit conversion operators.
2804 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2805 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002806 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002807
2808 // The type we're constructing needs to be complete.
2809 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002810 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002811 return;
2812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002814 // The type we're converting to is a class type. Enumerate its constructors
2815 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002816 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002818 CXXRecordDecl *DestRecordDecl
2819 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002820
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002821 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002822 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002823 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002824 NamedDecl *D = *Con;
2825 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002826 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002827
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002828 // Find the constructor (which may be a template).
2829 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002830 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002831 if (ConstructorTmpl)
2832 Constructor = cast<CXXConstructorDecl>(
2833 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002834 else {
John McCalla0296f72010-03-19 07:35:19 +00002835 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002836
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002837 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00002838 // suppress user-defined conversions on the arguments.
2839 // FIXME: Move constructors?
2840 if (Kind.getKind() == InitializationKind::IK_Copy &&
2841 Constructor->isCopyConstructor())
2842 SuppressUserConversions = true;
2843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002844
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002845 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002846 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002847 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002848 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002849 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002850 Args, NumArgs, CandidateSet,
2851 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002852 else
John McCalla0296f72010-03-19 07:35:19 +00002853 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002854 Args, NumArgs, CandidateSet,
2855 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002856 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857 }
2858
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002859 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002860
2861 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002862 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002864 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002865 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002867 Result);
2868 return;
2869 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002870
2871 // C++0x [dcl.init]p6:
2872 // If a program calls for the default initialization of an object
2873 // of a const-qualified type T, T shall be a class type with a
2874 // user-provided default constructor.
2875 if (Kind.getKind() == InitializationKind::IK_Default &&
2876 Entity.getType().isConstQualified() &&
2877 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2878 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2879 return;
2880 }
2881
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002882 // Add the constructor initialization step. Any cv-qualification conversion is
2883 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002884 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002886 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002887 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002888}
2889
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002890/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002891static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002892 const InitializedEntity &Entity,
2893 const InitializationKind &Kind,
2894 InitializationSequence &Sequence) {
2895 // C++ [dcl.init]p5:
2896 //
2897 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002898 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002899
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002900 // -- if T is an array type, then each element is value-initialized;
2901 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2902 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002903
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002904 if (const RecordType *RT = T->getAs<RecordType>()) {
2905 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2906 // -- if T is a class type (clause 9) with a user-declared
2907 // constructor (12.1), then the default constructor for T is
2908 // called (and the initialization is ill-formed if T has no
2909 // accessible default constructor);
2910 //
2911 // FIXME: we really want to refer to a single subobject of the array,
2912 // but Entity doesn't have a way to capture that (yet).
2913 if (ClassDecl->hasUserDeclaredConstructor())
2914 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002916 // -- if T is a (possibly cv-qualified) non-union class type
2917 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002918 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002919 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002920 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002921 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002922 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002923 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002924 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002925 }
2926 }
2927
Douglas Gregor1b303932009-12-22 15:35:07 +00002928 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002929 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2930}
2931
Douglas Gregor85dabae2009-12-16 01:38:02 +00002932/// \brief Attempt default initialization (C++ [dcl.init]p6).
2933static void TryDefaultInitialization(Sema &S,
2934 const InitializedEntity &Entity,
2935 const InitializationKind &Kind,
2936 InitializationSequence &Sequence) {
2937 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938
Douglas Gregor85dabae2009-12-16 01:38:02 +00002939 // C++ [dcl.init]p6:
2940 // To default-initialize an object of type T means:
2941 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002942 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002943 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2944 DestType = Array->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945
Douglas Gregor85dabae2009-12-16 01:38:02 +00002946 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2947 // constructor for T is called (and the initialization is ill-formed if
2948 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002949 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002950 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2951 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002953
Douglas Gregor85dabae2009-12-16 01:38:02 +00002954 // - otherwise, no initialization is performed.
2955 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956
Douglas Gregor85dabae2009-12-16 01:38:02 +00002957 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00002959 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002960 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002961 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2962}
2963
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002964/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2965/// which enumerates all conversion functions and performs overload resolution
2966/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002967static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002968 const InitializedEntity &Entity,
2969 const InitializationKind &Kind,
2970 Expr *Initializer,
2971 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002972 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002973
Douglas Gregor1b303932009-12-22 15:35:07 +00002974 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002975 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2976 QualType SourceType = Initializer->getType();
2977 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2978 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979
Douglas Gregor540c3b02009-12-14 17:27:33 +00002980 // Build the candidate set directly in the initialization sequence
2981 // structure, so that it will persist if we fail.
2982 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2983 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984
Douglas Gregor540c3b02009-12-14 17:27:33 +00002985 // Determine whether we are allowed to call explicit constructors or
2986 // explicit conversion operators.
2987 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002988
Douglas Gregor540c3b02009-12-14 17:27:33 +00002989 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2990 // The type we're converting to is a class type. Enumerate its constructors
2991 // to see if there is a suitable conversion.
2992 CXXRecordDecl *DestRecordDecl
2993 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994
Douglas Gregord9848152010-04-26 14:36:57 +00002995 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002996 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002997 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002998 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002999 Con != ConEnd; ++Con) {
3000 NamedDecl *D = *Con;
3001 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002
Douglas Gregord9848152010-04-26 14:36:57 +00003003 // Find the constructor (which may be a template).
3004 CXXConstructorDecl *Constructor = 0;
3005 FunctionTemplateDecl *ConstructorTmpl
3006 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003007 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003008 Constructor = cast<CXXConstructorDecl>(
3009 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003010 else
Douglas Gregord9848152010-04-26 14:36:57 +00003011 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003012
Douglas Gregord9848152010-04-26 14:36:57 +00003013 if (!Constructor->isInvalidDecl() &&
3014 Constructor->isConvertingConstructor(AllowExplicit)) {
3015 if (ConstructorTmpl)
3016 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3017 /*ExplicitArgs*/ 0,
3018 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003019 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003020 else
3021 S.AddOverloadCandidate(Constructor, FoundDecl,
3022 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003023 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025 }
Douglas Gregord9848152010-04-26 14:36:57 +00003026 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003027 }
Eli Friedman78275202009-12-19 08:11:05 +00003028
3029 SourceLocation DeclLoc = Initializer->getLocStart();
3030
Douglas Gregor540c3b02009-12-14 17:27:33 +00003031 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3032 // The type we're converting from is a class type, enumerate its conversion
3033 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003034
Eli Friedman4afe9a32009-12-20 22:12:03 +00003035 // We can only enumerate the conversion functions for a complete type; if
3036 // the type isn't complete, simply skip this step.
3037 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3038 CXXRecordDecl *SourceRecordDecl
3039 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003040
John McCallad371252010-01-20 00:46:10 +00003041 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003042 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003043 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003045 I != E; ++I) {
3046 NamedDecl *D = *I;
3047 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3048 if (isa<UsingShadowDecl>(D))
3049 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050
Eli Friedman4afe9a32009-12-20 22:12:03 +00003051 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3052 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003053 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003054 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003055 else
John McCallda4458e2010-03-31 01:36:47 +00003056 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057
Eli Friedman4afe9a32009-12-20 22:12:03 +00003058 if (AllowExplicit || !Conv->isExplicit()) {
3059 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003060 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003061 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003062 CandidateSet);
3063 else
John McCalla0296f72010-03-19 07:35:19 +00003064 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003065 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003066 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003067 }
3068 }
3069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070
3071 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003072 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003073 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003074 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003075 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003077 Result);
3078 return;
3079 }
John McCall0d1da222010-01-12 00:44:57 +00003080
Douglas Gregor540c3b02009-12-14 17:27:33 +00003081 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003082 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003083
Douglas Gregor540c3b02009-12-14 17:27:33 +00003084 if (isa<CXXConstructorDecl>(Function)) {
3085 // Add the user-defined conversion step. Any cv-qualification conversion is
3086 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003087 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003088 return;
3089 }
3090
3091 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003092 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003093 if (ConvType->getAs<RecordType>()) {
3094 // If we're converting to a class type, there may be an copy if
3095 // the resulting temporary object (possible to create an object of
3096 // a base class type). That copy is not a separate conversion, so
3097 // we just make a note of the actual destination type (possibly a
3098 // base class of the type returned by the conversion function) and
3099 // let the user-defined conversion step handle the conversion.
3100 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3101 return;
3102 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003103
Douglas Gregor5ab11652010-04-17 22:01:05 +00003104 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003105
Douglas Gregor5ab11652010-04-17 22:01:05 +00003106 // If the conversion following the call to the conversion function
3107 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003108 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3109 Best->FinalConversion.Third) {
3110 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003111 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003112 ICS.Standard = Best->FinalConversion;
3113 Sequence.AddConversionSequenceStep(ICS, DestType);
3114 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003115}
3116
Douglas Gregore2f943b2011-02-22 18:29:51 +00003117/// \brief Determine whether we have compatible array types for the
3118/// purposes of GNU by-copy array initialization.
3119static bool hasCompatibleArrayTypes(ASTContext &Context,
3120 const ArrayType *Dest,
3121 const ArrayType *Source) {
3122 // If the source and destination array types are equivalent, we're
3123 // done.
3124 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3125 return true;
3126
3127 // Make sure that the element types are the same.
3128 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3129 return false;
3130
3131 // The only mismatch we allow is when the destination is an
3132 // incomplete array type and the source is a constant array type.
3133 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3134}
3135
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003136InitializationSequence::InitializationSequence(Sema &S,
3137 const InitializedEntity &Entity,
3138 const InitializationKind &Kind,
3139 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003140 unsigned NumArgs)
3141 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003142 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003144 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145 // The semantics of initializers are as follows. The destination type is
3146 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003147 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003149 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003150 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003151
3152 if (DestType->isDependentType() ||
3153 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3154 SequenceKind = DependentSequence;
3155 return;
3156 }
3157
John McCalled75c092010-12-07 22:54:16 +00003158 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003159 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3160 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3161 if (Result.isInvalid()) {
3162 SetFailed(FK_ConversionFromPropertyFailed);
3163 return;
3164 }
3165 Args[I] = Result.take();
3166 }
John McCalled75c092010-12-07 22:54:16 +00003167
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003168 QualType SourceType;
3169 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003170 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003171 Initializer = Args[0];
3172 if (!isa<InitListExpr>(Initializer))
3173 SourceType = Initializer->getType();
3174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175
3176 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003177 // list-initialized (8.5.4).
3178 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3179 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003180 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003182
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003183 // - If the destination type is a reference type, see 8.5.3.
3184 if (DestType->isReferenceType()) {
3185 // C++0x [dcl.init.ref]p1:
3186 // A variable declared to be a T& or T&&, that is, "reference to type T"
3187 // (8.3.2), shall be initialized by an object, or function, of type T or
3188 // by an object that can be converted into a T.
3189 // (Therefore, multiple arguments are not permitted.)
3190 if (NumArgs != 1)
3191 SetFailed(FK_TooManyInitsForReference);
3192 else
3193 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3194 return;
3195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003197 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003198 if (Kind.getKind() == InitializationKind::IK_Value ||
3199 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003200 TryValueInitialization(S, Entity, Kind, *this);
3201 return;
3202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
Douglas Gregor85dabae2009-12-16 01:38:02 +00003204 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003205 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003206 TryDefaultInitialization(S, Entity, Kind, *this);
3207 return;
3208 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003209
John McCall66884dd2011-02-21 07:22:22 +00003210 // - If the destination type is an array of characters, an array of
3211 // char16_t, an array of char32_t, or an array of wchar_t, and the
3212 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003214 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003215 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3216 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCall66884dd2011-02-21 07:22:22 +00003217 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3218 return;
3219 }
3220
Douglas Gregore2f943b2011-02-22 18:29:51 +00003221 // Note: as an GNU C extension, we allow initialization of an
3222 // array from a compound literal that creates an array of the same
3223 // type, so long as the initializer has no side effects.
3224 if (!S.getLangOptions().CPlusPlus && Initializer &&
3225 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3226 Initializer->getType()->isArrayType()) {
3227 const ArrayType *SourceAT
3228 = Context.getAsArrayType(Initializer->getType());
3229 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3230 SetFailed(FK_ArrayTypeMismatch);
3231 else if (Initializer->HasSideEffects(S.Context))
3232 SetFailed(FK_NonConstantArrayInit);
3233 else {
3234 setSequenceKind(ArrayInit);
3235 AddArrayInitStep(DestType);
3236 }
3237 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3239 else
3240 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003242 return;
3243 }
Eli Friedman78275202009-12-19 08:11:05 +00003244
3245 // Handle initialization in C
3246 if (!S.getLangOptions().CPlusPlus) {
3247 setSequenceKind(CAssignment);
3248 AddCAssignmentStep(DestType);
3249 return;
3250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003252 // - If the destination type is a (possibly cv-qualified) class type:
3253 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254 // - If the initialization is direct-initialization, or if it is
3255 // copy-initialization where the cv-unqualified version of the
3256 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003257 // class of the destination, constructors are considered. [...]
3258 if (Kind.getKind() == InitializationKind::IK_Direct ||
3259 (Kind.getKind() == InitializationKind::IK_Copy &&
3260 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3261 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003263 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003265 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 // used) to a derived class thereof are enumerated as described in
3268 // 13.3.1.4, and the best one is chosen through overload resolution
3269 // (13.3).
3270 else
3271 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3272 return;
3273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274
Douglas Gregor85dabae2009-12-16 01:38:02 +00003275 if (NumArgs > 1) {
3276 SetFailed(FK_TooManyInitsForScalar);
3277 return;
3278 }
3279 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280
3281 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003282 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003283 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003284 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3285 return;
3286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003288 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003289 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003290 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003291 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003292 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003293 if (S.TryImplicitConversion(*this, Entity, Initializer,
3294 /*SuppressUserConversions*/ true,
3295 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003296 /*InOverloadResolution*/ false,
3297 /*CStyle=*/Kind.isCStyleOrFunctionalCast()))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003298 {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003299 DeclAccessPair dap;
3300 if (Initializer->getType() == Context.OverloadTy &&
3301 !S.ResolveAddressOfOverloadedFunction(Initializer
3302 , DestType, false, dap))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003303 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3304 else
3305 SetFailed(InitializationSequence::FK_ConversionFailed);
3306 }
John McCallec6f4e92010-06-04 02:29:22 +00003307 else
3308 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003309}
3310
3311InitializationSequence::~InitializationSequence() {
3312 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3313 StepEnd = Steps.end();
3314 Step != StepEnd; ++Step)
3315 Step->Destroy();
3316}
3317
3318//===----------------------------------------------------------------------===//
3319// Perform initialization
3320//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003322getAssignmentAction(const InitializedEntity &Entity) {
3323 switch(Entity.getKind()) {
3324 case InitializedEntity::EK_Variable:
3325 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003326 case InitializedEntity::EK_Exception:
3327 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003328 case InitializedEntity::EK_Delegation:
Douglas Gregore1314a62009-12-18 05:02:21 +00003329 return Sema::AA_Initializing;
3330
3331 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003333 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3334 return Sema::AA_Sending;
3335
Douglas Gregore1314a62009-12-18 05:02:21 +00003336 return Sema::AA_Passing;
3337
3338 case InitializedEntity::EK_Result:
3339 return Sema::AA_Returning;
3340
Douglas Gregore1314a62009-12-18 05:02:21 +00003341 case InitializedEntity::EK_Temporary:
3342 // FIXME: Can we tell apart casting vs. converting?
3343 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344
Douglas Gregore1314a62009-12-18 05:02:21 +00003345 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003346 case InitializedEntity::EK_ArrayElement:
3347 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003348 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003349 return Sema::AA_Initializing;
3350 }
3351
3352 return Sema::AA_Converting;
3353}
3354
Douglas Gregor95562572010-04-24 23:45:46 +00003355/// \brief Whether we should binding a created object as a temporary when
3356/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003357static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003358 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003359 case InitializedEntity::EK_ArrayElement:
3360 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003361 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003362 case InitializedEntity::EK_New:
3363 case InitializedEntity::EK_Variable:
3364 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003365 case InitializedEntity::EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003366 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003367 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003368 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003369 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003370
Douglas Gregore1314a62009-12-18 05:02:21 +00003371 case InitializedEntity::EK_Parameter:
3372 case InitializedEntity::EK_Temporary:
3373 return true;
3374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375
Douglas Gregore1314a62009-12-18 05:02:21 +00003376 llvm_unreachable("missed an InitializedEntity kind?");
3377}
3378
Douglas Gregor95562572010-04-24 23:45:46 +00003379/// \brief Whether the given entity, when initialized with an object
3380/// created for that initialization, requires destruction.
3381static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3382 switch (Entity.getKind()) {
3383 case InitializedEntity::EK_Member:
3384 case InitializedEntity::EK_Result:
3385 case InitializedEntity::EK_New:
3386 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003387 case InitializedEntity::EK_Delegation:
Douglas Gregor95562572010-04-24 23:45:46 +00003388 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003389 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003390 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391
Douglas Gregor95562572010-04-24 23:45:46 +00003392 case InitializedEntity::EK_Variable:
3393 case InitializedEntity::EK_Parameter:
3394 case InitializedEntity::EK_Temporary:
3395 case InitializedEntity::EK_ArrayElement:
3396 case InitializedEntity::EK_Exception:
3397 return true;
3398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
3400 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003401}
3402
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003403/// \brief Make a (potentially elidable) temporary copy of the object
3404/// provided by the given initializer by calling the appropriate copy
3405/// constructor.
3406///
3407/// \param S The Sema object used for type-checking.
3408///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003409/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003410/// the type of the initializer expression or a superclass thereof.
3411///
3412/// \param Enter The entity being initialized.
3413///
3414/// \param CurInit The initializer expression.
3415///
3416/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3417/// is permitted in C++03 (but not C++0x) when binding a reference to
3418/// an rvalue.
3419///
3420/// \returns An expression that copies the initializer expression into
3421/// a temporary object, or an error expression if a copy could not be
3422/// created.
John McCalldadc5752010-08-24 06:29:42 +00003423static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003424 QualType T,
3425 const InitializedEntity &Entity,
3426 ExprResult CurInit,
3427 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003428 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003429 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003431 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003432 Class = cast<CXXRecordDecl>(Record->getDecl());
3433 if (!Class)
3434 return move(CurInit);
3435
Douglas Gregor5d369002011-01-21 18:05:27 +00003436 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003437 // When certain criteria are met, an implementation is allowed to
3438 // omit the copy/move construction of a class object, even if the
3439 // copy/move constructor and/or destructor for the object have
3440 // side effects. [...]
3441 // - when a temporary class object that has not been bound to a
3442 // reference (12.2) would be copied/moved to a class object
3443 // with the same cv-unqualified type, the copy/move operation
3444 // can be omitted by constructing the temporary object
3445 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003447 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003448 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003450 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003451 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003452 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003453 switch (Entity.getKind()) {
3454 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003455 Loc = Entity.getReturnLoc();
3456 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457
Douglas Gregore1314a62009-12-18 05:02:21 +00003458 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003459 Loc = Entity.getThrowLoc();
3460 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461
Douglas Gregore1314a62009-12-18 05:02:21 +00003462 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003463 Loc = Entity.getDecl()->getLocation();
3464 break;
3465
Anders Carlsson0bd52402010-01-24 00:19:41 +00003466 case InitializedEntity::EK_ArrayElement:
3467 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003468 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003469 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003470 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003471 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003472 case InitializedEntity::EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003473 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003474 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003475 Loc = CurInitExpr->getLocStart();
3476 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003477 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003478
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003479 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003480 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3481 return move(CurInit);
3482
Douglas Gregorf282a762011-01-21 19:38:21 +00003483 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003484 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003485 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003486 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003487 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003488 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003489 // C++0x [dcl.init]p16, second bullet to class types, this
3490 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003491 CXXConstructorDecl *Constructor = 0;
3492
3493 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003494 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003495 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003496 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003497 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003498 continue;
3499
3500 DeclAccessPair FoundDecl
3501 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3502 S.AddOverloadCandidate(Constructor, FoundDecl,
3503 &CurInitExpr, 1, CandidateSet);
3504 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003506
3507 // Handle constructor templates.
3508 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3509 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003510 continue;
John McCalla0296f72010-03-19 07:35:19 +00003511
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003512 Constructor = cast<CXXConstructorDecl>(
3513 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003514 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003515 continue;
3516
3517 // FIXME: Do we need to limit this to copy-constructor-like
3518 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003519 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003520 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3521 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3522 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Douglas Gregore1314a62009-12-18 05:02:21 +00003525 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003526 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003527 case OR_Success:
3528 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529
Douglas Gregore1314a62009-12-18 05:02:21 +00003530 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003531 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3532 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3533 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003534 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003535 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003536 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003537 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003538 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003539 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540
Douglas Gregore1314a62009-12-18 05:02:21 +00003541 case OR_Ambiguous:
3542 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003543 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003544 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003545 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003546 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547
Douglas Gregore1314a62009-12-18 05:02:21 +00003548 case OR_Deleted:
3549 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003550 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003551 << CurInitExpr->getSourceRange();
3552 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3553 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003554 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003555 }
3556
Douglas Gregor5ab11652010-04-17 22:01:05 +00003557 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003558 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003559 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003560
Anders Carlssona01874b2010-04-21 18:47:17 +00003561 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003562 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003563
3564 if (IsExtraneousCopy) {
3565 // If this is a totally extraneous copy for C++03 reference
3566 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003567 // expression. We don't generate an (elided) copy operation here
3568 // because doing so would require us to pass down a flag to avoid
3569 // infinite recursion, where each step adds another extraneous,
3570 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003571
Douglas Gregor30b52772010-04-18 07:57:34 +00003572 // Instantiate the default arguments of any extra parameters in
3573 // the selected copy constructor, as if we were going to create a
3574 // proper call to the copy constructor.
3575 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3576 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3577 if (S.RequireCompleteType(Loc, Parm->getType(),
3578 S.PDiag(diag::err_call_incomplete_argument)))
3579 break;
3580
3581 // Build the default argument expression; we don't actually care
3582 // if this succeeds or not, because this routine will complain
3583 // if there was a problem.
3584 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3585 }
3586
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003587 return S.Owned(CurInitExpr);
3588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589
Chandler Carruth30141632011-02-25 19:41:05 +00003590 S.MarkDeclarationReferenced(Loc, Constructor);
3591
Douglas Gregor5ab11652010-04-17 22:01:05 +00003592 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003593 // constructor call (we might have derived-to-base conversions, or
3594 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003595 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003596 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003597 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003598
Douglas Gregord0ace022010-04-25 00:55:24 +00003599 // Actually perform the constructor call.
3600 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003601 move_arg(ConstructorArgs),
3602 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003603 CXXConstructExpr::CK_Complete,
3604 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003605
Douglas Gregord0ace022010-04-25 00:55:24 +00003606 // If we're supposed to bind temporaries, do so.
3607 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3608 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3609 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003610}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003611
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003612void InitializationSequence::PrintInitLocationNote(Sema &S,
3613 const InitializedEntity &Entity) {
3614 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3615 if (Entity.getDecl()->getLocation().isInvalid())
3616 return;
3617
3618 if (Entity.getDecl()->getDeclName())
3619 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3620 << Entity.getDecl()->getDeclName();
3621 else
3622 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3623 }
3624}
3625
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003627InitializationSequence::Perform(Sema &S,
3628 const InitializedEntity &Entity,
3629 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003630 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003631 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003632 if (SequenceKind == FailedSequence) {
3633 unsigned NumArgs = Args.size();
3634 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003635 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003638 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003639 // If the declaration is a non-dependent, incomplete array type
3640 // that has an initializer, then its type will be completed once
3641 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003642 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003643 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003644 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003645 if (const IncompleteArrayType *ArrayT
3646 = S.Context.getAsIncompleteArrayType(DeclType)) {
3647 // FIXME: We don't currently have the ability to accurately
3648 // compute the length of an initializer list without
3649 // performing full type-checking of the initializer list
3650 // (since we have to determine where braces are implicitly
3651 // introduced and such). So, we fall back to making the array
3652 // type a dependently-sized array type with no specified
3653 // bound.
3654 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3655 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003656
Douglas Gregor51e77d52009-12-10 17:56:55 +00003657 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003658 if (DeclaratorDecl *DD = Entity.getDecl()) {
3659 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3660 TypeLoc TL = TInfo->getTypeLoc();
3661 if (IncompleteArrayTypeLoc *ArrayLoc
3662 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3663 Brackets = ArrayLoc->getBracketsRange();
3664 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003665 }
3666
3667 *ResultType
3668 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3669 /*NumElts=*/0,
3670 ArrayT->getSizeModifier(),
3671 ArrayT->getIndexTypeCVRQualifiers(),
3672 Brackets);
3673 }
3674
3675 }
3676 }
3677
Eli Friedmana553d4a2009-12-22 02:35:53 +00003678 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003679 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003680
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003681 if (Args.size() == 0)
3682 return S.Owned((Expr *)0);
3683
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003684 unsigned NumArgs = Args.size();
3685 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3686 SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003687 (Expr **)Args.release(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003688 NumArgs,
3689 SourceLocation()));
3690 }
3691
Douglas Gregor85dabae2009-12-16 01:38:02 +00003692 if (SequenceKind == NoInitialization)
3693 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003694
Douglas Gregor1b303932009-12-22 15:35:07 +00003695 QualType DestType = Entity.getType().getNonReferenceType();
3696 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003697 // the same as Entity.getDecl()->getType() in cases involving type merging,
3698 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003699 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003700 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003701 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003702
John McCalldadc5752010-08-24 06:29:42 +00003703 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003704
Douglas Gregor85dabae2009-12-16 01:38:02 +00003705 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706
3707 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00003708 // grab the only argument out the Args and place it into the "current"
3709 // initializer.
3710 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003711 case SK_ResolveAddressOfOverloadedFunction:
3712 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003713 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003714 case SK_CastDerivedToBaseLValue:
3715 case SK_BindReference:
3716 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003717 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003718 case SK_UserConversion:
3719 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003720 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003721 case SK_QualificationConversionRValue:
3722 case SK_ConversionSequence:
3723 case SK_ListInitialization:
3724 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003725 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003726 case SK_ObjCObjectConversion:
3727 case SK_ArrayInit: {
Douglas Gregore1314a62009-12-18 05:02:21 +00003728 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00003729 CurInit = Args.get()[0];
3730 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003731
3732 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00003733 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3734 CurInit = S.ConvertPropertyForRValue(CurInit.take());
3735 if (CurInit.isInvalid())
3736 return ExprError();
3737 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003738 break;
John McCall34376a62010-12-04 03:47:34 +00003739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003740
Douglas Gregore1314a62009-12-18 05:02:21 +00003741 case SK_ConstructorInitialization:
3742 case SK_ZeroInitialization:
3743 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
3746 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003747 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003748 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003749 for (step_iterator Step = step_begin(), StepEnd = step_end();
3750 Step != StepEnd; ++Step) {
3751 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003752 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753
John Wiegley01296292011-04-08 18:41:53 +00003754 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003756 switch (Step->Kind) {
3757 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003759 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00003760 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003761 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003762 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003763 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003764 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003765 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003766
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003767 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003768 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003769 case SK_CastDerivedToBaseLValue: {
3770 // We have a derived-to-base cast that produces either an rvalue or an
3771 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772
John McCallcf142162010-08-07 06:22:56 +00003773 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003774
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003775 // Casts to inaccessible base classes are allowed with C-style casts.
3776 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3777 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00003778 CurInit.get()->getLocStart(),
3779 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003780 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003781 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003782
Douglas Gregor88d292c2010-05-13 16:44:06 +00003783 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3784 QualType T = SourceType;
3785 if (const PointerType *Pointer = T->getAs<PointerType>())
3786 T = Pointer->getPointeeType();
3787 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00003788 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003789 cast<CXXRecordDecl>(RecordTy->getDecl()));
3790 }
3791
John McCall2536c6d2010-08-25 10:28:54 +00003792 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003793 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003794 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003795 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003796 VK_XValue :
3797 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003798 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3799 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003800 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003801 CurInit.get(),
3802 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003803 break;
3804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003806 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00003807 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003808 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3809 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003810 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003811 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00003812 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003813 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003814 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003815 }
Anders Carlssona91be642010-01-29 02:47:33 +00003816
John Wiegley01296292011-04-08 18:41:53 +00003817 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003818 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003819 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3820 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00003821 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003822 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003823 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003826 // Reference binding does not have any corresponding ASTs.
3827
3828 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00003829 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003830 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003831
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003832 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003833
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003834 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003835 // Reference binding does not have any corresponding ASTs.
3836
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003837 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00003838 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003839 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003840
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003841 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003843 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003844 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003845 /*IsExtraneousCopy=*/true);
3846 break;
3847
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003848 case SK_UserConversion: {
3849 // We have a user-defined conversion that invokes either a constructor
3850 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00003851 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00003852 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003853 FunctionDecl *Fn = Step->Function.Function;
3854 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003855 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003856 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003857 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003858 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003859 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00003860 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003861 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003862
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003863 // Determine the arguments required to actually perform the constructor
3864 // call.
John Wiegley01296292011-04-08 18:41:53 +00003865 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003866 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00003867 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003868 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003869 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003871 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003872 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003873 move_arg(ConstructorArgs),
3874 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003875 CXXConstructExpr::CK_Complete,
3876 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003877 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003878 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003879
Anders Carlssona01874b2010-04-21 18:47:17 +00003880 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003881 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003882 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883
John McCalle3027922010-08-25 11:45:40 +00003884 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003885 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3886 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3887 S.IsDerivedFrom(SourceType, Class))
3888 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889
Douglas Gregor95562572010-04-24 23:45:46 +00003890 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003891 } else {
3892 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003893 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003894 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00003895 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00003896 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003897 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898
3899 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900 // derived-to-base conversion? I believe the answer is "no", because
3901 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00003902 ExprResult CurInitExprRes =
3903 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
3904 FoundFn, Conversion);
3905 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003906 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00003907 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003909 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00003910 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003911 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003912 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913
John McCalle3027922010-08-25 11:45:40 +00003914 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915
Douglas Gregor95562572010-04-24 23:45:46 +00003916 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918
3919 bool RequiresCopy = !IsCopy &&
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003920 getKind() != InitializationSequence::ReferenceBinding;
3921 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003922 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003923 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00003924 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00003925 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003926 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00003927 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00003928 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00003929 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00003930 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
3931 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00003932 }
3933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003935 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003936 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00003937 CurInit.get()->getType(),
3938 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00003939 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003940
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003941 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003942 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3943 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003944
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003945 break;
3946 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003947
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003948 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003949 case SK_QualificationConversionXValue:
3950 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003951 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003952 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003953 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003954 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003955 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003956 VK_XValue :
3957 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00003958 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003959 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003960 }
3961
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003962 case SK_ConversionSequence: {
John Wiegley01296292011-04-08 18:41:53 +00003963 ExprResult CurInitExprRes =
3964 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
3965 getAssignmentAction(Entity),
3966 Kind.isCStyleOrFunctionalCast());
3967 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003968 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00003969 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003970 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003972
Douglas Gregor51e77d52009-12-10 17:56:55 +00003973 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00003974 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003975 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003976 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003977 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003978
3979 CurInit.release();
3980 CurInit = S.Owned(InitList);
3981 break;
3982 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003983
3984 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003985 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003986 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003987 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003989 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003990 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003991 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3992 ? Kind.getEqualLoc()
3993 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003994
3995 if (Kind.getKind() == InitializationKind::IK_Default) {
3996 // Force even a trivial, implicit default constructor to be
3997 // semantically checked. We do this explicitly because we don't build
3998 // the definition for completely trivial constructors.
3999 CXXRecordDecl *ClassDecl = Constructor->getParent();
4000 assert(ClassDecl && "No parent class for constructor.");
4001 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4002 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
4003 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4004 }
4005
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004006 // Determine the arguments required to actually perform the constructor
4007 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004009 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004010 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004011
4012
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004013 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004014 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004015 (Kind.getKind() == InitializationKind::IK_Direct ||
4016 Kind.getKind() == InitializationKind::IK_Value)) {
4017 // An explicitly-constructed temporary, e.g., X(1, 2).
4018 unsigned NumExprs = ConstructorArgs.size();
4019 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004020 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004021 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022
Douglas Gregor2b88c112010-09-08 00:15:04 +00004023 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4024 if (!TSInfo)
4025 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004027 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4028 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004029 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004031 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004032 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004033 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004034 } else {
4035 CXXConstructExpr::ConstructionKind ConstructKind =
4036 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004038 if (Entity.getKind() == InitializedEntity::EK_Base) {
4039 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004041 CXXConstructExpr::CK_NonVirtualBase;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042 }
4043
Chandler Carruth01718152010-10-25 08:47:36 +00004044 // Only get the parenthesis range if it is a direct construction.
4045 SourceRange parenRange =
4046 Kind.getKind() == InitializationKind::IK_Direct ?
4047 Kind.getParenRange() : SourceRange();
4048
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004049 // If the entity allows NRVO, mark the construction as elidable
4050 // unconditionally.
4051 if (Entity.allowsNRVO())
4052 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4053 Constructor, /*Elidable=*/true,
4054 move_arg(ConstructorArgs),
4055 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004056 ConstructKind,
4057 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004058 else
4059 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004061 move_arg(ConstructorArgs),
4062 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004063 ConstructKind,
4064 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004065 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004066 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004067 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004068
4069 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004070 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004071 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004072 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004073
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004074 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004075 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004077 break;
4078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004080 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004081 step_iterator NextStep = Step;
4082 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004084 NextStep->Kind == SK_ConstructorInitialization) {
4085 // The need for zero-initialization is recorded directly into
4086 // the call to the object's constructor within the next step.
4087 ConstructorInitRequiresZeroInit = true;
4088 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4089 S.getLangOptions().CPlusPlus &&
4090 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004091 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4092 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004093 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004094 Kind.getRange().getBegin());
4095
4096 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4097 TSInfo->getType().getNonLValueExprType(S.Context),
4098 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004099 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004100 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004101 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004102 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004103 break;
4104 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004105
4106 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004107 QualType SourceType = CurInit.get()->getType();
4108 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004109 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004110 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4111 if (Result.isInvalid())
4112 return ExprError();
4113 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004114
4115 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004116 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004117 if (ConvTy != Sema::Compatible &&
4118 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004119 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004120 == Sema::Compatible)
4121 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004122 if (CurInitExprRes.isInvalid())
4123 return ExprError();
4124 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004125
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004126 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004127 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4128 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004129 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004130 getAssignmentAction(Entity),
4131 &Complained)) {
4132 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004133 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004134 } else if (Complained)
4135 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004136 break;
4137 }
Eli Friedman78275202009-12-19 08:11:05 +00004138
4139 case SK_StringInit: {
4140 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004141 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004142 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004143 break;
4144 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004145
4146 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004147 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004148 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004149 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004150 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004151
4152 case SK_ArrayInit:
4153 // Okay: we checked everything before creating this step. Note that
4154 // this is a GNU extension.
4155 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004156 << Step->Type << CurInit.get()->getType()
4157 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004158
4159 // If the destination type is an incomplete array type, update the
4160 // type accordingly.
4161 if (ResultType) {
4162 if (const IncompleteArrayType *IncompleteDest
4163 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4164 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004165 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004166 *ResultType = S.Context.getConstantArrayType(
4167 IncompleteDest->getElementType(),
4168 ConstantSource->getSize(),
4169 ArrayType::Normal, 0);
4170 }
4171 }
4172 }
4173
4174 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004175 }
4176 }
John McCall1f425642010-11-11 03:21:53 +00004177
4178 // Diagnose non-fatal problems with the completed initialization.
4179 if (Entity.getKind() == InitializedEntity::EK_Member &&
4180 cast<FieldDecl>(Entity.getDecl())->isBitField())
4181 S.CheckBitFieldInitialization(Kind.getLocation(),
4182 cast<FieldDecl>(Entity.getDecl()),
4183 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004185 return move(CurInit);
4186}
4187
4188//===----------------------------------------------------------------------===//
4189// Diagnose initialization failures
4190//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004191bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004192 const InitializedEntity &Entity,
4193 const InitializationKind &Kind,
4194 Expr **Args, unsigned NumArgs) {
4195 if (SequenceKind != FailedSequence)
4196 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197
Douglas Gregor1b303932009-12-22 15:35:07 +00004198 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004199 switch (Failure) {
4200 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004201 // FIXME: Customize for the initialized entity?
4202 if (NumArgs == 0)
4203 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4204 << DestType.getNonReferenceType();
4205 else // FIXME: diagnostic below could be better!
4206 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4207 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004208 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004209
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004210 case FK_ArrayNeedsInitList:
4211 case FK_ArrayNeedsInitListOrStringLiteral:
4212 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4213 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4214 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215
Douglas Gregore2f943b2011-02-22 18:29:51 +00004216 case FK_ArrayTypeMismatch:
4217 case FK_NonConstantArrayInit:
4218 S.Diag(Kind.getLocation(),
4219 (Failure == FK_ArrayTypeMismatch
4220 ? diag::err_array_init_different_type
4221 : diag::err_array_init_non_constant_array))
4222 << DestType.getNonReferenceType()
4223 << Args[0]->getType()
4224 << Args[0]->getSourceRange();
4225 break;
4226
John McCall16df1e52010-03-30 21:47:33 +00004227 case FK_AddressOfOverloadFailed: {
4228 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004230 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004231 true,
4232 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004233 break;
John McCall16df1e52010-03-30 21:47:33 +00004234 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004236 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004237 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004238 switch (FailedOverloadResult) {
4239 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004240 if (Failure == FK_UserConversionOverloadFailed)
4241 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4242 << Args[0]->getType() << DestType
4243 << Args[0]->getSourceRange();
4244 else
4245 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4246 << DestType << Args[0]->getType()
4247 << Args[0]->getSourceRange();
4248
John McCall5c32be02010-08-24 20:38:10 +00004249 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004250 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004251
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004252 case OR_No_Viable_Function:
4253 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4254 << Args[0]->getType() << DestType.getNonReferenceType()
4255 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004256 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004257 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004259 case OR_Deleted: {
4260 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4261 << Args[0]->getType() << DestType.getNonReferenceType()
4262 << Args[0]->getSourceRange();
4263 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004264 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004265 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4266 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004267 if (Ovl == OR_Deleted) {
4268 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4269 << Best->Function->isDeleted();
4270 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004271 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004272 }
4273 break;
4274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004276 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004277 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004278 break;
4279 }
4280 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004282 case FK_NonConstLValueReferenceBindingToTemporary:
4283 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 Failure == FK_NonConstLValueReferenceBindingToTemporary
4286 ? diag::err_lvalue_reference_bind_to_temporary
4287 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004288 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004289 << DestType.getNonReferenceType()
4290 << Args[0]->getType()
4291 << Args[0]->getSourceRange();
4292 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004294 case FK_RValueReferenceBindingToLValue:
4295 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004296 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004297 << Args[0]->getSourceRange();
4298 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004300 case FK_ReferenceInitDropsQualifiers:
4301 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4302 << DestType.getNonReferenceType()
4303 << Args[0]->getType()
4304 << Args[0]->getSourceRange();
4305 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004307 case FK_ReferenceInitFailed:
4308 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4309 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004310 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004311 << Args[0]->getType()
4312 << Args[0]->getSourceRange();
4313 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314
Douglas Gregorb491ed32011-02-19 21:32:49 +00004315 case FK_ConversionFailed: {
4316 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004317 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4318 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004319 << DestType
John McCall086a4642010-11-24 05:12:34 +00004320 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004321 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004322 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004323 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004324 }
John Wiegley01296292011-04-08 18:41:53 +00004325
4326 case FK_ConversionFromPropertyFailed:
4327 // No-op. This error has already been reported.
4328 break;
4329
Douglas Gregor51e77d52009-12-10 17:56:55 +00004330 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004331 SourceRange R;
4332
4333 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004334 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004335 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004337 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004338
Douglas Gregor8ec51732010-09-08 21:40:08 +00004339 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4340 if (Kind.isCStyleOrFunctionalCast())
4341 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4342 << R;
4343 else
4344 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4345 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004346 break;
4347 }
4348
4349 case FK_ReferenceBindingToInitList:
4350 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4351 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4352 break;
4353
4354 case FK_InitListBadDestinationType:
4355 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4356 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4357 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004359 case FK_ConstructorOverloadFailed: {
4360 SourceRange ArgsRange;
4361 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004362 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004363 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004365 // FIXME: Using "DestType" for the entity we're printing is probably
4366 // bad.
4367 switch (FailedOverloadResult) {
4368 case OR_Ambiguous:
4369 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4370 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004371 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4372 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004373 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004375 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004376 if (Kind.getKind() == InitializationKind::IK_Default &&
4377 (Entity.getKind() == InitializedEntity::EK_Base ||
4378 Entity.getKind() == InitializedEntity::EK_Member) &&
4379 isa<CXXConstructorDecl>(S.CurContext)) {
4380 // This is implicit default initialization of a member or
4381 // base within a constructor. If no viable function was
4382 // found, notify the user that she needs to explicitly
4383 // initialize this base/member.
4384 CXXConstructorDecl *Constructor
4385 = cast<CXXConstructorDecl>(S.CurContext);
4386 if (Entity.getKind() == InitializedEntity::EK_Base) {
4387 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4388 << Constructor->isImplicit()
4389 << S.Context.getTypeDeclType(Constructor->getParent())
4390 << /*base=*/0
4391 << Entity.getType();
4392
4393 RecordDecl *BaseDecl
4394 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4395 ->getDecl();
4396 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4397 << S.Context.getTagDeclType(BaseDecl);
4398 } else {
4399 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4400 << Constructor->isImplicit()
4401 << S.Context.getTypeDeclType(Constructor->getParent())
4402 << /*member=*/1
4403 << Entity.getName();
4404 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4405
4406 if (const RecordType *Record
4407 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004409 diag::note_previous_decl)
4410 << S.Context.getTagDeclType(Record->getDecl());
4411 }
4412 break;
4413 }
4414
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004415 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4416 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004417 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004420 case OR_Deleted: {
4421 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4422 << true << DestType << ArgsRange;
4423 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004424 OverloadingResult Ovl
4425 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004426 if (Ovl == OR_Deleted) {
4427 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4428 << Best->Function->isDeleted();
4429 } else {
4430 llvm_unreachable("Inconsistent overload resolution?");
4431 }
4432 break;
4433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004435 case OR_Success:
4436 llvm_unreachable("Conversion did not fail!");
4437 break;
4438 }
4439 break;
4440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441
Douglas Gregor85dabae2009-12-16 01:38:02 +00004442 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004443 if (Entity.getKind() == InitializedEntity::EK_Member &&
4444 isa<CXXConstructorDecl>(S.CurContext)) {
4445 // This is implicit default-initialization of a const member in
4446 // a constructor. Complain that it needs to be explicitly
4447 // initialized.
4448 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4449 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4450 << Constructor->isImplicit()
4451 << S.Context.getTypeDeclType(Constructor->getParent())
4452 << /*const=*/1
4453 << Entity.getName();
4454 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4455 << Entity.getName();
4456 } else {
4457 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4458 << DestType << (bool)DestType->getAs<RecordType>();
4459 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004460 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004461
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004462 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004464 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004468 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004469 return true;
4470}
Douglas Gregore1314a62009-12-18 05:02:21 +00004471
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004472void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4473 switch (SequenceKind) {
4474 case FailedSequence: {
4475 OS << "Failed sequence: ";
4476 switch (Failure) {
4477 case FK_TooManyInitsForReference:
4478 OS << "too many initializers for reference";
4479 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004481 case FK_ArrayNeedsInitList:
4482 OS << "array requires initializer list";
4483 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004484
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004485 case FK_ArrayNeedsInitListOrStringLiteral:
4486 OS << "array requires initializer list or string literal";
4487 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004488
Douglas Gregore2f943b2011-02-22 18:29:51 +00004489 case FK_ArrayTypeMismatch:
4490 OS << "array type mismatch";
4491 break;
4492
4493 case FK_NonConstantArrayInit:
4494 OS << "non-constant array initializer";
4495 break;
4496
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004497 case FK_AddressOfOverloadFailed:
4498 OS << "address of overloaded function failed";
4499 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004500
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004501 case FK_ReferenceInitOverloadFailed:
4502 OS << "overload resolution for reference initialization failed";
4503 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004505 case FK_NonConstLValueReferenceBindingToTemporary:
4506 OS << "non-const lvalue reference bound to temporary";
4507 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004509 case FK_NonConstLValueReferenceBindingToUnrelated:
4510 OS << "non-const lvalue reference bound to unrelated type";
4511 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004512
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004513 case FK_RValueReferenceBindingToLValue:
4514 OS << "rvalue reference bound to an lvalue";
4515 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004517 case FK_ReferenceInitDropsQualifiers:
4518 OS << "reference initialization drops qualifiers";
4519 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004521 case FK_ReferenceInitFailed:
4522 OS << "reference initialization failed";
4523 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004524
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004525 case FK_ConversionFailed:
4526 OS << "conversion failed";
4527 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528
John Wiegley01296292011-04-08 18:41:53 +00004529 case FK_ConversionFromPropertyFailed:
4530 OS << "conversion from property failed";
4531 break;
4532
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004533 case FK_TooManyInitsForScalar:
4534 OS << "too many initializers for scalar";
4535 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004536
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004537 case FK_ReferenceBindingToInitList:
4538 OS << "referencing binding to initializer list";
4539 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004541 case FK_InitListBadDestinationType:
4542 OS << "initializer list for non-aggregate, non-scalar type";
4543 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004544
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004545 case FK_UserConversionOverloadFailed:
4546 OS << "overloading failed for user-defined conversion";
4547 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004549 case FK_ConstructorOverloadFailed:
4550 OS << "constructor overloading failed";
4551 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004553 case FK_DefaultInitOfConst:
4554 OS << "default initialization of a const variable";
4555 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004557 case FK_Incomplete:
4558 OS << "initialization of incomplete type";
4559 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004560 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004561 OS << '\n';
4562 return;
4563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004565 case DependentSequence:
4566 OS << "Dependent sequence: ";
4567 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004569 case UserDefinedConversion:
4570 OS << "User-defined conversion sequence: ";
4571 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004573 case ConstructorInitialization:
4574 OS << "Constructor initialization sequence: ";
4575 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004577 case ReferenceBinding:
4578 OS << "Reference binding: ";
4579 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004581 case ListInitialization:
4582 OS << "List initialization: ";
4583 break;
4584
4585 case ZeroInitialization:
4586 OS << "Zero initialization\n";
4587 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004588
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004589 case NoInitialization:
4590 OS << "No initialization\n";
4591 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004592
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004593 case StandardConversion:
4594 OS << "Standard conversion: ";
4595 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004596
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004597 case CAssignment:
4598 OS << "C assignment: ";
4599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004601 case StringInit:
4602 OS << "String initialization: ";
4603 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004604
4605 case ArrayInit:
4606 OS << "Array initialization: ";
4607 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004610 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4611 if (S != step_begin()) {
4612 OS << " -> ";
4613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004615 switch (S->Kind) {
4616 case SK_ResolveAddressOfOverloadedFunction:
4617 OS << "resolve address of overloaded function";
4618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004620 case SK_CastDerivedToBaseRValue:
4621 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4622 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004624 case SK_CastDerivedToBaseXValue:
4625 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4626 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004628 case SK_CastDerivedToBaseLValue:
4629 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4630 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004631
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004632 case SK_BindReference:
4633 OS << "bind reference to lvalue";
4634 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004636 case SK_BindReferenceToTemporary:
4637 OS << "bind reference to a temporary";
4638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004640 case SK_ExtraneousCopyToTemporary:
4641 OS << "extraneous C++03 copy to temporary";
4642 break;
4643
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004644 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004645 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004646 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004647
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004648 case SK_QualificationConversionRValue:
4649 OS << "qualification conversion (rvalue)";
4650
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004651 case SK_QualificationConversionXValue:
4652 OS << "qualification conversion (xvalue)";
4653
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004654 case SK_QualificationConversionLValue:
4655 OS << "qualification conversion (lvalue)";
4656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004658 case SK_ConversionSequence:
4659 OS << "implicit conversion sequence (";
4660 S->ICS->DebugPrint(); // FIXME: use OS
4661 OS << ")";
4662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004664 case SK_ListInitialization:
4665 OS << "list initialization";
4666 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004668 case SK_ConstructorInitialization:
4669 OS << "constructor initialization";
4670 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004672 case SK_ZeroInitialization:
4673 OS << "zero initialization";
4674 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004675
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004676 case SK_CAssignment:
4677 OS << "C assignment";
4678 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004680 case SK_StringInit:
4681 OS << "string initialization";
4682 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004683
4684 case SK_ObjCObjectConversion:
4685 OS << "Objective-C object conversion";
4686 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004687
4688 case SK_ArrayInit:
4689 OS << "array initialization";
4690 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004691 }
4692 }
4693}
4694
4695void InitializationSequence::dump() const {
4696 dump(llvm::errs());
4697}
4698
Douglas Gregore1314a62009-12-18 05:02:21 +00004699//===----------------------------------------------------------------------===//
4700// Initialization helper functions
4701//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004703Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4704 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004705 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004706 if (Init.isInvalid())
4707 return ExprError();
4708
John McCall1f425642010-11-11 03:21:53 +00004709 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00004710 assert(InitE && "No initialization expression?");
4711
4712 if (EqualLoc.isInvalid())
4713 EqualLoc = InitE->getLocStart();
4714
4715 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4716 EqualLoc);
4717 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4718 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004719 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004720}