blob: 0f8d4ddc336b187217bf6c888c95c0a3061d5b02 [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 Friedman893abe42009-05-29 18:22:49 +000095 // C99 6.7.8p14. We have an array of character type with known size. However,
96 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
98 if (StrLength-1 > CAT->getSize().getZExtValue())
99 S.Diag(Str->getSourceRange().getBegin(),
100 diag::warn_initializer_string_for_char_array_too_long)
101 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000102
Eli Friedman893abe42009-05-29 18:22:49 +0000103 // Set the type to the actual size that we are initializing. If we have
104 // something like:
105 // char x[1] = "foo";
106 // then this will set the string literal's type to char[1].
107 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000108}
109
Chris Lattner0cb78032009-02-24 22:27:37 +0000110//===----------------------------------------------------------------------===//
111// Semantic checking for initializer lists.
112//===----------------------------------------------------------------------===//
113
Douglas Gregorcde232f2009-01-29 01:05:33 +0000114/// @brief Semantic checking for initializer lists.
115///
116/// The InitListChecker class contains a set of routines that each
117/// handle the initialization of a certain kind of entity, e.g.,
118/// arrays, vectors, struct/union types, scalars, etc. The
119/// InitListChecker itself performs a recursive walk of the subobject
120/// structure of the type to be initialized, while stepping through
121/// the initializer list one element at a time. The IList and Index
122/// parameters to each of the Check* routines contain the active
123/// (syntactic) initializer list and the index into that initializer
124/// list that represents the current initializer. Each routine is
125/// responsible for moving that Index forward as it consumes elements.
126///
127/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000128/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000129/// initializer list and the index into that initializer list where we
130/// are copying initializers as we map them over to the semantic
131/// list. Once we have completed our recursive walk of the subobject
132/// structure, we will have constructed a full semantic initializer
133/// list.
134///
135/// C99 designators cause changes in the initializer list traversal,
136/// because they make the initialization "jump" into a specific
137/// subobject and then continue the initialization from that
138/// point. CheckDesignatedInitializer() recursively steps into the
139/// designated subobject and manages backing out the recursion to
140/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000141namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000142class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000143 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000144 bool hadError;
145 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
146 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000147
Anders Carlsson6cabf312010-01-23 23:23:01 +0000148 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000149 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000153 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000155 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000156 unsigned &StructuredIndex,
157 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000158 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000159 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000160 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000161 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000162 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000163 unsigned &StructuredIndex,
164 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000165 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000170 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000171 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000172 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000175 void CheckReferenceType(const InitializedEntity &Entity,
176 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000177 unsigned &Index,
178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000180 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000181 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000182 InitListExpr *StructuredList,
183 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000184 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000185 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000186 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000187 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000188 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000189 unsigned &StructuredIndex,
190 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000191 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000192 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000193 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000194 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000197 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000198 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000199 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000200 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000201 RecordDecl::field_iterator *NextField,
202 llvm::APSInt *NextElementIndex,
203 unsigned &Index,
204 InitListExpr *StructuredList,
205 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000206 bool FinishSubobjectInit,
207 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000208 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
209 QualType CurrentObjectType,
210 InitListExpr *StructuredList,
211 unsigned StructuredIndex,
212 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000213 void UpdateStructuredListElement(InitListExpr *StructuredList,
214 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000215 Expr *expr);
216 int numArrayElements(QualType DeclType);
217 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000218
Douglas Gregor2bb07652009-12-22 00:05:34 +0000219 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
220 const InitializedEntity &ParentEntity,
221 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000222 void FillInValueInitializations(const InitializedEntity &Entity,
223 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000224public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000225 InitListChecker(Sema &S, const InitializedEntity &Entity,
226 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 bool HadError() { return hadError; }
228
229 // @brief Retrieves the fully-structured initializer list used for
230 // semantic analysis and code generation.
231 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
232};
Chris Lattner9ececce2009-02-24 22:48:58 +0000233} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000234
Douglas Gregor2bb07652009-12-22 00:05:34 +0000235void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
236 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000238 bool &RequiresSecondPass) {
239 SourceLocation Loc = ILE->getSourceRange().getBegin();
240 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000241 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000242 = InitializedEntity::InitializeMember(Field, &ParentEntity);
243 if (Init >= NumInits || !ILE->getInit(Init)) {
244 // FIXME: We probably don't need to handle references
245 // specially here, since value-initialization of references is
246 // handled in InitializationSequence.
247 if (Field->getType()->isReferenceType()) {
248 // C++ [dcl.init.aggr]p9:
249 // If an incomplete or empty initializer-list leaves a
250 // member of reference type uninitialized, the program is
251 // ill-formed.
252 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
253 << Field->getType()
254 << ILE->getSyntacticForm()->getSourceRange();
255 SemaRef.Diag(Field->getLocation(),
256 diag::note_uninit_reference_member);
257 hadError = true;
258 return;
259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000260
Douglas Gregor2bb07652009-12-22 00:05:34 +0000261 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
262 true);
263 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
264 if (!InitSeq) {
265 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
266 hadError = true;
267 return;
268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269
John McCalldadc5752010-08-24 06:29:42 +0000270 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000271 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000272 if (MemberInit.isInvalid()) {
273 hadError = true;
274 return;
275 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276
Douglas Gregor2bb07652009-12-22 00:05:34 +0000277 if (hadError) {
278 // Do nothing
279 } else if (Init < NumInits) {
280 ILE->setInit(Init, MemberInit.takeAs<Expr>());
281 } else if (InitSeq.getKind()
282 == InitializationSequence::ConstructorInitialization) {
283 // Value-initialization requires a constructor call, so
284 // extend the initializer list to include the constructor
285 // call and make a note that we'll need to take another pass
286 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000287 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000288 RequiresSecondPass = true;
289 }
290 } else if (InitListExpr *InnerILE
291 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292 FillInValueInitializations(MemberEntity, InnerILE,
293 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000294}
295
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000296/// Recursively replaces NULL values within the given initializer list
297/// with expressions that perform value-initialization of the
298/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000299void
Douglas Gregor723796a2009-12-16 06:35:08 +0000300InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
301 InitListExpr *ILE,
302 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000303 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000304 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000305 SourceLocation Loc = ILE->getSourceRange().getBegin();
306 if (ILE->getSyntacticForm())
307 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000308
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000309 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000310 if (RType->getDecl()->isUnion() &&
311 ILE->getInitializedFieldInUnion())
312 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
313 Entity, ILE, RequiresSecondPass);
314 else {
315 unsigned Init = 0;
316 for (RecordDecl::field_iterator
317 Field = RType->getDecl()->field_begin(),
318 FieldEnd = RType->getDecl()->field_end();
319 Field != FieldEnd; ++Field) {
320 if (Field->isUnnamedBitfield())
321 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000322
Douglas Gregor2bb07652009-12-22 00:05:34 +0000323 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000324 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000325
326 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
327 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000328 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000329
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000331
Douglas Gregor2bb07652009-12-22 00:05:34 +0000332 // Only look at the first initialization of a union.
333 if (RType->getDecl()->isUnion())
334 break;
335 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000336 }
337
338 return;
Mike Stump11289f42009-09-09 15:08:12 +0000339 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000340
341 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000342
Douglas Gregor723796a2009-12-16 06:35:08 +0000343 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000344 unsigned NumInits = ILE->getNumInits();
345 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000346 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000347 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000348 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
349 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000350 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000351 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000352 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000353 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000354 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000356 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000357 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000358 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000359
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000361 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000362 if (hadError)
363 return;
364
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000365 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
366 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000367 ElementEntity.setElementIndex(Init);
368
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000369 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000370 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
371 true);
372 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
373 if (!InitSeq) {
374 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000375 hadError = true;
376 return;
377 }
378
John McCalldadc5752010-08-24 06:29:42 +0000379 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000380 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000381 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000382 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000383 return;
384 }
385
386 if (hadError) {
387 // Do nothing
388 } else if (Init < NumInits) {
389 ILE->setInit(Init, ElementInit.takeAs<Expr>());
390 } else if (InitSeq.getKind()
391 == InitializationSequence::ConstructorInitialization) {
392 // Value-initialization requires a constructor call, so
393 // extend the initializer list to include the constructor
394 // call and make a note that we'll need to take another pass
395 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000396 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 RequiresSecondPass = true;
398 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000399 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000400 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
401 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000402 }
403}
404
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000405
Douglas Gregor723796a2009-12-16 06:35:08 +0000406InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
407 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000408 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000409 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000410
Eli Friedman23a9e312008-05-19 19:16:24 +0000411 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000412 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000413 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000414 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000416 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000417 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000418
Douglas Gregor723796a2009-12-16 06:35:08 +0000419 if (!hadError) {
420 bool RequiresSecondPass = false;
421 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000422 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000423 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000424 RequiresSecondPass);
425 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000426}
427
428int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000429 // FIXME: use a proper constant
430 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000431 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000432 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000433 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
434 }
435 return maxElements;
436}
437
438int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000439 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000440 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000441 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000442 Field = structDecl->field_begin(),
443 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000444 Field != FieldEnd; ++Field) {
445 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
446 ++InitializableMembers;
447 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000448 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000449 return std::min(InitializableMembers, 1);
450 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000451}
452
Anders Carlsson6cabf312010-01-23 23:23:01 +0000453void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000454 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000455 QualType T, unsigned &Index,
456 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000457 unsigned &StructuredIndex,
458 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000459 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000460
Steve Narofff8ecff22008-05-01 22:18:59 +0000461 if (T->isArrayType())
462 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000463 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000464 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000465 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000466 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000467 else
468 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000469
Eli Friedmane0f832b2008-05-25 13:49:22 +0000470 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000471 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000472 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000473 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000474 hadError = true;
475 return;
476 }
477
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000478 // Build a structured initializer list corresponding to this subobject.
479 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000480 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
481 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000482 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
483 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000484 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000485
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000486 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000487 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000489 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000490 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000491 StructuredSubobjectInitIndex,
492 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000493 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000494 StructuredSubobjectInitList->setType(T);
495
Douglas Gregor5741efb2009-03-01 17:12:46 +0000496 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000497 // range corresponds with the end of the last initializer it used.
498 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000499 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000500 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
501 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Tanya Lattner5029d562010-03-07 04:17:15 +0000504 // Warn about missing braces.
505 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000506 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
507 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000508 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000509 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000510 "{")
511 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000512 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000513 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000514 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000515}
516
Anders Carlsson6cabf312010-01-23 23:23:01 +0000517void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000518 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000519 unsigned &Index,
520 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000521 unsigned &StructuredIndex,
522 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000523 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000524 SyntacticToSemantic[IList] = StructuredList;
525 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000527 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000528 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
529 IList->setType(ExprTy);
530 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000531 if (hadError)
532 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000533
Eli Friedman85f54972008-05-25 13:22:35 +0000534 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000535 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000536 if (StructuredIndex == 1 &&
537 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000538 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000539 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000540 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000541 hadError = true;
542 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000543 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000544 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000545 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000546 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000547 // Don't complain for incomplete types, since we'll get an error
548 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000549 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000550 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000551 CurrentObjectType->isArrayType()? 0 :
552 CurrentObjectType->isVectorType()? 1 :
553 CurrentObjectType->isScalarType()? 2 :
554 CurrentObjectType->isUnionType()? 3 :
555 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000556
557 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000558 if (SemaRef.getLangOptions().CPlusPlus) {
559 DK = diag::err_excess_initializers;
560 hadError = true;
561 }
Nate Begeman425038c2009-07-07 21:53:06 +0000562 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
563 DK = diag::err_excess_initializers;
564 hadError = true;
565 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000566
Chris Lattnerb0912a52009-02-24 22:50:46 +0000567 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000568 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000569 }
570 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000571
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000572 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000573 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000574 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000575 << FixItHint::CreateRemoval(IList->getLocStart())
576 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000577}
578
Anders Carlsson6cabf312010-01-23 23:23:01 +0000579void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000580 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000581 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000582 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000583 unsigned &Index,
584 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000585 unsigned &StructuredIndex,
586 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000587 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000588 CheckScalarType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000590 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000592 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000593 } else if (DeclType->isAggregateType()) {
594 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000595 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000596 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000597 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000598 StructuredList, StructuredIndex,
599 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000600 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000601 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000602 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000603 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000605 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000606 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000607 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000608 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000609 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
610 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000611 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000612 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000613 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000614 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000615 } else if (DeclType->isRecordType()) {
616 // C++ [dcl.init]p14:
617 // [...] If the class is an aggregate (8.5.1), and the initializer
618 // is a brace-enclosed list, see 8.5.1.
619 //
620 // Note: 8.5.1 is handled below; here, we diagnose the case where
621 // we have an initializer list and a destination type that is not
622 // an aggregate.
623 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000624 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000625 << DeclType << IList->getSourceRange();
626 hadError = true;
627 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000628 CheckReferenceType(Entity, IList, DeclType, Index,
629 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000630 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000631 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
632 << DeclType;
633 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000634 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000635 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
636 << DeclType;
637 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000638 }
639}
640
Anders Carlsson6cabf312010-01-23 23:23:01 +0000641void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000642 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000643 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000644 unsigned &Index,
645 InitListExpr *StructuredList,
646 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000647 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000648 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
649 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000650 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000651 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000652 = getStructuredSubobjectInit(IList, Index, ElemType,
653 StructuredList, StructuredIndex,
654 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000655 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000656 newStructuredList, newStructuredIndex);
657 ++StructuredIndex;
658 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000659 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000660 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000661 return CheckScalarType(Entity, IList, ElemType, Index,
662 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000663 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000664 return CheckReferenceType(Entity, IList, ElemType, Index,
665 StructuredList, StructuredIndex);
666 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000667
John McCall5decec92011-02-21 07:57:55 +0000668 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
669 // arrayType can be incomplete if we're initializing a flexible
670 // array member. There's nothing we can do with the completed
671 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
John McCall5decec92011-02-21 07:57:55 +0000673 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
674 CheckStringInit(Str, ElemType, arrayType, SemaRef);
675 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000676 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000677 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000678 }
John McCall5decec92011-02-21 07:57:55 +0000679
680 // Fall through for subaggregate initialization.
681
682 } else if (SemaRef.getLangOptions().CPlusPlus) {
683 // C++ [dcl.init.aggr]p12:
684 // All implicit type conversions (clause 4) are considered when
685 // initializing the aggregate member with an ini- tializer from
686 // an initializer-list. If the initializer can initialize a
687 // member, the member is initialized. [...]
688
689 // FIXME: Better EqualLoc?
690 InitializationKind Kind =
691 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
692 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
693
694 if (Seq) {
695 ExprResult Result =
696 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
697 if (Result.isInvalid())
698 hadError = true;
699
700 UpdateStructuredListElement(StructuredList, StructuredIndex,
701 Result.takeAs<Expr>());
702 ++Index;
703 return;
704 }
705
706 // Fall through for subaggregate initialization
707 } else {
708 // C99 6.7.8p13:
709 //
710 // The initializer for a structure or union object that has
711 // automatic storage duration shall be either an initializer
712 // list as described below, or a single expression that has
713 // compatible structure or union type. In the latter case, the
714 // initial value of the object, including unnamed members, is
715 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000716 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000717 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000718 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000719 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000720 if (ExprRes.isInvalid())
721 hadError = true;
722 else {
723 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
724 if (ExprRes.isInvalid())
725 hadError = true;
726 }
727 UpdateStructuredListElement(StructuredList, StructuredIndex,
728 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000729 ++Index;
730 return;
731 }
John Wiegley01296292011-04-08 18:41:53 +0000732 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000733 // Fall through for subaggregate initialization
734 }
735
736 // C++ [dcl.init.aggr]p12:
737 //
738 // [...] Otherwise, if the member is itself a non-empty
739 // subaggregate, brace elision is assumed and the initializer is
740 // considered for the initialization of the first member of
741 // the subaggregate.
742 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
743 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
744 StructuredIndex);
745 ++StructuredIndex;
746 } else {
747 // We cannot initialize this element, so let
748 // PerformCopyInitialization produce the appropriate diagnostic.
749 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
750 SemaRef.Owned(expr));
751 hadError = true;
752 ++Index;
753 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000754 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000755}
756
Anders Carlsson6cabf312010-01-23 23:23:01 +0000757void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000758 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000759 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000760 InitListExpr *StructuredList,
761 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000762 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000763 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000764 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000765 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000766 ++Index;
767 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000768 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000769 }
John McCall643169b2010-11-11 00:46:36 +0000770
771 Expr *expr = IList->getInit(Index);
772 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
773 SemaRef.Diag(SubIList->getLocStart(),
774 diag::warn_many_braces_around_scalar_init)
775 << SubIList->getSourceRange();
776
777 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
778 StructuredIndex);
779 return;
780 } else if (isa<DesignatedInitExpr>(expr)) {
781 SemaRef.Diag(expr->getSourceRange().getBegin(),
782 diag::err_designator_for_scalar_init)
783 << DeclType << expr->getSourceRange();
784 hadError = true;
785 ++Index;
786 ++StructuredIndex;
787 return;
788 }
789
790 ExprResult Result =
791 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
792 SemaRef.Owned(expr));
793
794 Expr *ResultExpr = 0;
795
796 if (Result.isInvalid())
797 hadError = true; // types weren't compatible.
798 else {
799 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
John McCall643169b2010-11-11 00:46:36 +0000801 if (ResultExpr != expr) {
802 // The type was promoted, update initializer list.
803 IList->setInit(Index, ResultExpr);
804 }
805 }
806 if (hadError)
807 ++StructuredIndex;
808 else
809 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
810 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000811}
812
Anders Carlsson6cabf312010-01-23 23:23:01 +0000813void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
814 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000815 unsigned &Index,
816 InitListExpr *StructuredList,
817 unsigned &StructuredIndex) {
818 if (Index < IList->getNumInits()) {
819 Expr *expr = IList->getInit(Index);
820 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000821 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000822 << DeclType << IList->getSourceRange();
823 hadError = true;
824 ++Index;
825 ++StructuredIndex;
826 return;
Mike Stump11289f42009-09-09 15:08:12 +0000827 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000828
John McCalldadc5752010-08-24 06:29:42 +0000829 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000830 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
831 SemaRef.Owned(expr));
832
833 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000834 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000835
836 expr = Result.takeAs<Expr>();
837 IList->setInit(Index, expr);
838
Douglas Gregord14247a2009-01-30 22:09:00 +0000839 if (hadError)
840 ++StructuredIndex;
841 else
842 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
843 ++Index;
844 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000845 // FIXME: It would be wonderful if we could point at the actual member. In
846 // general, it would be useful to pass location information down the stack,
847 // so that we know the location (or decl) of the "current object" being
848 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000849 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000850 diag::err_init_reference_member_uninitialized)
851 << DeclType
852 << IList->getSourceRange();
853 hadError = true;
854 ++Index;
855 ++StructuredIndex;
856 return;
857 }
858}
859
Anders Carlsson6cabf312010-01-23 23:23:01 +0000860void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000861 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000862 unsigned &Index,
863 InitListExpr *StructuredList,
864 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000865 if (Index >= IList->getNumInits())
866 return;
Mike Stump11289f42009-09-09 15:08:12 +0000867
John McCall6a16b2f2010-10-30 00:11:39 +0000868 const VectorType *VT = DeclType->getAs<VectorType>();
869 unsigned maxElements = VT->getNumElements();
870 unsigned numEltsInit = 0;
871 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000872
John McCall6a16b2f2010-10-30 00:11:39 +0000873 if (!SemaRef.getLangOptions().OpenCL) {
874 // If the initializing element is a vector, try to copy-initialize
875 // instead of breaking it apart (which is doomed to failure anyway).
876 Expr *Init = IList->getInit(Index);
877 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
878 ExprResult Result =
879 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
880 SemaRef.Owned(Init));
881
882 Expr *ResultExpr = 0;
883 if (Result.isInvalid())
884 hadError = true; // types weren't compatible.
885 else {
886 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887
John McCall6a16b2f2010-10-30 00:11:39 +0000888 if (ResultExpr != Init) {
889 // The type was promoted, update initializer list.
890 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000891 }
892 }
John McCall6a16b2f2010-10-30 00:11:39 +0000893 if (hadError)
894 ++StructuredIndex;
895 else
896 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
897 ++Index;
898 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000899 }
Mike Stump11289f42009-09-09 15:08:12 +0000900
John McCall6a16b2f2010-10-30 00:11:39 +0000901 InitializedEntity ElementEntity =
902 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903
John McCall6a16b2f2010-10-30 00:11:39 +0000904 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
905 // Don't attempt to go past the end of the init list
906 if (Index >= IList->getNumInits())
907 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000908
John McCall6a16b2f2010-10-30 00:11:39 +0000909 ElementEntity.setElementIndex(Index);
910 CheckSubElementType(ElementEntity, IList, elementType, Index,
911 StructuredList, StructuredIndex);
912 }
913 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000914 }
John McCall6a16b2f2010-10-30 00:11:39 +0000915
916 InitializedEntity ElementEntity =
917 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
John McCall6a16b2f2010-10-30 00:11:39 +0000919 // OpenCL initializers allows vectors to be constructed from vectors.
920 for (unsigned i = 0; i < maxElements; ++i) {
921 // Don't attempt to go past the end of the init list
922 if (Index >= IList->getNumInits())
923 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000924
John McCall6a16b2f2010-10-30 00:11:39 +0000925 ElementEntity.setElementIndex(Index);
926
927 QualType IType = IList->getInit(Index)->getType();
928 if (!IType->isVectorType()) {
929 CheckSubElementType(ElementEntity, IList, elementType, Index,
930 StructuredList, StructuredIndex);
931 ++numEltsInit;
932 } else {
933 QualType VecType;
934 const VectorType *IVT = IType->getAs<VectorType>();
935 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936
John McCall6a16b2f2010-10-30 00:11:39 +0000937 if (IType->isExtVectorType())
938 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
939 else
940 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000941 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000942 CheckSubElementType(ElementEntity, IList, VecType, Index,
943 StructuredList, StructuredIndex);
944 numEltsInit += numIElts;
945 }
946 }
947
948 // OpenCL requires all elements to be initialized.
949 if (numEltsInit != maxElements)
950 if (SemaRef.getLangOptions().OpenCL)
951 SemaRef.Diag(IList->getSourceRange().getBegin(),
952 diag::err_vector_incorrect_num_initializers)
953 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000954}
955
Anders Carlsson6cabf312010-01-23 23:23:01 +0000956void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000957 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000958 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000959 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000960 unsigned &Index,
961 InitListExpr *StructuredList,
962 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000963 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
964
Steve Narofff8ecff22008-05-01 22:18:59 +0000965 // Check for the special-case of initializing an array with a string.
966 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +0000967 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000968 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +0000969 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000970 // We place the string literal directly into the resulting
971 // initializer list. This is the only place where the structure
972 // of the structured initializer list doesn't match exactly,
973 // because doing so would involve allocating one character
974 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000975 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000976 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000977 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000978 return;
979 }
980 }
John McCall66884dd2011-02-21 07:22:22 +0000981 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000982 // Check for VLAs; in standard C it would be possible to check this
983 // earlier, but I don't know where clang accepts VLAs (gcc accepts
984 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000985 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000986 diag::err_variable_object_no_init)
987 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000988 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000989 ++Index;
990 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000991 return;
992 }
993
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000994 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000995 llvm::APSInt maxElements(elementIndex.getBitWidth(),
996 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000997 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +0000998 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000999 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001000 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001001 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001002 maxElementsKnown = true;
1003 }
1004
John McCall66884dd2011-02-21 07:22:22 +00001005 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001006 while (Index < IList->getNumInits()) {
1007 Expr *Init = IList->getInit(Index);
1008 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001009 // If we're not the subobject that matches up with the '{' for
1010 // the designator, we shouldn't be handling the
1011 // designator. Return immediately.
1012 if (!SubobjectIsDesignatorContext)
1013 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001014
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001015 // Handle this designated initializer. elementIndex will be
1016 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001017 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001018 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001019 StructuredList, StructuredIndex, true,
1020 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001021 hadError = true;
1022 continue;
1023 }
1024
Douglas Gregor033d1252009-01-23 16:54:12 +00001025 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001026 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001027 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001028 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001029 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001030
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001031 // If the array is of incomplete type, keep track of the number of
1032 // elements in the initializer.
1033 if (!maxElementsKnown && elementIndex > maxElements)
1034 maxElements = elementIndex;
1035
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001036 continue;
1037 }
1038
1039 // If we know the maximum number of elements, and we've already
1040 // hit it, stop consuming elements in the initializer list.
1041 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001042 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001043
Anders Carlsson6cabf312010-01-23 23:23:01 +00001044 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001046 Entity);
1047 // Check this element.
1048 CheckSubElementType(ElementEntity, IList, elementType, Index,
1049 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001050 ++elementIndex;
1051
1052 // If the array is of incomplete type, keep track of the number of
1053 // elements in the initializer.
1054 if (!maxElementsKnown && elementIndex > maxElements)
1055 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001056 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001057 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001058 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001059 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001060 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001061 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001062 // Sizing an array implicitly to zero is not allowed by ISO C,
1063 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001064 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001065 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001066 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001067
Mike Stump11289f42009-09-09 15:08:12 +00001068 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001069 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001070 }
1071}
1072
Anders Carlsson6cabf312010-01-23 23:23:01 +00001073void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001074 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001075 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001076 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001077 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001078 unsigned &Index,
1079 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001080 unsigned &StructuredIndex,
1081 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001082 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001083
Eli Friedman23a9e312008-05-19 19:16:24 +00001084 // If the record is invalid, some of it's members are invalid. To avoid
1085 // confusion, we forgo checking the intializer for the entire record.
1086 if (structDecl->isInvalidDecl()) {
1087 hadError = true;
1088 return;
Mike Stump11289f42009-09-09 15:08:12 +00001089 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001090
1091 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1092 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001093 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001094 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001095 Field != FieldEnd; ++Field) {
1096 if (Field->getDeclName()) {
1097 StructuredList->setInitializedFieldInUnion(*Field);
1098 break;
1099 }
1100 }
1101 return;
1102 }
1103
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001104 // If structDecl is a forward declaration, this loop won't do
1105 // anything except look at designated initializers; That's okay,
1106 // because an error should get printed out elsewhere. It might be
1107 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001108 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001109 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001110 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001111 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001112 while (Index < IList->getNumInits()) {
1113 Expr *Init = IList->getInit(Index);
1114
1115 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001116 // If we're not the subobject that matches up with the '{' for
1117 // the designator, we shouldn't be handling the
1118 // designator. Return immediately.
1119 if (!SubobjectIsDesignatorContext)
1120 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001121
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001122 // Handle this designated initializer. Field will be updated to
1123 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001124 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001125 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001126 StructuredList, StructuredIndex,
1127 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001128 hadError = true;
1129
Douglas Gregora9add4e2009-02-12 19:00:39 +00001130 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001131
1132 // Disable check for missing fields when designators are used.
1133 // This matches gcc behaviour.
1134 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001135 continue;
1136 }
1137
1138 if (Field == FieldEnd) {
1139 // We've run out of fields. We're done.
1140 break;
1141 }
1142
Douglas Gregora9add4e2009-02-12 19:00:39 +00001143 // We've already initialized a member of a union. We're done.
1144 if (InitializedSomething && DeclType->isUnionType())
1145 break;
1146
Douglas Gregor91f84212008-12-11 16:49:14 +00001147 // If we've hit the flexible array member at the end, we're done.
1148 if (Field->getType()->isIncompleteArrayType())
1149 break;
1150
Douglas Gregor51695702009-01-29 16:53:55 +00001151 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001152 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001153 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001154 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001155 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001156
Anders Carlsson6cabf312010-01-23 23:23:01 +00001157 InitializedEntity MemberEntity =
1158 InitializedEntity::InitializeMember(*Field, &Entity);
1159 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1160 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001161 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001162
1163 if (DeclType->isUnionType()) {
1164 // Initialize the first field within the union.
1165 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001166 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001167
1168 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001169 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001170
John McCalle40b58e2010-03-11 19:32:38 +00001171 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001173 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1174 // It is possible we have one or more unnamed bitfields remaining.
1175 // Find first (if any) named field and emit warning.
1176 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1177 it != end; ++it) {
1178 if (!it->isUnnamedBitfield()) {
1179 SemaRef.Diag(IList->getSourceRange().getEnd(),
1180 diag::warn_missing_field_initializers) << it->getName();
1181 break;
1182 }
1183 }
1184 }
1185
Mike Stump11289f42009-09-09 15:08:12 +00001186 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001187 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001188 return;
1189
1190 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001191 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001192 (!isa<InitListExpr>(IList->getInit(Index)) ||
1193 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001194 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001195 diag::err_flexible_array_init_nonempty)
1196 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001197 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001198 << *Field;
1199 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001200 ++Index;
1201 return;
1202 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001203 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001204 diag::ext_flexible_array_init)
1205 << IList->getInit(Index)->getSourceRange().getBegin();
1206 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1207 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001208 }
1209
Anders Carlsson6cabf312010-01-23 23:23:01 +00001210 InitializedEntity MemberEntity =
1211 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001212
Anders Carlsson6cabf312010-01-23 23:23:01 +00001213 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001214 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001215 StructuredList, StructuredIndex);
1216 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001218 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001219}
Steve Narofff8ecff22008-05-01 22:18:59 +00001220
Douglas Gregord5846a12009-04-15 06:41:24 +00001221/// \brief Expand a field designator that refers to a member of an
1222/// anonymous struct or union into a series of field designators that
1223/// refers to the field within the appropriate subobject.
1224///
Douglas Gregord5846a12009-04-15 06:41:24 +00001225static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001226 DesignatedInitExpr *DIE,
1227 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001228 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001229 typedef DesignatedInitExpr::Designator Designator;
1230
Douglas Gregord5846a12009-04-15 06:41:24 +00001231 // Build the replacement designators.
1232 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001233 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1234 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1235 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001236 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001237 DIE->getDesignator(DesigIdx)->getDotLoc(),
1238 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1239 else
1240 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1241 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001242 assert(isa<FieldDecl>(*PI));
1243 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001244 }
1245
1246 // Expand the current designator into the set of replacement
1247 // designators, so we have a full subobject path down to where the
1248 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001249 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001250 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001251}
Mike Stump11289f42009-09-09 15:08:12 +00001252
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001254/// corresponds to FieldName.
1255static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1256 IdentifierInfo *FieldName) {
1257 assert(AnonField->isAnonymousStructOrUnion());
1258 Decl *NextDecl = AnonField->getNextDeclInContext();
1259 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1260 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1261 return IF;
1262 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001263 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001264 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001265}
1266
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001267/// @brief Check the well-formedness of a C99 designated initializer.
1268///
1269/// Determines whether the designated initializer @p DIE, which
1270/// resides at the given @p Index within the initializer list @p
1271/// IList, is well-formed for a current object of type @p DeclType
1272/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001273/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001274/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001275///
1276/// @param IList The initializer list in which this designated
1277/// initializer occurs.
1278///
Douglas Gregora5324162009-04-15 04:56:10 +00001279/// @param DIE The designated initializer expression.
1280///
1281/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001282///
1283/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1284/// into which the designation in @p DIE should refer.
1285///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001286/// @param NextField If non-NULL and the first designator in @p DIE is
1287/// a field, this will be set to the field declaration corresponding
1288/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001289///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001290/// @param NextElementIndex If non-NULL and the first designator in @p
1291/// DIE is an array designator or GNU array-range designator, this
1292/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001293///
1294/// @param Index Index into @p IList where the designated initializer
1295/// @p DIE occurs.
1296///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001297/// @param StructuredList The initializer list expression that
1298/// describes all of the subobject initializers in the order they'll
1299/// actually be initialized.
1300///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001301/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001302bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001303InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001304 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001305 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001306 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001307 QualType &CurrentObjectType,
1308 RecordDecl::field_iterator *NextField,
1309 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001310 unsigned &Index,
1311 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001312 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001313 bool FinishSubobjectInit,
1314 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001315 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001316 // Check the actual initialization for the designated object type.
1317 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001318
1319 // Temporarily remove the designator expression from the
1320 // initializer list that the child calls see, so that we don't try
1321 // to re-process the designator.
1322 unsigned OldIndex = Index;
1323 IList->setInit(OldIndex, DIE->getInit());
1324
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001325 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001326 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001327
1328 // Restore the designated initializer expression in the syntactic
1329 // form of the initializer list.
1330 if (IList->getInit(OldIndex) != DIE->getInit())
1331 DIE->setInit(IList->getInit(OldIndex));
1332 IList->setInit(OldIndex, DIE);
1333
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001334 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001335 }
1336
Douglas Gregora5324162009-04-15 04:56:10 +00001337 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001338 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001339 "Need a non-designated initializer list to start from");
1340
Douglas Gregora5324162009-04-15 04:56:10 +00001341 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001342 // Determine the structural initializer list that corresponds to the
1343 // current subobject.
1344 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001345 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001346 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001347 SourceRange(D->getStartLocation(),
1348 DIE->getSourceRange().getEnd()));
1349 assert(StructuredList && "Expected a structured initializer list");
1350
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001351 if (D->isFieldDesignator()) {
1352 // C99 6.7.8p7:
1353 //
1354 // If a designator has the form
1355 //
1356 // . identifier
1357 //
1358 // then the current object (defined below) shall have
1359 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001360 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001361 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001362 if (!RT) {
1363 SourceLocation Loc = D->getDotLoc();
1364 if (Loc.isInvalid())
1365 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001366 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1367 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001368 ++Index;
1369 return true;
1370 }
1371
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001372 // Note: we perform a linear search of the fields here, despite
1373 // the fact that we have a faster lookup method, because we always
1374 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001375 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001376 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001377 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001378 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001379 Field = RT->getDecl()->field_begin(),
1380 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001381 for (; Field != FieldEnd; ++Field) {
1382 if (Field->isUnnamedBitfield())
1383 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001385 // If we find a field representing an anonymous field, look in the
1386 // IndirectFieldDecl that follow for the designated initializer.
1387 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1388 if (IndirectFieldDecl *IF =
1389 FindIndirectFieldDesignator(*Field, FieldName)) {
1390 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1391 D = DIE->getDesignator(DesigIdx);
1392 break;
1393 }
1394 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001395 if (KnownField && KnownField == *Field)
1396 break;
1397 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001398 break;
1399
1400 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001401 }
1402
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001403 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001404 // There was no normal field in the struct with the designated
1405 // name. Perform another lookup for this name, which may find
1406 // something that we can't designate (e.g., a member function),
1407 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001408 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001409 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001410 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001411 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001412 // Name lookup didn't find anything. Determine whether this
1413 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001415 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001416 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001417 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001418 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001419 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001420 ->Equals(RT->getDecl())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001422 diag::err_field_designator_unknown_suggest)
1423 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001424 << FixItHint::CreateReplacement(D->getFieldLoc(),
1425 R.getLookupName().getAsString());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001426 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregor6da83622010-01-07 00:17:44 +00001427 diag::note_previous_decl)
1428 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001429 } else {
1430 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1431 << FieldName << CurrentObjectType;
1432 ++Index;
1433 return true;
1434 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001436
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001437 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001438 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001439 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001440 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001441 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001442 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001443 ++Index;
1444 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001445 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001446
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001447 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001448 // The replacement field comes from typo correction; find it
1449 // in the list of fields.
1450 FieldIndex = 0;
1451 Field = RT->getDecl()->field_begin();
1452 for (; Field != FieldEnd; ++Field) {
1453 if (Field->isUnnamedBitfield())
1454 continue;
1455
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001457 Field->getIdentifier() == ReplacementField->getIdentifier())
1458 break;
1459
1460 ++FieldIndex;
1461 }
1462 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001463 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001464
1465 // All of the fields of a union are located at the same place in
1466 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001467 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001468 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001469 StructuredList->setInitializedFieldInUnion(*Field);
1470 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001471
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001472 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001473 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001474
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001475 // Make sure that our non-designated initializer list has space
1476 // for a subobject corresponding to this field.
1477 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001478 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001479
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001480 // This designator names a flexible array member.
1481 if (Field->getType()->isIncompleteArrayType()) {
1482 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001483 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001484 // We can't designate an object within the flexible array
1485 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001486 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001487 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001488 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001489 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001490 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001491 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001492 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001493 << *Field;
1494 Invalid = true;
1495 }
1496
Chris Lattner001b29c2010-10-10 17:49:49 +00001497 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1498 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001499 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001500 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001501 diag::err_flexible_array_init_needs_braces)
1502 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001503 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001504 << *Field;
1505 Invalid = true;
1506 }
1507
1508 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001509 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001510 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001511 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001512 diag::err_flexible_array_init_nonempty)
1513 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001514 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001515 << *Field;
1516 Invalid = true;
1517 }
1518
1519 if (Invalid) {
1520 ++Index;
1521 return true;
1522 }
1523
1524 // Initialize the array.
1525 bool prevHadError = hadError;
1526 unsigned newStructuredIndex = FieldIndex;
1527 unsigned OldIndex = Index;
1528 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001529
1530 InitializedEntity MemberEntity =
1531 InitializedEntity::InitializeMember(*Field, &Entity);
1532 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001533 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001534
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001535 IList->setInit(OldIndex, DIE);
1536 if (hadError && !prevHadError) {
1537 ++Field;
1538 ++FieldIndex;
1539 if (NextField)
1540 *NextField = Field;
1541 StructuredIndex = FieldIndex;
1542 return true;
1543 }
1544 } else {
1545 // Recurse to check later designated subobjects.
1546 QualType FieldType = (*Field)->getType();
1547 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001548
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001549 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001550 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1552 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001553 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001554 true, false))
1555 return true;
1556 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001557
1558 // Find the position of the next field to be initialized in this
1559 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001560 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001561 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001562
1563 // If this the first designator, our caller will continue checking
1564 // the rest of this struct/class/union subobject.
1565 if (IsFirstDesignator) {
1566 if (NextField)
1567 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001568 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001569 return false;
1570 }
1571
Douglas Gregor17bd0942009-01-28 23:36:17 +00001572 if (!FinishSubobjectInit)
1573 return false;
1574
Douglas Gregord5846a12009-04-15 06:41:24 +00001575 // We've already initialized something in the union; we're done.
1576 if (RT->getDecl()->isUnion())
1577 return hadError;
1578
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001579 // Check the remaining fields within this class/struct/union subobject.
1580 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001581
Anders Carlsson6cabf312010-01-23 23:23:01 +00001582 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001583 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001584 return hadError && !prevHadError;
1585 }
1586
1587 // C99 6.7.8p6:
1588 //
1589 // If a designator has the form
1590 //
1591 // [ constant-expression ]
1592 //
1593 // then the current object (defined below) shall have array
1594 // type and the expression shall be an integer constant
1595 // expression. If the array is of unknown size, any
1596 // nonnegative value is valid.
1597 //
1598 // Additionally, cope with the GNU extension that permits
1599 // designators of the form
1600 //
1601 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001602 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001603 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001604 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001605 << CurrentObjectType;
1606 ++Index;
1607 return true;
1608 }
1609
1610 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001611 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1612 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001613 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001614 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001615 DesignatedEndIndex = DesignatedStartIndex;
1616 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001617 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001618
Mike Stump11289f42009-09-09 15:08:12 +00001619 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001620 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001621 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001622 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001623 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001624
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001625 // Codegen can't handle evaluating array range designators that have side
1626 // effects, because we replicate the AST value for each initialized element.
1627 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1628 // elements with something that has a side effect, so codegen can emit an
1629 // "error unsupported" error instead of miscompiling the app.
1630 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1631 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001632 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001633 }
1634
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001635 if (isa<ConstantArrayType>(AT)) {
1636 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001637 DesignatedStartIndex
1638 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001639 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001640 DesignatedEndIndex
1641 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001642 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1643 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001644 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001645 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001646 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001647 << IndexExpr->getSourceRange();
1648 ++Index;
1649 return true;
1650 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001651 } else {
1652 // Make sure the bit-widths and signedness match.
1653 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001654 DesignatedEndIndex
1655 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001656 else if (DesignatedStartIndex.getBitWidth() <
1657 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001658 DesignatedStartIndex
1659 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001660 DesignatedStartIndex.setIsUnsigned(true);
1661 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001662 }
Mike Stump11289f42009-09-09 15:08:12 +00001663
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001664 // Make sure that our non-designated initializer list has space
1665 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001666 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001667 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001668 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001669
Douglas Gregor17bd0942009-01-28 23:36:17 +00001670 // Repeatedly perform subobject initializations in the range
1671 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001672
Douglas Gregor17bd0942009-01-28 23:36:17 +00001673 // Move to the next designator
1674 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1675 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001677 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001678 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001679
Douglas Gregor17bd0942009-01-28 23:36:17 +00001680 while (DesignatedStartIndex <= DesignatedEndIndex) {
1681 // Recurse to check later designated subobjects.
1682 QualType ElementType = AT->getElementType();
1683 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001684
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001685 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001686 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1687 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001688 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001689 (DesignatedStartIndex == DesignatedEndIndex),
1690 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001691 return true;
1692
1693 // Move to the next index in the array that we'll be initializing.
1694 ++DesignatedStartIndex;
1695 ElementIndex = DesignatedStartIndex.getZExtValue();
1696 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001697
1698 // If this the first designator, our caller will continue checking
1699 // the rest of this array subobject.
1700 if (IsFirstDesignator) {
1701 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001702 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001703 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001704 return false;
1705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregor17bd0942009-01-28 23:36:17 +00001707 if (!FinishSubobjectInit)
1708 return false;
1709
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001710 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001711 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001712 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001713 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001714 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001715 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001716}
1717
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001718// Get the structured initializer list for a subobject of type
1719// @p CurrentObjectType.
1720InitListExpr *
1721InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1722 QualType CurrentObjectType,
1723 InitListExpr *StructuredList,
1724 unsigned StructuredIndex,
1725 SourceRange InitRange) {
1726 Expr *ExistingInit = 0;
1727 if (!StructuredList)
1728 ExistingInit = SyntacticToSemantic[IList];
1729 else if (StructuredIndex < StructuredList->getNumInits())
1730 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001731
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001732 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1733 return Result;
1734
1735 if (ExistingInit) {
1736 // We are creating an initializer list that initializes the
1737 // subobjects of the current object, but there was already an
1738 // initialization that completely initialized the current
1739 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001740 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 // struct X { int a, b; };
1742 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001743 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001744 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1745 // designated initializer re-initializes the whole
1746 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001747 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001748 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001749 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001750 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001751 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001752 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001753 << ExistingInit->getSourceRange();
1754 }
1755
Mike Stump11289f42009-09-09 15:08:12 +00001756 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001757 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1758 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001759 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001760
Douglas Gregora8a089b2010-07-13 18:40:04 +00001761 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001762
Douglas Gregor6d00c992009-03-20 23:58:33 +00001763 // Pre-allocate storage for the structured initializer list.
1764 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001765 unsigned NumInits = 0;
1766 if (!StructuredList)
1767 NumInits = IList->getNumInits();
1768 else if (Index < IList->getNumInits()) {
1769 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1770 NumInits = SubList->getNumInits();
1771 }
1772
Mike Stump11289f42009-09-09 15:08:12 +00001773 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001774 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1775 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1776 NumElements = CAType->getSize().getZExtValue();
1777 // Simple heuristic so that we don't allocate a very large
1778 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001779 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001780 NumElements = 0;
1781 }
John McCall9dd450b2009-09-21 23:43:11 +00001782 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001783 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001784 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001785 RecordDecl *RDecl = RType->getDecl();
1786 if (RDecl->isUnion())
1787 NumElements = 1;
1788 else
Mike Stump11289f42009-09-09 15:08:12 +00001789 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001790 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001791 }
1792
Douglas Gregor221c9a52009-03-21 18:13:52 +00001793 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001794 NumElements = IList->getNumInits();
1795
Ted Kremenekac034612010-04-13 23:39:13 +00001796 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001797
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001798 // Link this new initializer list into the structured initializer
1799 // lists.
1800 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001801 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001802 else {
1803 Result->setSyntacticForm(IList);
1804 SyntacticToSemantic[IList] = Result;
1805 }
1806
1807 return Result;
1808}
1809
1810/// Update the initializer at index @p StructuredIndex within the
1811/// structured initializer list to the value @p expr.
1812void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1813 unsigned &StructuredIndex,
1814 Expr *expr) {
1815 // No structured initializer list to update
1816 if (!StructuredList)
1817 return;
1818
Ted Kremenekac034612010-04-13 23:39:13 +00001819 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1820 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001821 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001822 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001823 diag::warn_initializer_overrides)
1824 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001825 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001826 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001827 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001828 << PrevInit->getSourceRange();
1829 }
Mike Stump11289f42009-09-09 15:08:12 +00001830
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001831 ++StructuredIndex;
1832}
1833
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001834/// Check that the given Index expression is a valid array designator
1835/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001836/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001837/// and produces a reasonable diagnostic if there is a
1838/// failure. Returns true if there was an error, false otherwise. If
1839/// everything went okay, Value will receive the value of the constant
1840/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001841static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001842CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001843 SourceLocation Loc = Index->getSourceRange().getBegin();
1844
1845 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001846 if (S.VerifyIntegerConstantExpression(Index, &Value))
1847 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001848
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001849 if (Value.isSigned() && Value.isNegative())
1850 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001851 << Value.toString(10) << Index->getSourceRange();
1852
Douglas Gregor51650d32009-01-23 21:04:18 +00001853 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001854 return false;
1855}
1856
John McCalldadc5752010-08-24 06:29:42 +00001857ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001858 SourceLocation Loc,
1859 bool GNUSyntax,
1860 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001861 typedef DesignatedInitExpr::Designator ASTDesignator;
1862
1863 bool Invalid = false;
1864 llvm::SmallVector<ASTDesignator, 32> Designators;
1865 llvm::SmallVector<Expr *, 32> InitExpressions;
1866
1867 // Build designators and check array designator expressions.
1868 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1869 const Designator &D = Desig.getDesignator(Idx);
1870 switch (D.getKind()) {
1871 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001872 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001873 D.getFieldLoc()));
1874 break;
1875
1876 case Designator::ArrayDesignator: {
1877 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1878 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001879 if (!Index->isTypeDependent() &&
1880 !Index->isValueDependent() &&
1881 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001882 Invalid = true;
1883 else {
1884 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001885 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001886 D.getRBracketLoc()));
1887 InitExpressions.push_back(Index);
1888 }
1889 break;
1890 }
1891
1892 case Designator::ArrayRangeDesignator: {
1893 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1894 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1895 llvm::APSInt StartValue;
1896 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001897 bool StartDependent = StartIndex->isTypeDependent() ||
1898 StartIndex->isValueDependent();
1899 bool EndDependent = EndIndex->isTypeDependent() ||
1900 EndIndex->isValueDependent();
1901 if ((!StartDependent &&
1902 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1903 (!EndDependent &&
1904 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001906 else {
1907 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001908 if (StartDependent || EndDependent) {
1909 // Nothing to compute.
1910 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001911 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001912 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001913 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001914
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001915 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001916 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001917 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001918 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1919 Invalid = true;
1920 } else {
1921 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001922 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001923 D.getEllipsisLoc(),
1924 D.getRBracketLoc()));
1925 InitExpressions.push_back(StartIndex);
1926 InitExpressions.push_back(EndIndex);
1927 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001928 }
1929 break;
1930 }
1931 }
1932 }
1933
1934 if (Invalid || Init.isInvalid())
1935 return ExprError();
1936
1937 // Clear out the expressions within the designation.
1938 Desig.ClearExprs(*this);
1939
1940 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001941 = DesignatedInitExpr::Create(Context,
1942 Designators.data(), Designators.size(),
1943 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001944 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945
Douglas Gregorc124e592011-01-16 16:13:16 +00001946 if (getLangOptions().CPlusPlus)
1947 Diag(DIE->getLocStart(), diag::ext_designated_init)
1948 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001950 return Owned(DIE);
1951}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001952
Douglas Gregor723796a2009-12-16 06:35:08 +00001953bool Sema::CheckInitList(const InitializedEntity &Entity,
1954 InitListExpr *&InitList, QualType &DeclType) {
1955 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001956 if (!CheckInitList.HadError())
1957 InitList = CheckInitList.getFullyStructuredList();
1958
1959 return CheckInitList.HadError();
1960}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001961
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001962//===----------------------------------------------------------------------===//
1963// Initialization entity
1964//===----------------------------------------------------------------------===//
1965
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00001967 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001969{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001970 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1971 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001972 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001973 } else {
1974 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001975 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001976 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001977}
1978
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001980 CXXBaseSpecifier *Base,
1981 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001982{
1983 InitializedEntity Result;
1984 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001985 Result.Base = reinterpret_cast<uintptr_t>(Base);
1986 if (IsInheritedVirtualBase)
1987 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988
Douglas Gregor1b303932009-12-22 15:35:07 +00001989 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001990 return Result;
1991}
1992
Douglas Gregor85dabae2009-12-16 01:38:02 +00001993DeclarationName InitializedEntity::getName() const {
1994 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001995 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001996 if (!VariableOrMember)
1997 return DeclarationName();
1998 // Fall through
1999
2000 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002001 case EK_Member:
2002 return VariableOrMember->getDeclName();
2003
2004 case EK_Result:
2005 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002006 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002007 case EK_Temporary:
2008 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002009 case EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002010 case EK_ArrayElement:
2011 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002012 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002013 return DeclarationName();
2014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Douglas Gregor85dabae2009-12-16 01:38:02 +00002016 // Silence GCC warning
2017 return DeclarationName();
2018}
2019
Douglas Gregora4b592a2009-12-19 03:01:41 +00002020DeclaratorDecl *InitializedEntity::getDecl() const {
2021 switch (getKind()) {
2022 case EK_Variable:
2023 case EK_Parameter:
2024 case EK_Member:
2025 return VariableOrMember;
2026
2027 case EK_Result:
2028 case EK_Exception:
2029 case EK_New:
2030 case EK_Temporary:
2031 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002032 case EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002033 case EK_ArrayElement:
2034 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002035 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002036 return 0;
2037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Douglas Gregora4b592a2009-12-19 03:01:41 +00002039 // Silence GCC warning
2040 return 0;
2041}
2042
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002043bool InitializedEntity::allowsNRVO() const {
2044 switch (getKind()) {
2045 case EK_Result:
2046 case EK_Exception:
2047 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002048
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002049 case EK_Variable:
2050 case EK_Parameter:
2051 case EK_Member:
2052 case EK_New:
2053 case EK_Temporary:
2054 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002055 case EK_Delegation:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002056 case EK_ArrayElement:
2057 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002058 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002059 break;
2060 }
2061
2062 return false;
2063}
2064
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002065//===----------------------------------------------------------------------===//
2066// Initialization sequence
2067//===----------------------------------------------------------------------===//
2068
2069void InitializationSequence::Step::Destroy() {
2070 switch (Kind) {
2071 case SK_ResolveAddressOfOverloadedFunction:
2072 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002073 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002074 case SK_CastDerivedToBaseLValue:
2075 case SK_BindReference:
2076 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002077 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002078 case SK_UserConversion:
2079 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002080 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002081 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002082 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002083 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002084 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002085 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002086 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002087 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002088 case SK_ArrayInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002089 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002091 case SK_ConversionSequence:
2092 delete ICS;
2093 }
2094}
2095
Douglas Gregor838fcc32010-03-26 20:14:36 +00002096bool InitializationSequence::isDirectReferenceBinding() const {
2097 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2098}
2099
2100bool InitializationSequence::isAmbiguous() const {
2101 if (getKind() != FailedSequence)
2102 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103
Douglas Gregor838fcc32010-03-26 20:14:36 +00002104 switch (getFailureKind()) {
2105 case FK_TooManyInitsForReference:
2106 case FK_ArrayNeedsInitList:
2107 case FK_ArrayNeedsInitListOrStringLiteral:
2108 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2109 case FK_NonConstLValueReferenceBindingToTemporary:
2110 case FK_NonConstLValueReferenceBindingToUnrelated:
2111 case FK_RValueReferenceBindingToLValue:
2112 case FK_ReferenceInitDropsQualifiers:
2113 case FK_ReferenceInitFailed:
2114 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002115 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002116 case FK_TooManyInitsForScalar:
2117 case FK_ReferenceBindingToInitList:
2118 case FK_InitListBadDestinationType:
2119 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002120 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002121 case FK_ArrayTypeMismatch:
2122 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002123 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Douglas Gregor838fcc32010-03-26 20:14:36 +00002125 case FK_ReferenceInitOverloadFailed:
2126 case FK_UserConversionOverloadFailed:
2127 case FK_ConstructorOverloadFailed:
2128 return FailedOverloadResult == OR_Ambiguous;
2129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Douglas Gregor838fcc32010-03-26 20:14:36 +00002131 return false;
2132}
2133
Douglas Gregorb33eed02010-04-16 22:09:46 +00002134bool InitializationSequence::isConstructorInitialization() const {
2135 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2136}
2137
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002138void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002139 FunctionDecl *Function,
2140 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002141 Step S;
2142 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2143 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002144 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002145 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002146 Steps.push_back(S);
2147}
2148
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002150 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002151 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002152 switch (VK) {
2153 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2154 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2155 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002156 default: llvm_unreachable("No such category");
2157 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002158 S.Type = BaseType;
2159 Steps.push_back(S);
2160}
2161
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002163 bool BindingTemporary) {
2164 Step S;
2165 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2166 S.Type = T;
2167 Steps.push_back(S);
2168}
2169
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002170void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2171 Step S;
2172 S.Kind = SK_ExtraneousCopyToTemporary;
2173 S.Type = T;
2174 Steps.push_back(S);
2175}
2176
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002177void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002178 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002179 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002180 Step S;
2181 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002182 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002183 S.Function.Function = Function;
2184 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002185 Steps.push_back(S);
2186}
2187
2188void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002189 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002190 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002191 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002192 switch (VK) {
2193 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002194 S.Kind = SK_QualificationConversionRValue;
2195 break;
John McCall2536c6d2010-08-25 10:28:54 +00002196 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002197 S.Kind = SK_QualificationConversionXValue;
2198 break;
John McCall2536c6d2010-08-25 10:28:54 +00002199 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002200 S.Kind = SK_QualificationConversionLValue;
2201 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002202 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002203 S.Type = Ty;
2204 Steps.push_back(S);
2205}
2206
2207void InitializationSequence::AddConversionSequenceStep(
2208 const ImplicitConversionSequence &ICS,
2209 QualType T) {
2210 Step S;
2211 S.Kind = SK_ConversionSequence;
2212 S.Type = T;
2213 S.ICS = new ImplicitConversionSequence(ICS);
2214 Steps.push_back(S);
2215}
2216
Douglas Gregor51e77d52009-12-10 17:56:55 +00002217void InitializationSequence::AddListInitializationStep(QualType T) {
2218 Step S;
2219 S.Kind = SK_ListInitialization;
2220 S.Type = T;
2221 Steps.push_back(S);
2222}
2223
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002224void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002225InitializationSequence::AddConstructorInitializationStep(
2226 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002227 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002228 QualType T) {
2229 Step S;
2230 S.Kind = SK_ConstructorInitialization;
2231 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002232 S.Function.Function = Constructor;
2233 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002234 Steps.push_back(S);
2235}
2236
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002237void InitializationSequence::AddZeroInitializationStep(QualType T) {
2238 Step S;
2239 S.Kind = SK_ZeroInitialization;
2240 S.Type = T;
2241 Steps.push_back(S);
2242}
2243
Douglas Gregore1314a62009-12-18 05:02:21 +00002244void InitializationSequence::AddCAssignmentStep(QualType T) {
2245 Step S;
2246 S.Kind = SK_CAssignment;
2247 S.Type = T;
2248 Steps.push_back(S);
2249}
2250
Eli Friedman78275202009-12-19 08:11:05 +00002251void InitializationSequence::AddStringInitStep(QualType T) {
2252 Step S;
2253 S.Kind = SK_StringInit;
2254 S.Type = T;
2255 Steps.push_back(S);
2256}
2257
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002258void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2259 Step S;
2260 S.Kind = SK_ObjCObjectConversion;
2261 S.Type = T;
2262 Steps.push_back(S);
2263}
2264
Douglas Gregore2f943b2011-02-22 18:29:51 +00002265void InitializationSequence::AddArrayInitStep(QualType T) {
2266 Step S;
2267 S.Kind = SK_ArrayInit;
2268 S.Type = T;
2269 Steps.push_back(S);
2270}
2271
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002272void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002273 OverloadingResult Result) {
2274 SequenceKind = FailedSequence;
2275 this->Failure = Failure;
2276 this->FailedOverloadResult = Result;
2277}
2278
2279//===----------------------------------------------------------------------===//
2280// Attempt initialization
2281//===----------------------------------------------------------------------===//
2282
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002283/// \brief Attempt list initialization (C++0x [dcl.init.list])
2284static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002285 const InitializedEntity &Entity,
2286 const InitializationKind &Kind,
2287 InitListExpr *InitList,
2288 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002289 // FIXME: We only perform rudimentary checking of list
2290 // initializations at this point, then assume that any list
2291 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002292 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002293 // do all of the necessary checking. C++0x initializer lists will
2294 // force us to perform more checking here.
2295 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2296
Douglas Gregor1b303932009-12-22 15:35:07 +00002297 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002298
2299 // C++ [dcl.init]p13:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002300 // If T is a scalar type, then a declaration of the form
Douglas Gregor51e77d52009-12-10 17:56:55 +00002301 //
2302 // T x = { a };
2303 //
2304 // is equivalent to
2305 //
2306 // T x = a;
2307 if (DestType->isScalarType()) {
2308 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2309 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2310 return;
2311 }
2312
2313 // Assume scalar initialization from a single value works.
2314 } else if (DestType->isAggregateType()) {
2315 // Assume aggregate initialization works.
2316 } else if (DestType->isVectorType()) {
2317 // Assume vector initialization works.
2318 } else if (DestType->isReferenceType()) {
2319 // FIXME: C++0x defines behavior for this.
2320 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2321 return;
2322 } else if (DestType->isRecordType()) {
2323 // FIXME: C++0x defines behavior for this
2324 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2325 }
2326
2327 // Add a general "list initialization" step.
2328 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002329}
2330
2331/// \brief Try a reference initialization that involves calling a conversion
2332/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002333static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2334 const InitializedEntity &Entity,
2335 const InitializationKind &Kind,
2336 Expr *Initializer,
2337 bool AllowRValues,
2338 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002339 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002340 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2341 QualType T1 = cv1T1.getUnqualifiedType();
2342 QualType cv2T2 = Initializer->getType();
2343 QualType T2 = cv2T2.getUnqualifiedType();
2344
2345 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002346 bool ObjCConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002348 T1, T2, DerivedToBase,
2349 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002350 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002351 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002352 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002353
2354 // Build the candidate set directly in the initialization sequence
2355 // structure, so that it will persist if we fail.
2356 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2357 CandidateSet.clear();
2358
2359 // Determine whether we are allowed to call explicit constructors or
2360 // explicit conversion operators.
2361 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002362
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002363 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002364 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2365 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002366 // The type we're converting to is a class type. Enumerate its constructors
2367 // to see if there is a suitable conversion.
2368 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002369
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002370 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002371 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002372 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002373 NamedDecl *D = *Con;
2374 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2375
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002376 // Find the constructor (which may be a template).
2377 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002378 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002379 if (ConstructorTmpl)
2380 Constructor = cast<CXXConstructorDecl>(
2381 ConstructorTmpl->getTemplatedDecl());
2382 else
John McCalla0296f72010-03-19 07:35:19 +00002383 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002384
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002385 if (!Constructor->isInvalidDecl() &&
2386 Constructor->isConvertingConstructor(AllowExplicit)) {
2387 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002388 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002389 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002390 &Initializer, 1, CandidateSet,
2391 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002392 else
John McCalla0296f72010-03-19 07:35:19 +00002393 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002394 &Initializer, 1, CandidateSet,
2395 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002397 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002398 }
John McCall3696dcb2010-08-17 07:23:57 +00002399 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2400 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002401
Douglas Gregor496e8b342010-05-07 19:42:26 +00002402 const RecordType *T2RecordType = 0;
2403 if ((T2RecordType = T2->getAs<RecordType>()) &&
2404 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002405 // The type we're converting from is a class type, enumerate its conversion
2406 // functions.
2407 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2408
John McCallad371252010-01-20 00:46:10 +00002409 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002410 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002411 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2412 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002413 NamedDecl *D = *I;
2414 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2415 if (isa<UsingShadowDecl>(D))
2416 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002417
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2419 CXXConversionDecl *Conv;
2420 if (ConvTemplate)
2421 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2422 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002423 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002424
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002425 // If the conversion function doesn't return a reference type,
2426 // it can't be considered for this conversion unless we're allowed to
2427 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002428 // FIXME: Do we need to make sure that we only consider conversion
2429 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002430 // break recursion.
2431 if ((AllowExplicit || !Conv->isExplicit()) &&
2432 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2433 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002434 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002435 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002436 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002437 else
John McCalla0296f72010-03-19 07:35:19 +00002438 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002439 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002440 }
2441 }
2442 }
John McCall3696dcb2010-08-17 07:23:57 +00002443 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2444 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002445
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002446 SourceLocation DeclLoc = Initializer->getLocStart();
2447
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002449 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002450 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002451 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002452 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002453
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002454 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002455
Chandler Carruth30141632011-02-25 19:41:05 +00002456 // This is the overload that will actually be used for the initialization, so
2457 // mark it as used.
2458 S.MarkDeclarationReferenced(DeclLoc, Function);
2459
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002460 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002461 if (isa<CXXConversionDecl>(Function))
2462 T2 = Function->getResultType();
2463 else
2464 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002465
2466 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002467 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002468 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002469
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002471 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002472 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002473 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002474 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002475 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002476 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002477
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002478 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002479 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002480 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002481 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002482 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002483 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002484 if (NewRefRelationship == Sema::Ref_Incompatible) {
2485 // If the type we've converted to is not reference-related to the
2486 // type we're looking for, then there is another conversion step
2487 // we need to perform to produce a temporary of the right type
2488 // that we'll be binding to.
2489 ImplicitConversionSequence ICS;
2490 ICS.setStandard();
2491 ICS.Standard = Best->FinalConversion;
2492 T2 = ICS.Standard.getToType(2);
2493 Sequence.AddConversionSequenceStep(ICS, T2);
2494 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002495 Sequence.AddDerivedToBaseCastStep(
2496 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002498 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002499 else if (NewObjCConversion)
2500 Sequence.AddObjCObjectConversionStep(
2501 S.Context.getQualifiedType(T1,
2502 T2.getNonReferenceType().getQualifiers()));
2503
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002504 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002505 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002507 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2508 return OR_Success;
2509}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002510
2511/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2512static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002513 const InitializedEntity &Entity,
2514 const InitializationKind &Kind,
2515 Expr *Initializer,
2516 InitializationSequence &Sequence) {
2517 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002518
Douglas Gregor1b303932009-12-22 15:35:07 +00002519 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002520 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002521 Qualifiers T1Quals;
2522 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002523 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002524 Qualifiers T2Quals;
2525 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002526 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002527
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002528 // If the initializer is the address of an overloaded function, try
2529 // to resolve the overloaded function. If all goes well, T2 is the
2530 // type of the resulting function.
2531 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002532 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002534 T1,
2535 false,
2536 Found)) {
2537 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2538 cv2T2 = Fn->getType();
2539 T2 = cv2T2.getUnqualifiedType();
2540 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002541 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2542 return;
2543 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002544 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002545
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002546 // Compute some basic properties of the types and the initializer.
2547 bool isLValueRef = DestType->isLValueReferenceType();
2548 bool isRValueRef = !isLValueRef;
2549 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002550 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002551 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002552 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002553 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2554 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002555
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002556 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002558 // "cv2 T2" as follows:
2559 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002560 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002561 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002562 // Note the analogous bullet points for rvlaue refs to functions. Because
2563 // there are no function rvalues in C++, rvalue refs to functions are treated
2564 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002565 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002566 bool T1Function = T1->isFunctionType();
2567 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002568 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002569 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002570 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002571 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002572 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002573 // reference-compatible with "cv2 T2," or
2574 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002575 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002576 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002577 // can occur. However, we do pay attention to whether it is a bit-field
2578 // to decide whether we're actually binding to a temporary created from
2579 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002580 if (DerivedToBase)
2581 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002583 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002584 else if (ObjCConversion)
2585 Sequence.AddObjCObjectConversionStep(
2586 S.Context.getQualifiedType(T1, T2Quals));
2587
Chandler Carruth04bdce62010-01-12 20:32:25 +00002588 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002589 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002590 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002591 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002592 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002593 return;
2594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595
2596 // - has a class type (i.e., T2 is a class type), where T1 is not
2597 // reference-related to T2, and can be implicitly converted to an
2598 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2599 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002600 // applicable conversion functions (13.3.1.6) and choosing the best
2601 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002602 // If we have an rvalue ref to function type here, the rhs must be
2603 // an rvalue.
2604 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2605 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002607 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002608 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002609 Sequence);
2610 if (ConvOvlResult == OR_Success)
2611 return;
John McCall0d1da222010-01-12 00:44:57 +00002612 if (ConvOvlResult != OR_No_Viable_Function) {
2613 Sequence.SetOverloadFailure(
2614 InitializationSequence::FK_ReferenceInitOverloadFailed,
2615 ConvOvlResult);
2616 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002617 }
2618 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002619
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002620 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002621 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002622 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002623 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002624 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2625 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2626 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002627 Sequence.SetOverloadFailure(
2628 InitializationSequence::FK_ReferenceInitOverloadFailed,
2629 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002630 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002631 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002632 ? (RefRelationship == Sema::Ref_Related
2633 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2634 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2635 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002636
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002637 return;
2638 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002639
Douglas Gregor92e460e2011-01-20 16:44:54 +00002640 // - If the initializer expression
2641 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2642 // "cv1 T1" is reference-compatible with "cv2 T2"
2643 // Note: functions are handled below.
2644 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002645 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002646 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002647 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002648 (InitCategory.isXValue() ||
2649 (InitCategory.isPRValue() && T2->isRecordType()) ||
2650 (InitCategory.isPRValue() && T2->isArrayType()))) {
2651 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2652 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002653 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2654 // compiler the freedom to perform a copy here or bind to the
2655 // object, while C++0x requires that we bind directly to the
2656 // object. Hence, we always bind to the object without making an
2657 // extra copy. However, in C++03 requires that we check for the
2658 // presence of a suitable copy constructor:
2659 //
2660 // The constructor that would be used to make the copy shall
2661 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002662 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002663 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665
Douglas Gregor92e460e2011-01-20 16:44:54 +00002666 if (DerivedToBase)
2667 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2668 ValueKind);
2669 else if (ObjCConversion)
2670 Sequence.AddObjCObjectConversionStep(
2671 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002672
Douglas Gregor92e460e2011-01-20 16:44:54 +00002673 if (T1Quals != T2Quals)
2674 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002675 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002676 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002679
2680 // - has a class type (i.e., T2 is a class type), where T1 is not
2681 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002682 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2683 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002684 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002685 if (RefRelationship == Sema::Ref_Incompatible) {
2686 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2687 Kind, Initializer,
2688 /*AllowRValues=*/true,
2689 Sequence);
2690 if (ConvOvlResult)
2691 Sequence.SetOverloadFailure(
2692 InitializationSequence::FK_ReferenceInitOverloadFailed,
2693 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002694
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002695 return;
2696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002697
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002698 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2699 return;
2700 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002701
2702 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002703 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002704 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002705 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002706
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002707 // Determine whether we are allowed to call explicit constructors or
2708 // explicit conversion operators.
2709 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002710
2711 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2712
2713 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2714 /*SuppressUserConversions*/ false,
2715 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002716 /*FIXME:InOverloadResolution=*/false,
2717 /*CStyle=*/Kind.isCStyleOrFunctionalCast())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002718 // FIXME: Use the conversion function set stored in ICS to turn
2719 // this into an overloading ambiguity diagnostic. However, we need
2720 // to keep that set as an OverloadCandidateSet rather than as some
2721 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002722 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2723 Sequence.SetOverloadFailure(
2724 InitializationSequence::FK_ReferenceInitOverloadFailed,
2725 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002726 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2727 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002728 else
2729 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002730 return;
2731 }
2732
2733 // [...] If T1 is reference-related to T2, cv1 must be the
2734 // same cv-qualification as, or greater cv-qualification
2735 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002736 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2737 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002738 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002739 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002740 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2741 return;
2742 }
2743
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002744 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002745 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002747 InitCategory.isLValue()) {
2748 Sequence.SetFailed(
2749 InitializationSequence::FK_RValueReferenceBindingToLValue);
2750 return;
2751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002752
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002753 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2754 return;
2755}
2756
2757/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002758/// (C++ [dcl.init.string], C99 6.7.8).
2759static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002760 const InitializedEntity &Entity,
2761 const InitializationKind &Kind,
2762 Expr *Initializer,
2763 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002764 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002765 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002766}
2767
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002768/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2769/// enumerates the constructors of the initialized entity and performs overload
2770/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002771static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002772 const InitializedEntity &Entity,
2773 const InitializationKind &Kind,
2774 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002775 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002776 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002777 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002778
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002779 // Build the candidate set directly in the initialization sequence
2780 // structure, so that it will persist if we fail.
2781 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2782 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002783
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002784 // Determine whether we are allowed to call explicit constructors or
2785 // explicit conversion operators.
2786 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2787 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002788 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002789
2790 // The type we're constructing needs to be complete.
2791 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002792 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002793 return;
2794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002796 // The type we're converting to is a class type. Enumerate its constructors
2797 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002798 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002799 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002800 CXXRecordDecl *DestRecordDecl
2801 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002802
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002803 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002804 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002805 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002806 NamedDecl *D = *Con;
2807 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002808 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002810 // Find the constructor (which may be a template).
2811 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002812 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002813 if (ConstructorTmpl)
2814 Constructor = cast<CXXConstructorDecl>(
2815 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002816 else {
John McCalla0296f72010-03-19 07:35:19 +00002817 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002818
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002819 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00002820 // suppress user-defined conversions on the arguments.
2821 // FIXME: Move constructors?
2822 if (Kind.getKind() == InitializationKind::IK_Copy &&
2823 Constructor->isCopyConstructor())
2824 SuppressUserConversions = true;
2825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002827 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002828 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002829 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002830 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002831 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002832 Args, NumArgs, CandidateSet,
2833 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002834 else
John McCalla0296f72010-03-19 07:35:19 +00002835 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002836 Args, NumArgs, CandidateSet,
2837 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002839 }
2840
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002841 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002842
2843 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002844 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002845 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002846 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002847 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002849 Result);
2850 return;
2851 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002852
2853 // C++0x [dcl.init]p6:
2854 // If a program calls for the default initialization of an object
2855 // of a const-qualified type T, T shall be a class type with a
2856 // user-provided default constructor.
2857 if (Kind.getKind() == InitializationKind::IK_Default &&
2858 Entity.getType().isConstQualified() &&
2859 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2860 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2861 return;
2862 }
2863
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002864 // Add the constructor initialization step. Any cv-qualification conversion is
2865 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002866 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002868 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002869 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002870}
2871
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002872/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002874 const InitializedEntity &Entity,
2875 const InitializationKind &Kind,
2876 InitializationSequence &Sequence) {
2877 // C++ [dcl.init]p5:
2878 //
2879 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002880 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002881
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002882 // -- if T is an array type, then each element is value-initialized;
2883 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2884 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002886 if (const RecordType *RT = T->getAs<RecordType>()) {
2887 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2888 // -- if T is a class type (clause 9) with a user-declared
2889 // constructor (12.1), then the default constructor for T is
2890 // called (and the initialization is ill-formed if T has no
2891 // accessible default constructor);
2892 //
2893 // FIXME: we really want to refer to a single subobject of the array,
2894 // but Entity doesn't have a way to capture that (yet).
2895 if (ClassDecl->hasUserDeclaredConstructor())
2896 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002897
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002898 // -- if T is a (possibly cv-qualified) non-union class type
2899 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002900 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002901 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002902 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002903 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002904 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002905 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002906 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002907 }
2908 }
2909
Douglas Gregor1b303932009-12-22 15:35:07 +00002910 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002911 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2912}
2913
Douglas Gregor85dabae2009-12-16 01:38:02 +00002914/// \brief Attempt default initialization (C++ [dcl.init]p6).
2915static void TryDefaultInitialization(Sema &S,
2916 const InitializedEntity &Entity,
2917 const InitializationKind &Kind,
2918 InitializationSequence &Sequence) {
2919 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002920
Douglas Gregor85dabae2009-12-16 01:38:02 +00002921 // C++ [dcl.init]p6:
2922 // To default-initialize an object of type T means:
2923 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002924 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002925 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2926 DestType = Array->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927
Douglas Gregor85dabae2009-12-16 01:38:02 +00002928 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2929 // constructor for T is called (and the initialization is ill-formed if
2930 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002931 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002932 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2933 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935
Douglas Gregor85dabae2009-12-16 01:38:02 +00002936 // - otherwise, no initialization is performed.
2937 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938
Douglas Gregor85dabae2009-12-16 01:38:02 +00002939 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00002941 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002942 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002943 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2944}
2945
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002946/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2947/// which enumerates all conversion functions and performs overload resolution
2948/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002949static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002950 const InitializedEntity &Entity,
2951 const InitializationKind &Kind,
2952 Expr *Initializer,
2953 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002954 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002955
Douglas Gregor1b303932009-12-22 15:35:07 +00002956 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002957 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2958 QualType SourceType = Initializer->getType();
2959 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2960 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002961
Douglas Gregor540c3b02009-12-14 17:27:33 +00002962 // Build the candidate set directly in the initialization sequence
2963 // structure, so that it will persist if we fail.
2964 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2965 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002966
Douglas Gregor540c3b02009-12-14 17:27:33 +00002967 // Determine whether we are allowed to call explicit constructors or
2968 // explicit conversion operators.
2969 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002970
Douglas Gregor540c3b02009-12-14 17:27:33 +00002971 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2972 // The type we're converting to is a class type. Enumerate its constructors
2973 // to see if there is a suitable conversion.
2974 CXXRecordDecl *DestRecordDecl
2975 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002976
Douglas Gregord9848152010-04-26 14:36:57 +00002977 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002979 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002980 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002981 Con != ConEnd; ++Con) {
2982 NamedDecl *D = *Con;
2983 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984
Douglas Gregord9848152010-04-26 14:36:57 +00002985 // Find the constructor (which may be a template).
2986 CXXConstructorDecl *Constructor = 0;
2987 FunctionTemplateDecl *ConstructorTmpl
2988 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002989 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002990 Constructor = cast<CXXConstructorDecl>(
2991 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002992 else
Douglas Gregord9848152010-04-26 14:36:57 +00002993 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994
Douglas Gregord9848152010-04-26 14:36:57 +00002995 if (!Constructor->isInvalidDecl() &&
2996 Constructor->isConvertingConstructor(AllowExplicit)) {
2997 if (ConstructorTmpl)
2998 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2999 /*ExplicitArgs*/ 0,
3000 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003001 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003002 else
3003 S.AddOverloadCandidate(Constructor, FoundDecl,
3004 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003005 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003006 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003007 }
Douglas Gregord9848152010-04-26 14:36:57 +00003008 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003009 }
Eli Friedman78275202009-12-19 08:11:05 +00003010
3011 SourceLocation DeclLoc = Initializer->getLocStart();
3012
Douglas Gregor540c3b02009-12-14 17:27:33 +00003013 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3014 // The type we're converting from is a class type, enumerate its conversion
3015 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003016
Eli Friedman4afe9a32009-12-20 22:12:03 +00003017 // We can only enumerate the conversion functions for a complete type; if
3018 // the type isn't complete, simply skip this step.
3019 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3020 CXXRecordDecl *SourceRecordDecl
3021 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003022
John McCallad371252010-01-20 00:46:10 +00003023 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003024 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003025 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003026 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003027 I != E; ++I) {
3028 NamedDecl *D = *I;
3029 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3030 if (isa<UsingShadowDecl>(D))
3031 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003032
Eli Friedman4afe9a32009-12-20 22:12:03 +00003033 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3034 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003035 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003036 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003037 else
John McCallda4458e2010-03-31 01:36:47 +00003038 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003039
Eli Friedman4afe9a32009-12-20 22:12:03 +00003040 if (AllowExplicit || !Conv->isExplicit()) {
3041 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003042 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003043 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003044 CandidateSet);
3045 else
John McCalla0296f72010-03-19 07:35:19 +00003046 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003047 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003048 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003049 }
3050 }
3051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052
3053 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003054 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003055 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003056 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003057 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003059 Result);
3060 return;
3061 }
John McCall0d1da222010-01-12 00:44:57 +00003062
Douglas Gregor540c3b02009-12-14 17:27:33 +00003063 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003064 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003065
Douglas Gregor540c3b02009-12-14 17:27:33 +00003066 if (isa<CXXConstructorDecl>(Function)) {
3067 // Add the user-defined conversion step. Any cv-qualification conversion is
3068 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003069 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003070 return;
3071 }
3072
3073 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003074 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003075 if (ConvType->getAs<RecordType>()) {
3076 // If we're converting to a class type, there may be an copy if
3077 // the resulting temporary object (possible to create an object of
3078 // a base class type). That copy is not a separate conversion, so
3079 // we just make a note of the actual destination type (possibly a
3080 // base class of the type returned by the conversion function) and
3081 // let the user-defined conversion step handle the conversion.
3082 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3083 return;
3084 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003085
Douglas Gregor5ab11652010-04-17 22:01:05 +00003086 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087
Douglas Gregor5ab11652010-04-17 22:01:05 +00003088 // If the conversion following the call to the conversion function
3089 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003090 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3091 Best->FinalConversion.Third) {
3092 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003093 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003094 ICS.Standard = Best->FinalConversion;
3095 Sequence.AddConversionSequenceStep(ICS, DestType);
3096 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003097}
3098
Douglas Gregore2f943b2011-02-22 18:29:51 +00003099/// \brief Determine whether we have compatible array types for the
3100/// purposes of GNU by-copy array initialization.
3101static bool hasCompatibleArrayTypes(ASTContext &Context,
3102 const ArrayType *Dest,
3103 const ArrayType *Source) {
3104 // If the source and destination array types are equivalent, we're
3105 // done.
3106 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3107 return true;
3108
3109 // Make sure that the element types are the same.
3110 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3111 return false;
3112
3113 // The only mismatch we allow is when the destination is an
3114 // incomplete array type and the source is a constant array type.
3115 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3116}
3117
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003118InitializationSequence::InitializationSequence(Sema &S,
3119 const InitializedEntity &Entity,
3120 const InitializationKind &Kind,
3121 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003122 unsigned NumArgs)
3123 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003124 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003125
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003126 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003127 // The semantics of initializers are as follows. The destination type is
3128 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003129 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003130 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003131 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003132 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003133
3134 if (DestType->isDependentType() ||
3135 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3136 SequenceKind = DependentSequence;
3137 return;
3138 }
3139
John McCalled75c092010-12-07 22:54:16 +00003140 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003141 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3142 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3143 if (Result.isInvalid()) {
3144 SetFailed(FK_ConversionFromPropertyFailed);
3145 return;
3146 }
3147 Args[I] = Result.take();
3148 }
John McCalled75c092010-12-07 22:54:16 +00003149
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003150 QualType SourceType;
3151 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003152 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003153 Initializer = Args[0];
3154 if (!isa<InitListExpr>(Initializer))
3155 SourceType = Initializer->getType();
3156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157
3158 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003159 // list-initialized (8.5.4).
3160 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3161 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003162 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003164
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003165 // - If the destination type is a reference type, see 8.5.3.
3166 if (DestType->isReferenceType()) {
3167 // C++0x [dcl.init.ref]p1:
3168 // A variable declared to be a T& or T&&, that is, "reference to type T"
3169 // (8.3.2), shall be initialized by an object, or function, of type T or
3170 // by an object that can be converted into a T.
3171 // (Therefore, multiple arguments are not permitted.)
3172 if (NumArgs != 1)
3173 SetFailed(FK_TooManyInitsForReference);
3174 else
3175 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3176 return;
3177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003179 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003180 if (Kind.getKind() == InitializationKind::IK_Value ||
3181 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003182 TryValueInitialization(S, Entity, Kind, *this);
3183 return;
3184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185
Douglas Gregor85dabae2009-12-16 01:38:02 +00003186 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003187 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003188 TryDefaultInitialization(S, Entity, Kind, *this);
3189 return;
3190 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003191
John McCall66884dd2011-02-21 07:22:22 +00003192 // - If the destination type is an array of characters, an array of
3193 // char16_t, an array of char32_t, or an array of wchar_t, and the
3194 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003196 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003197 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3198 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCall66884dd2011-02-21 07:22:22 +00003199 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3200 return;
3201 }
3202
Douglas Gregore2f943b2011-02-22 18:29:51 +00003203 // Note: as an GNU C extension, we allow initialization of an
3204 // array from a compound literal that creates an array of the same
3205 // type, so long as the initializer has no side effects.
3206 if (!S.getLangOptions().CPlusPlus && Initializer &&
3207 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3208 Initializer->getType()->isArrayType()) {
3209 const ArrayType *SourceAT
3210 = Context.getAsArrayType(Initializer->getType());
3211 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3212 SetFailed(FK_ArrayTypeMismatch);
3213 else if (Initializer->HasSideEffects(S.Context))
3214 SetFailed(FK_NonConstantArrayInit);
3215 else {
3216 setSequenceKind(ArrayInit);
3217 AddArrayInitStep(DestType);
3218 }
3219 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003220 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3221 else
3222 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003223
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003224 return;
3225 }
Eli Friedman78275202009-12-19 08:11:05 +00003226
3227 // Handle initialization in C
3228 if (!S.getLangOptions().CPlusPlus) {
3229 setSequenceKind(CAssignment);
3230 AddCAssignmentStep(DestType);
3231 return;
3232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003234 // - If the destination type is a (possibly cv-qualified) class type:
3235 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236 // - If the initialization is direct-initialization, or if it is
3237 // copy-initialization where the cv-unqualified version of the
3238 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003239 // class of the destination, constructors are considered. [...]
3240 if (Kind.getKind() == InitializationKind::IK_Direct ||
3241 (Kind.getKind() == InitializationKind::IK_Copy &&
3242 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3243 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003245 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003247 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003249 // used) to a derived class thereof are enumerated as described in
3250 // 13.3.1.4, and the best one is chosen through overload resolution
3251 // (13.3).
3252 else
3253 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3254 return;
3255 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256
Douglas Gregor85dabae2009-12-16 01:38:02 +00003257 if (NumArgs > 1) {
3258 SetFailed(FK_TooManyInitsForScalar);
3259 return;
3260 }
3261 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262
3263 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003264 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003265 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003266 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3267 return;
3268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003270 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003271 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003272 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003274 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003275 if (S.TryImplicitConversion(*this, Entity, Initializer,
3276 /*SuppressUserConversions*/ true,
3277 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003278 /*InOverloadResolution*/ false,
3279 /*CStyle=*/Kind.isCStyleOrFunctionalCast()))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003280 {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003281 DeclAccessPair dap;
3282 if (Initializer->getType() == Context.OverloadTy &&
3283 !S.ResolveAddressOfOverloadedFunction(Initializer
3284 , DestType, false, dap))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003285 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3286 else
3287 SetFailed(InitializationSequence::FK_ConversionFailed);
3288 }
John McCallec6f4e92010-06-04 02:29:22 +00003289 else
3290 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003291}
3292
3293InitializationSequence::~InitializationSequence() {
3294 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3295 StepEnd = Steps.end();
3296 Step != StepEnd; ++Step)
3297 Step->Destroy();
3298}
3299
3300//===----------------------------------------------------------------------===//
3301// Perform initialization
3302//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003304getAssignmentAction(const InitializedEntity &Entity) {
3305 switch(Entity.getKind()) {
3306 case InitializedEntity::EK_Variable:
3307 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003308 case InitializedEntity::EK_Exception:
3309 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003310 case InitializedEntity::EK_Delegation:
Douglas Gregore1314a62009-12-18 05:02:21 +00003311 return Sema::AA_Initializing;
3312
3313 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003315 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3316 return Sema::AA_Sending;
3317
Douglas Gregore1314a62009-12-18 05:02:21 +00003318 return Sema::AA_Passing;
3319
3320 case InitializedEntity::EK_Result:
3321 return Sema::AA_Returning;
3322
Douglas Gregore1314a62009-12-18 05:02:21 +00003323 case InitializedEntity::EK_Temporary:
3324 // FIXME: Can we tell apart casting vs. converting?
3325 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003326
Douglas Gregore1314a62009-12-18 05:02:21 +00003327 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003328 case InitializedEntity::EK_ArrayElement:
3329 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003330 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003331 return Sema::AA_Initializing;
3332 }
3333
3334 return Sema::AA_Converting;
3335}
3336
Douglas Gregor95562572010-04-24 23:45:46 +00003337/// \brief Whether we should binding a created object as a temporary when
3338/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003339static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003340 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003341 case InitializedEntity::EK_ArrayElement:
3342 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003343 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003344 case InitializedEntity::EK_New:
3345 case InitializedEntity::EK_Variable:
3346 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003347 case InitializedEntity::EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003348 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003349 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003350 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003351 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352
Douglas Gregore1314a62009-12-18 05:02:21 +00003353 case InitializedEntity::EK_Parameter:
3354 case InitializedEntity::EK_Temporary:
3355 return true;
3356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357
Douglas Gregore1314a62009-12-18 05:02:21 +00003358 llvm_unreachable("missed an InitializedEntity kind?");
3359}
3360
Douglas Gregor95562572010-04-24 23:45:46 +00003361/// \brief Whether the given entity, when initialized with an object
3362/// created for that initialization, requires destruction.
3363static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3364 switch (Entity.getKind()) {
3365 case InitializedEntity::EK_Member:
3366 case InitializedEntity::EK_Result:
3367 case InitializedEntity::EK_New:
3368 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003369 case InitializedEntity::EK_Delegation:
Douglas Gregor95562572010-04-24 23:45:46 +00003370 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003371 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003372 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373
Douglas Gregor95562572010-04-24 23:45:46 +00003374 case InitializedEntity::EK_Variable:
3375 case InitializedEntity::EK_Parameter:
3376 case InitializedEntity::EK_Temporary:
3377 case InitializedEntity::EK_ArrayElement:
3378 case InitializedEntity::EK_Exception:
3379 return true;
3380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381
3382 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003383}
3384
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003385/// \brief Make a (potentially elidable) temporary copy of the object
3386/// provided by the given initializer by calling the appropriate copy
3387/// constructor.
3388///
3389/// \param S The Sema object used for type-checking.
3390///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003391/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003392/// the type of the initializer expression or a superclass thereof.
3393///
3394/// \param Enter The entity being initialized.
3395///
3396/// \param CurInit The initializer expression.
3397///
3398/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3399/// is permitted in C++03 (but not C++0x) when binding a reference to
3400/// an rvalue.
3401///
3402/// \returns An expression that copies the initializer expression into
3403/// a temporary object, or an error expression if a copy could not be
3404/// created.
John McCalldadc5752010-08-24 06:29:42 +00003405static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003406 QualType T,
3407 const InitializedEntity &Entity,
3408 ExprResult CurInit,
3409 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003410 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003411 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003413 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003414 Class = cast<CXXRecordDecl>(Record->getDecl());
3415 if (!Class)
3416 return move(CurInit);
3417
Douglas Gregor5d369002011-01-21 18:05:27 +00003418 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003419 // When certain criteria are met, an implementation is allowed to
3420 // omit the copy/move construction of a class object, even if the
3421 // copy/move constructor and/or destructor for the object have
3422 // side effects. [...]
3423 // - when a temporary class object that has not been bound to a
3424 // reference (12.2) would be copied/moved to a class object
3425 // with the same cv-unqualified type, the copy/move operation
3426 // can be omitted by constructing the temporary object
3427 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003429 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003430 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003432 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003433 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003434 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003435 switch (Entity.getKind()) {
3436 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003437 Loc = Entity.getReturnLoc();
3438 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Douglas Gregore1314a62009-12-18 05:02:21 +00003440 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003441 Loc = Entity.getThrowLoc();
3442 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003443
Douglas Gregore1314a62009-12-18 05:02:21 +00003444 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003445 Loc = Entity.getDecl()->getLocation();
3446 break;
3447
Anders Carlsson0bd52402010-01-24 00:19:41 +00003448 case InitializedEntity::EK_ArrayElement:
3449 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003450 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003451 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003452 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003453 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003454 case InitializedEntity::EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003455 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003456 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003457 Loc = CurInitExpr->getLocStart();
3458 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003459 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003460
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003462 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3463 return move(CurInit);
3464
Douglas Gregorf282a762011-01-21 19:38:21 +00003465 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003466 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003467 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003468 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003469 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003470 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003471 // C++0x [dcl.init]p16, second bullet to class types, this
3472 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003473 CXXConstructorDecl *Constructor = 0;
3474
3475 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003476 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003477 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003478 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003479 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003480 continue;
3481
3482 DeclAccessPair FoundDecl
3483 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3484 S.AddOverloadCandidate(Constructor, FoundDecl,
3485 &CurInitExpr, 1, CandidateSet);
3486 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003487 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003488
3489 // Handle constructor templates.
3490 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3491 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003492 continue;
John McCalla0296f72010-03-19 07:35:19 +00003493
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003494 Constructor = cast<CXXConstructorDecl>(
3495 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003496 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003497 continue;
3498
3499 // FIXME: Do we need to limit this to copy-constructor-like
3500 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003501 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003502 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3503 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3504 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregore1314a62009-12-18 05:02:21 +00003507 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003508 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003509 case OR_Success:
3510 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511
Douglas Gregore1314a62009-12-18 05:02:21 +00003512 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003513 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3514 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3515 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003516 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003517 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003518 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003519 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003520 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003521 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522
Douglas Gregore1314a62009-12-18 05:02:21 +00003523 case OR_Ambiguous:
3524 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003525 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003526 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003527 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003528 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529
Douglas Gregore1314a62009-12-18 05:02:21 +00003530 case OR_Deleted:
3531 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003532 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003533 << CurInitExpr->getSourceRange();
3534 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3535 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003536 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003537 }
3538
Douglas Gregor5ab11652010-04-17 22:01:05 +00003539 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003540 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003541 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003542
Anders Carlssona01874b2010-04-21 18:47:17 +00003543 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003544 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003545
3546 if (IsExtraneousCopy) {
3547 // If this is a totally extraneous copy for C++03 reference
3548 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003549 // expression. We don't generate an (elided) copy operation here
3550 // because doing so would require us to pass down a flag to avoid
3551 // infinite recursion, where each step adds another extraneous,
3552 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003553
Douglas Gregor30b52772010-04-18 07:57:34 +00003554 // Instantiate the default arguments of any extra parameters in
3555 // the selected copy constructor, as if we were going to create a
3556 // proper call to the copy constructor.
3557 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3558 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3559 if (S.RequireCompleteType(Loc, Parm->getType(),
3560 S.PDiag(diag::err_call_incomplete_argument)))
3561 break;
3562
3563 // Build the default argument expression; we don't actually care
3564 // if this succeeds or not, because this routine will complain
3565 // if there was a problem.
3566 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3567 }
3568
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003569 return S.Owned(CurInitExpr);
3570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Chandler Carruth30141632011-02-25 19:41:05 +00003572 S.MarkDeclarationReferenced(Loc, Constructor);
3573
Douglas Gregor5ab11652010-04-17 22:01:05 +00003574 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003575 // constructor call (we might have derived-to-base conversions, or
3576 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003577 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003578 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003579 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003580
Douglas Gregord0ace022010-04-25 00:55:24 +00003581 // Actually perform the constructor call.
3582 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003583 move_arg(ConstructorArgs),
3584 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003585 CXXConstructExpr::CK_Complete,
3586 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003587
Douglas Gregord0ace022010-04-25 00:55:24 +00003588 // If we're supposed to bind temporaries, do so.
3589 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3590 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3591 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003592}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003593
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003594void InitializationSequence::PrintInitLocationNote(Sema &S,
3595 const InitializedEntity &Entity) {
3596 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3597 if (Entity.getDecl()->getLocation().isInvalid())
3598 return;
3599
3600 if (Entity.getDecl()->getDeclName())
3601 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3602 << Entity.getDecl()->getDeclName();
3603 else
3604 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3605 }
3606}
3607
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003609InitializationSequence::Perform(Sema &S,
3610 const InitializedEntity &Entity,
3611 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003612 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003613 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003614 if (SequenceKind == FailedSequence) {
3615 unsigned NumArgs = Args.size();
3616 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003617 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003620 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003621 // If the declaration is a non-dependent, incomplete array type
3622 // that has an initializer, then its type will be completed once
3623 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003624 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003625 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003626 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003627 if (const IncompleteArrayType *ArrayT
3628 = S.Context.getAsIncompleteArrayType(DeclType)) {
3629 // FIXME: We don't currently have the ability to accurately
3630 // compute the length of an initializer list without
3631 // performing full type-checking of the initializer list
3632 // (since we have to determine where braces are implicitly
3633 // introduced and such). So, we fall back to making the array
3634 // type a dependently-sized array type with no specified
3635 // bound.
3636 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3637 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003638
Douglas Gregor51e77d52009-12-10 17:56:55 +00003639 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003640 if (DeclaratorDecl *DD = Entity.getDecl()) {
3641 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3642 TypeLoc TL = TInfo->getTypeLoc();
3643 if (IncompleteArrayTypeLoc *ArrayLoc
3644 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3645 Brackets = ArrayLoc->getBracketsRange();
3646 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003647 }
3648
3649 *ResultType
3650 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3651 /*NumElts=*/0,
3652 ArrayT->getSizeModifier(),
3653 ArrayT->getIndexTypeCVRQualifiers(),
3654 Brackets);
3655 }
3656
3657 }
3658 }
3659
Eli Friedmana553d4a2009-12-22 02:35:53 +00003660 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003661 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003662
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003663 if (Args.size() == 0)
3664 return S.Owned((Expr *)0);
3665
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003666 unsigned NumArgs = Args.size();
3667 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3668 SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669 (Expr **)Args.release(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003670 NumArgs,
3671 SourceLocation()));
3672 }
3673
Douglas Gregor85dabae2009-12-16 01:38:02 +00003674 if (SequenceKind == NoInitialization)
3675 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
Douglas Gregor1b303932009-12-22 15:35:07 +00003677 QualType DestType = Entity.getType().getNonReferenceType();
3678 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003679 // the same as Entity.getDecl()->getType() in cases involving type merging,
3680 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003681 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003682 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003683 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003684
John McCalldadc5752010-08-24 06:29:42 +00003685 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686
Douglas Gregor85dabae2009-12-16 01:38:02 +00003687 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688
3689 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00003690 // grab the only argument out the Args and place it into the "current"
3691 // initializer.
3692 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003693 case SK_ResolveAddressOfOverloadedFunction:
3694 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003695 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003696 case SK_CastDerivedToBaseLValue:
3697 case SK_BindReference:
3698 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003699 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003700 case SK_UserConversion:
3701 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003702 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003703 case SK_QualificationConversionRValue:
3704 case SK_ConversionSequence:
3705 case SK_ListInitialization:
3706 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003707 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003708 case SK_ObjCObjectConversion:
3709 case SK_ArrayInit: {
Douglas Gregore1314a62009-12-18 05:02:21 +00003710 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00003711 CurInit = Args.get()[0];
3712 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003713
3714 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00003715 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3716 CurInit = S.ConvertPropertyForRValue(CurInit.take());
3717 if (CurInit.isInvalid())
3718 return ExprError();
3719 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003720 break;
John McCall34376a62010-12-04 03:47:34 +00003721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722
Douglas Gregore1314a62009-12-18 05:02:21 +00003723 case SK_ConstructorInitialization:
3724 case SK_ZeroInitialization:
3725 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727
3728 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003729 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003730 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003731 for (step_iterator Step = step_begin(), StepEnd = step_end();
3732 Step != StepEnd; ++Step) {
3733 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003734 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735
John Wiegley01296292011-04-08 18:41:53 +00003736 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003738 switch (Step->Kind) {
3739 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003740 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003741 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00003742 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003743 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003744 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003745 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003746 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003747 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003749 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003750 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003751 case SK_CastDerivedToBaseLValue: {
3752 // We have a derived-to-base cast that produces either an rvalue or an
3753 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754
John McCallcf142162010-08-07 06:22:56 +00003755 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003756
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003757 // Casts to inaccessible base classes are allowed with C-style casts.
3758 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3759 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00003760 CurInit.get()->getLocStart(),
3761 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003762 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003763 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
Douglas Gregor88d292c2010-05-13 16:44:06 +00003765 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3766 QualType T = SourceType;
3767 if (const PointerType *Pointer = T->getAs<PointerType>())
3768 T = Pointer->getPointeeType();
3769 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00003770 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003771 cast<CXXRecordDecl>(RecordTy->getDecl()));
3772 }
3773
John McCall2536c6d2010-08-25 10:28:54 +00003774 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003775 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003776 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003777 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003778 VK_XValue :
3779 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003780 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3781 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003782 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003783 CurInit.get(),
3784 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003785 break;
3786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003788 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00003789 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003790 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3791 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003792 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003793 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00003794 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003795 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003796 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003797 }
Anders Carlssona91be642010-01-29 02:47:33 +00003798
John Wiegley01296292011-04-08 18:41:53 +00003799 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003800 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003801 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3802 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00003803 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003804 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003805 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003807
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003808 // Reference binding does not have any corresponding ASTs.
3809
3810 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00003811 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003812 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003813
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003814 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003815
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003816 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003817 // Reference binding does not have any corresponding ASTs.
3818
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003819 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00003820 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003821 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003822
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003823 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003825 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003826 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003827 /*IsExtraneousCopy=*/true);
3828 break;
3829
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003830 case SK_UserConversion: {
3831 // We have a user-defined conversion that invokes either a constructor
3832 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00003833 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00003834 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003835 FunctionDecl *Fn = Step->Function.Function;
3836 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003837 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003838 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003839 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003840 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003841 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00003842 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003843 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003844
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003845 // Determine the arguments required to actually perform the constructor
3846 // call.
John Wiegley01296292011-04-08 18:41:53 +00003847 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003848 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00003849 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003850 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003851 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003852
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003853 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003855 move_arg(ConstructorArgs),
3856 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003857 CXXConstructExpr::CK_Complete,
3858 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003859 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003860 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003861
Anders Carlssona01874b2010-04-21 18:47:17 +00003862 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003863 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003864 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003865
John McCalle3027922010-08-25 11:45:40 +00003866 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003867 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3868 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3869 S.IsDerivedFrom(SourceType, Class))
3870 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871
Douglas Gregor95562572010-04-24 23:45:46 +00003872 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003873 } else {
3874 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003875 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003876 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00003877 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00003878 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003879 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880
3881 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003882 // derived-to-base conversion? I believe the answer is "no", because
3883 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00003884 ExprResult CurInitExprRes =
3885 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
3886 FoundFn, Conversion);
3887 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003888 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00003889 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003891 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00003892 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003893 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003894 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895
John McCalle3027922010-08-25 11:45:40 +00003896 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897
Douglas Gregor95562572010-04-24 23:45:46 +00003898 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900
3901 bool RequiresCopy = !IsCopy &&
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003902 getKind() != InitializationSequence::ReferenceBinding;
3903 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003904 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003905 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00003906 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00003907 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003908 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00003909 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00003910 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00003911 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00003912 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
3913 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00003914 }
3915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003917 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003918 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00003919 CurInit.get()->getType(),
3920 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00003921 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003923 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003924 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3925 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003926
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003927 break;
3928 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003929
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003930 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003931 case SK_QualificationConversionXValue:
3932 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003933 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003934 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003935 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003936 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003937 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003938 VK_XValue :
3939 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00003940 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003941 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003942 }
3943
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003944 case SK_ConversionSequence: {
John Wiegley01296292011-04-08 18:41:53 +00003945 ExprResult CurInitExprRes =
3946 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
3947 getAssignmentAction(Entity),
3948 Kind.isCStyleOrFunctionalCast());
3949 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003950 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00003951 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003952 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003953 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954
Douglas Gregor51e77d52009-12-10 17:56:55 +00003955 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00003956 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003957 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003958 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003959 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003960
3961 CurInit.release();
3962 CurInit = S.Owned(InitList);
3963 break;
3964 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003965
3966 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003967 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003968 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003969 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003970
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003971 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003972 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003973 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3974 ? Kind.getEqualLoc()
3975 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003976
3977 if (Kind.getKind() == InitializationKind::IK_Default) {
3978 // Force even a trivial, implicit default constructor to be
3979 // semantically checked. We do this explicitly because we don't build
3980 // the definition for completely trivial constructors.
3981 CXXRecordDecl *ClassDecl = Constructor->getParent();
3982 assert(ClassDecl && "No parent class for constructor.");
3983 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3984 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3985 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3986 }
3987
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003988 // Determine the arguments required to actually perform the constructor
3989 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003990 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003991 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003992 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003993
3994
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003995 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003996 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003997 (Kind.getKind() == InitializationKind::IK_Direct ||
3998 Kind.getKind() == InitializationKind::IK_Value)) {
3999 // An explicitly-constructed temporary, e.g., X(1, 2).
4000 unsigned NumExprs = ConstructorArgs.size();
4001 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004002 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004003 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004004
Douglas Gregor2b88c112010-09-08 00:15:04 +00004005 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4006 if (!TSInfo)
4007 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004009 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4010 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004011 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004012 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004013 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004014 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004015 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004016 } else {
4017 CXXConstructExpr::ConstructionKind ConstructKind =
4018 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004020 if (Entity.getKind() == InitializedEntity::EK_Base) {
4021 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004023 CXXConstructExpr::CK_NonVirtualBase;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024 }
4025
Chandler Carruth01718152010-10-25 08:47:36 +00004026 // Only get the parenthesis range if it is a direct construction.
4027 SourceRange parenRange =
4028 Kind.getKind() == InitializationKind::IK_Direct ?
4029 Kind.getParenRange() : SourceRange();
4030
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004031 // If the entity allows NRVO, mark the construction as elidable
4032 // unconditionally.
4033 if (Entity.allowsNRVO())
4034 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4035 Constructor, /*Elidable=*/true,
4036 move_arg(ConstructorArgs),
4037 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004038 ConstructKind,
4039 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004040 else
4041 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004043 move_arg(ConstructorArgs),
4044 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004045 ConstructKind,
4046 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004047 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004048 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004049 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004050
4051 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004052 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004053 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004054 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004056 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004057 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004059 break;
4060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004061
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004062 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004063 step_iterator NextStep = Step;
4064 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004066 NextStep->Kind == SK_ConstructorInitialization) {
4067 // The need for zero-initialization is recorded directly into
4068 // the call to the object's constructor within the next step.
4069 ConstructorInitRequiresZeroInit = true;
4070 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4071 S.getLangOptions().CPlusPlus &&
4072 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004073 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4074 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004076 Kind.getRange().getBegin());
4077
4078 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4079 TSInfo->getType().getNonLValueExprType(S.Context),
4080 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004081 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004082 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004083 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004084 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004085 break;
4086 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004087
4088 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004089 QualType SourceType = CurInit.get()->getType();
4090 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004091 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004092 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4093 if (Result.isInvalid())
4094 return ExprError();
4095 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004096
4097 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004098 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004099 if (ConvTy != Sema::Compatible &&
4100 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004101 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004102 == Sema::Compatible)
4103 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004104 if (CurInitExprRes.isInvalid())
4105 return ExprError();
4106 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004107
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004108 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004109 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4110 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004111 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004112 getAssignmentAction(Entity),
4113 &Complained)) {
4114 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004115 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004116 } else if (Complained)
4117 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004118 break;
4119 }
Eli Friedman78275202009-12-19 08:11:05 +00004120
4121 case SK_StringInit: {
4122 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004123 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004124 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004125 break;
4126 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004127
4128 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004129 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004130 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004131 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004132 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004133
4134 case SK_ArrayInit:
4135 // Okay: we checked everything before creating this step. Note that
4136 // this is a GNU extension.
4137 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004138 << Step->Type << CurInit.get()->getType()
4139 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004140
4141 // If the destination type is an incomplete array type, update the
4142 // type accordingly.
4143 if (ResultType) {
4144 if (const IncompleteArrayType *IncompleteDest
4145 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4146 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004147 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004148 *ResultType = S.Context.getConstantArrayType(
4149 IncompleteDest->getElementType(),
4150 ConstantSource->getSize(),
4151 ArrayType::Normal, 0);
4152 }
4153 }
4154 }
4155
4156 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004157 }
4158 }
John McCall1f425642010-11-11 03:21:53 +00004159
4160 // Diagnose non-fatal problems with the completed initialization.
4161 if (Entity.getKind() == InitializedEntity::EK_Member &&
4162 cast<FieldDecl>(Entity.getDecl())->isBitField())
4163 S.CheckBitFieldInitialization(Kind.getLocation(),
4164 cast<FieldDecl>(Entity.getDecl()),
4165 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004167 return move(CurInit);
4168}
4169
4170//===----------------------------------------------------------------------===//
4171// Diagnose initialization failures
4172//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004174 const InitializedEntity &Entity,
4175 const InitializationKind &Kind,
4176 Expr **Args, unsigned NumArgs) {
4177 if (SequenceKind != FailedSequence)
4178 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004179
Douglas Gregor1b303932009-12-22 15:35:07 +00004180 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004181 switch (Failure) {
4182 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004183 // FIXME: Customize for the initialized entity?
4184 if (NumArgs == 0)
4185 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4186 << DestType.getNonReferenceType();
4187 else // FIXME: diagnostic below could be better!
4188 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4189 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004190 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004191
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004192 case FK_ArrayNeedsInitList:
4193 case FK_ArrayNeedsInitListOrStringLiteral:
4194 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4195 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4196 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197
Douglas Gregore2f943b2011-02-22 18:29:51 +00004198 case FK_ArrayTypeMismatch:
4199 case FK_NonConstantArrayInit:
4200 S.Diag(Kind.getLocation(),
4201 (Failure == FK_ArrayTypeMismatch
4202 ? diag::err_array_init_different_type
4203 : diag::err_array_init_non_constant_array))
4204 << DestType.getNonReferenceType()
4205 << Args[0]->getType()
4206 << Args[0]->getSourceRange();
4207 break;
4208
John McCall16df1e52010-03-30 21:47:33 +00004209 case FK_AddressOfOverloadFailed: {
4210 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004212 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004213 true,
4214 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004215 break;
John McCall16df1e52010-03-30 21:47:33 +00004216 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004218 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004219 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004220 switch (FailedOverloadResult) {
4221 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004222 if (Failure == FK_UserConversionOverloadFailed)
4223 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4224 << Args[0]->getType() << DestType
4225 << Args[0]->getSourceRange();
4226 else
4227 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4228 << DestType << Args[0]->getType()
4229 << Args[0]->getSourceRange();
4230
John McCall5c32be02010-08-24 20:38:10 +00004231 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004232 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004233
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004234 case OR_No_Viable_Function:
4235 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4236 << Args[0]->getType() << DestType.getNonReferenceType()
4237 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004238 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004239 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004241 case OR_Deleted: {
4242 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4243 << Args[0]->getType() << DestType.getNonReferenceType()
4244 << Args[0]->getSourceRange();
4245 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004246 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004247 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4248 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004249 if (Ovl == OR_Deleted) {
4250 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4251 << Best->Function->isDeleted();
4252 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004253 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004254 }
4255 break;
4256 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004258 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004259 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004260 break;
4261 }
4262 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004264 case FK_NonConstLValueReferenceBindingToTemporary:
4265 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004266 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004267 Failure == FK_NonConstLValueReferenceBindingToTemporary
4268 ? diag::err_lvalue_reference_bind_to_temporary
4269 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004270 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004271 << DestType.getNonReferenceType()
4272 << Args[0]->getType()
4273 << Args[0]->getSourceRange();
4274 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004276 case FK_RValueReferenceBindingToLValue:
4277 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004278 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004279 << Args[0]->getSourceRange();
4280 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004282 case FK_ReferenceInitDropsQualifiers:
4283 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4284 << DestType.getNonReferenceType()
4285 << Args[0]->getType()
4286 << Args[0]->getSourceRange();
4287 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004289 case FK_ReferenceInitFailed:
4290 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4291 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004292 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004293 << Args[0]->getType()
4294 << Args[0]->getSourceRange();
4295 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296
Douglas Gregorb491ed32011-02-19 21:32:49 +00004297 case FK_ConversionFailed: {
4298 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004299 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4300 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004301 << DestType
John McCall086a4642010-11-24 05:12:34 +00004302 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004303 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004304 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004305 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004306 }
John Wiegley01296292011-04-08 18:41:53 +00004307
4308 case FK_ConversionFromPropertyFailed:
4309 // No-op. This error has already been reported.
4310 break;
4311
Douglas Gregor51e77d52009-12-10 17:56:55 +00004312 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004313 SourceRange R;
4314
4315 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004316 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004317 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004319 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004320
Douglas Gregor8ec51732010-09-08 21:40:08 +00004321 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4322 if (Kind.isCStyleOrFunctionalCast())
4323 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4324 << R;
4325 else
4326 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4327 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004328 break;
4329 }
4330
4331 case FK_ReferenceBindingToInitList:
4332 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4333 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4334 break;
4335
4336 case FK_InitListBadDestinationType:
4337 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4338 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4339 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004341 case FK_ConstructorOverloadFailed: {
4342 SourceRange ArgsRange;
4343 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004345 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004347 // FIXME: Using "DestType" for the entity we're printing is probably
4348 // bad.
4349 switch (FailedOverloadResult) {
4350 case OR_Ambiguous:
4351 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4352 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004353 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4354 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004355 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004357 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004358 if (Kind.getKind() == InitializationKind::IK_Default &&
4359 (Entity.getKind() == InitializedEntity::EK_Base ||
4360 Entity.getKind() == InitializedEntity::EK_Member) &&
4361 isa<CXXConstructorDecl>(S.CurContext)) {
4362 // This is implicit default initialization of a member or
4363 // base within a constructor. If no viable function was
4364 // found, notify the user that she needs to explicitly
4365 // initialize this base/member.
4366 CXXConstructorDecl *Constructor
4367 = cast<CXXConstructorDecl>(S.CurContext);
4368 if (Entity.getKind() == InitializedEntity::EK_Base) {
4369 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4370 << Constructor->isImplicit()
4371 << S.Context.getTypeDeclType(Constructor->getParent())
4372 << /*base=*/0
4373 << Entity.getType();
4374
4375 RecordDecl *BaseDecl
4376 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4377 ->getDecl();
4378 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4379 << S.Context.getTagDeclType(BaseDecl);
4380 } else {
4381 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4382 << Constructor->isImplicit()
4383 << S.Context.getTypeDeclType(Constructor->getParent())
4384 << /*member=*/1
4385 << Entity.getName();
4386 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4387
4388 if (const RecordType *Record
4389 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004391 diag::note_previous_decl)
4392 << S.Context.getTagDeclType(Record->getDecl());
4393 }
4394 break;
4395 }
4396
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004397 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4398 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004399 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004400 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004402 case OR_Deleted: {
4403 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4404 << true << DestType << ArgsRange;
4405 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004406 OverloadingResult Ovl
4407 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004408 if (Ovl == OR_Deleted) {
4409 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4410 << Best->Function->isDeleted();
4411 } else {
4412 llvm_unreachable("Inconsistent overload resolution?");
4413 }
4414 break;
4415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004417 case OR_Success:
4418 llvm_unreachable("Conversion did not fail!");
4419 break;
4420 }
4421 break;
4422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregor85dabae2009-12-16 01:38:02 +00004424 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004425 if (Entity.getKind() == InitializedEntity::EK_Member &&
4426 isa<CXXConstructorDecl>(S.CurContext)) {
4427 // This is implicit default-initialization of a const member in
4428 // a constructor. Complain that it needs to be explicitly
4429 // initialized.
4430 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4431 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4432 << Constructor->isImplicit()
4433 << S.Context.getTypeDeclType(Constructor->getParent())
4434 << /*const=*/1
4435 << Entity.getName();
4436 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4437 << Entity.getName();
4438 } else {
4439 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4440 << DestType << (bool)DestType->getAs<RecordType>();
4441 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004442 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004444 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004446 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004450 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004451 return true;
4452}
Douglas Gregore1314a62009-12-18 05:02:21 +00004453
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004454void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4455 switch (SequenceKind) {
4456 case FailedSequence: {
4457 OS << "Failed sequence: ";
4458 switch (Failure) {
4459 case FK_TooManyInitsForReference:
4460 OS << "too many initializers for reference";
4461 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004462
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004463 case FK_ArrayNeedsInitList:
4464 OS << "array requires initializer list";
4465 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004466
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004467 case FK_ArrayNeedsInitListOrStringLiteral:
4468 OS << "array requires initializer list or string literal";
4469 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470
Douglas Gregore2f943b2011-02-22 18:29:51 +00004471 case FK_ArrayTypeMismatch:
4472 OS << "array type mismatch";
4473 break;
4474
4475 case FK_NonConstantArrayInit:
4476 OS << "non-constant array initializer";
4477 break;
4478
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004479 case FK_AddressOfOverloadFailed:
4480 OS << "address of overloaded function failed";
4481 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004483 case FK_ReferenceInitOverloadFailed:
4484 OS << "overload resolution for reference initialization failed";
4485 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004486
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004487 case FK_NonConstLValueReferenceBindingToTemporary:
4488 OS << "non-const lvalue reference bound to temporary";
4489 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004490
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004491 case FK_NonConstLValueReferenceBindingToUnrelated:
4492 OS << "non-const lvalue reference bound to unrelated type";
4493 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004494
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004495 case FK_RValueReferenceBindingToLValue:
4496 OS << "rvalue reference bound to an lvalue";
4497 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004499 case FK_ReferenceInitDropsQualifiers:
4500 OS << "reference initialization drops qualifiers";
4501 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004502
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004503 case FK_ReferenceInitFailed:
4504 OS << "reference initialization failed";
4505 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004507 case FK_ConversionFailed:
4508 OS << "conversion failed";
4509 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
John Wiegley01296292011-04-08 18:41:53 +00004511 case FK_ConversionFromPropertyFailed:
4512 OS << "conversion from property failed";
4513 break;
4514
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004515 case FK_TooManyInitsForScalar:
4516 OS << "too many initializers for scalar";
4517 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004519 case FK_ReferenceBindingToInitList:
4520 OS << "referencing binding to initializer list";
4521 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004523 case FK_InitListBadDestinationType:
4524 OS << "initializer list for non-aggregate, non-scalar type";
4525 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004527 case FK_UserConversionOverloadFailed:
4528 OS << "overloading failed for user-defined conversion";
4529 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004531 case FK_ConstructorOverloadFailed:
4532 OS << "constructor overloading failed";
4533 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004535 case FK_DefaultInitOfConst:
4536 OS << "default initialization of a const variable";
4537 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004539 case FK_Incomplete:
4540 OS << "initialization of incomplete type";
4541 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004543 OS << '\n';
4544 return;
4545 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004547 case DependentSequence:
4548 OS << "Dependent sequence: ";
4549 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004551 case UserDefinedConversion:
4552 OS << "User-defined conversion sequence: ";
4553 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004555 case ConstructorInitialization:
4556 OS << "Constructor initialization sequence: ";
4557 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004559 case ReferenceBinding:
4560 OS << "Reference binding: ";
4561 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004563 case ListInitialization:
4564 OS << "List initialization: ";
4565 break;
4566
4567 case ZeroInitialization:
4568 OS << "Zero initialization\n";
4569 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004571 case NoInitialization:
4572 OS << "No initialization\n";
4573 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004575 case StandardConversion:
4576 OS << "Standard conversion: ";
4577 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004579 case CAssignment:
4580 OS << "C assignment: ";
4581 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004582
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004583 case StringInit:
4584 OS << "String initialization: ";
4585 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004586
4587 case ArrayInit:
4588 OS << "Array initialization: ";
4589 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004592 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4593 if (S != step_begin()) {
4594 OS << " -> ";
4595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004596
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004597 switch (S->Kind) {
4598 case SK_ResolveAddressOfOverloadedFunction:
4599 OS << "resolve address of overloaded function";
4600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004602 case SK_CastDerivedToBaseRValue:
4603 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004606 case SK_CastDerivedToBaseXValue:
4607 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004610 case SK_CastDerivedToBaseLValue:
4611 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4612 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004613
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004614 case SK_BindReference:
4615 OS << "bind reference to lvalue";
4616 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004618 case SK_BindReferenceToTemporary:
4619 OS << "bind reference to a temporary";
4620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004622 case SK_ExtraneousCopyToTemporary:
4623 OS << "extraneous C++03 copy to temporary";
4624 break;
4625
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004626 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004627 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004628 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004629
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004630 case SK_QualificationConversionRValue:
4631 OS << "qualification conversion (rvalue)";
4632
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004633 case SK_QualificationConversionXValue:
4634 OS << "qualification conversion (xvalue)";
4635
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004636 case SK_QualificationConversionLValue:
4637 OS << "qualification conversion (lvalue)";
4638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004640 case SK_ConversionSequence:
4641 OS << "implicit conversion sequence (";
4642 S->ICS->DebugPrint(); // FIXME: use OS
4643 OS << ")";
4644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004646 case SK_ListInitialization:
4647 OS << "list initialization";
4648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004650 case SK_ConstructorInitialization:
4651 OS << "constructor initialization";
4652 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004654 case SK_ZeroInitialization:
4655 OS << "zero initialization";
4656 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004658 case SK_CAssignment:
4659 OS << "C assignment";
4660 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004662 case SK_StringInit:
4663 OS << "string initialization";
4664 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004665
4666 case SK_ObjCObjectConversion:
4667 OS << "Objective-C object conversion";
4668 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004669
4670 case SK_ArrayInit:
4671 OS << "array initialization";
4672 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004673 }
4674 }
4675}
4676
4677void InitializationSequence::dump() const {
4678 dump(llvm::errs());
4679}
4680
Douglas Gregore1314a62009-12-18 05:02:21 +00004681//===----------------------------------------------------------------------===//
4682// Initialization helper functions
4683//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004685Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4686 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004687 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004688 if (Init.isInvalid())
4689 return ExprError();
4690
John McCall1f425642010-11-11 03:21:53 +00004691 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00004692 assert(InitE && "No initialization expression?");
4693
4694 if (EqualLoc.isInvalid())
4695 EqualLoc = InitE->getLocStart();
4696
4697 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4698 EqualLoc);
4699 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4700 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004701 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004702}