blob: 6a1bc97de7970848cf10f2c7d6dd326f3052bf63 [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.
716 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
717 SemaRef.CheckSingleAssignmentConstraints(ElemType, expr)
718 == Sema::Compatible) {
719 SemaRef.DefaultFunctionArrayLvalueConversion(expr);
720 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
721 ++Index;
722 return;
723 }
724
725 // Fall through for subaggregate initialization
726 }
727
728 // C++ [dcl.init.aggr]p12:
729 //
730 // [...] Otherwise, if the member is itself a non-empty
731 // subaggregate, brace elision is assumed and the initializer is
732 // considered for the initialization of the first member of
733 // the subaggregate.
734 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
735 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
736 StructuredIndex);
737 ++StructuredIndex;
738 } else {
739 // We cannot initialize this element, so let
740 // PerformCopyInitialization produce the appropriate diagnostic.
741 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
742 SemaRef.Owned(expr));
743 hadError = true;
744 ++Index;
745 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000746 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000747}
748
Anders Carlsson6cabf312010-01-23 23:23:01 +0000749void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000750 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000751 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000752 InitListExpr *StructuredList,
753 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000754 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000755 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000756 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000757 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000758 ++Index;
759 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000760 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000761 }
John McCall643169b2010-11-11 00:46:36 +0000762
763 Expr *expr = IList->getInit(Index);
764 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
765 SemaRef.Diag(SubIList->getLocStart(),
766 diag::warn_many_braces_around_scalar_init)
767 << SubIList->getSourceRange();
768
769 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
770 StructuredIndex);
771 return;
772 } else if (isa<DesignatedInitExpr>(expr)) {
773 SemaRef.Diag(expr->getSourceRange().getBegin(),
774 diag::err_designator_for_scalar_init)
775 << DeclType << expr->getSourceRange();
776 hadError = true;
777 ++Index;
778 ++StructuredIndex;
779 return;
780 }
781
782 ExprResult Result =
783 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
784 SemaRef.Owned(expr));
785
786 Expr *ResultExpr = 0;
787
788 if (Result.isInvalid())
789 hadError = true; // types weren't compatible.
790 else {
791 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000792
John McCall643169b2010-11-11 00:46:36 +0000793 if (ResultExpr != expr) {
794 // The type was promoted, update initializer list.
795 IList->setInit(Index, ResultExpr);
796 }
797 }
798 if (hadError)
799 ++StructuredIndex;
800 else
801 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
802 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000803}
804
Anders Carlsson6cabf312010-01-23 23:23:01 +0000805void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
806 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000807 unsigned &Index,
808 InitListExpr *StructuredList,
809 unsigned &StructuredIndex) {
810 if (Index < IList->getNumInits()) {
811 Expr *expr = IList->getInit(Index);
812 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000813 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000814 << DeclType << IList->getSourceRange();
815 hadError = true;
816 ++Index;
817 ++StructuredIndex;
818 return;
Mike Stump11289f42009-09-09 15:08:12 +0000819 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000820
John McCalldadc5752010-08-24 06:29:42 +0000821 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000822 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
823 SemaRef.Owned(expr));
824
825 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000826 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000827
828 expr = Result.takeAs<Expr>();
829 IList->setInit(Index, expr);
830
Douglas Gregord14247a2009-01-30 22:09:00 +0000831 if (hadError)
832 ++StructuredIndex;
833 else
834 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
835 ++Index;
836 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000837 // FIXME: It would be wonderful if we could point at the actual member. In
838 // general, it would be useful to pass location information down the stack,
839 // so that we know the location (or decl) of the "current object" being
840 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000841 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000842 diag::err_init_reference_member_uninitialized)
843 << DeclType
844 << IList->getSourceRange();
845 hadError = true;
846 ++Index;
847 ++StructuredIndex;
848 return;
849 }
850}
851
Anders Carlsson6cabf312010-01-23 23:23:01 +0000852void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000853 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000854 unsigned &Index,
855 InitListExpr *StructuredList,
856 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000857 if (Index >= IList->getNumInits())
858 return;
Mike Stump11289f42009-09-09 15:08:12 +0000859
John McCall6a16b2f2010-10-30 00:11:39 +0000860 const VectorType *VT = DeclType->getAs<VectorType>();
861 unsigned maxElements = VT->getNumElements();
862 unsigned numEltsInit = 0;
863 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000864
John McCall6a16b2f2010-10-30 00:11:39 +0000865 if (!SemaRef.getLangOptions().OpenCL) {
866 // If the initializing element is a vector, try to copy-initialize
867 // instead of breaking it apart (which is doomed to failure anyway).
868 Expr *Init = IList->getInit(Index);
869 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
870 ExprResult Result =
871 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
872 SemaRef.Owned(Init));
873
874 Expr *ResultExpr = 0;
875 if (Result.isInvalid())
876 hadError = true; // types weren't compatible.
877 else {
878 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879
John McCall6a16b2f2010-10-30 00:11:39 +0000880 if (ResultExpr != Init) {
881 // The type was promoted, update initializer list.
882 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000883 }
884 }
John McCall6a16b2f2010-10-30 00:11:39 +0000885 if (hadError)
886 ++StructuredIndex;
887 else
888 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
889 ++Index;
890 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000891 }
Mike Stump11289f42009-09-09 15:08:12 +0000892
John McCall6a16b2f2010-10-30 00:11:39 +0000893 InitializedEntity ElementEntity =
894 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000895
John McCall6a16b2f2010-10-30 00:11:39 +0000896 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
897 // Don't attempt to go past the end of the init list
898 if (Index >= IList->getNumInits())
899 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
John McCall6a16b2f2010-10-30 00:11:39 +0000901 ElementEntity.setElementIndex(Index);
902 CheckSubElementType(ElementEntity, IList, elementType, Index,
903 StructuredList, StructuredIndex);
904 }
905 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000906 }
John McCall6a16b2f2010-10-30 00:11:39 +0000907
908 InitializedEntity ElementEntity =
909 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000910
John McCall6a16b2f2010-10-30 00:11:39 +0000911 // OpenCL initializers allows vectors to be constructed from vectors.
912 for (unsigned i = 0; i < maxElements; ++i) {
913 // Don't attempt to go past the end of the init list
914 if (Index >= IList->getNumInits())
915 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
John McCall6a16b2f2010-10-30 00:11:39 +0000917 ElementEntity.setElementIndex(Index);
918
919 QualType IType = IList->getInit(Index)->getType();
920 if (!IType->isVectorType()) {
921 CheckSubElementType(ElementEntity, IList, elementType, Index,
922 StructuredList, StructuredIndex);
923 ++numEltsInit;
924 } else {
925 QualType VecType;
926 const VectorType *IVT = IType->getAs<VectorType>();
927 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000928
John McCall6a16b2f2010-10-30 00:11:39 +0000929 if (IType->isExtVectorType())
930 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
931 else
932 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000933 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000934 CheckSubElementType(ElementEntity, IList, VecType, Index,
935 StructuredList, StructuredIndex);
936 numEltsInit += numIElts;
937 }
938 }
939
940 // OpenCL requires all elements to be initialized.
941 if (numEltsInit != maxElements)
942 if (SemaRef.getLangOptions().OpenCL)
943 SemaRef.Diag(IList->getSourceRange().getBegin(),
944 diag::err_vector_incorrect_num_initializers)
945 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000946}
947
Anders Carlsson6cabf312010-01-23 23:23:01 +0000948void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000949 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000950 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000951 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000952 unsigned &Index,
953 InitListExpr *StructuredList,
954 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000955 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
956
Steve Narofff8ecff22008-05-01 22:18:59 +0000957 // Check for the special-case of initializing an array with a string.
958 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +0000959 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000960 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +0000961 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000962 // We place the string literal directly into the resulting
963 // initializer list. This is the only place where the structure
964 // of the structured initializer list doesn't match exactly,
965 // because doing so would involve allocating one character
966 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000967 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000968 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000969 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000970 return;
971 }
972 }
John McCall66884dd2011-02-21 07:22:22 +0000973 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000974 // Check for VLAs; in standard C it would be possible to check this
975 // earlier, but I don't know where clang accepts VLAs (gcc accepts
976 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000977 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000978 diag::err_variable_object_no_init)
979 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000980 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000981 ++Index;
982 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000983 return;
984 }
985
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000986 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000987 llvm::APSInt maxElements(elementIndex.getBitWidth(),
988 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000989 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +0000990 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000991 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +0000992 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000993 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000994 maxElementsKnown = true;
995 }
996
John McCall66884dd2011-02-21 07:22:22 +0000997 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000998 while (Index < IList->getNumInits()) {
999 Expr *Init = IList->getInit(Index);
1000 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001001 // If we're not the subobject that matches up with the '{' for
1002 // the designator, we shouldn't be handling the
1003 // designator. Return immediately.
1004 if (!SubobjectIsDesignatorContext)
1005 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001006
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001007 // Handle this designated initializer. elementIndex will be
1008 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001009 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001010 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001011 StructuredList, StructuredIndex, true,
1012 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001013 hadError = true;
1014 continue;
1015 }
1016
Douglas Gregor033d1252009-01-23 16:54:12 +00001017 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001018 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001019 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001020 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001021 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001022
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001023 // If the array is of incomplete type, keep track of the number of
1024 // elements in the initializer.
1025 if (!maxElementsKnown && elementIndex > maxElements)
1026 maxElements = elementIndex;
1027
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001028 continue;
1029 }
1030
1031 // If we know the maximum number of elements, and we've already
1032 // hit it, stop consuming elements in the initializer list.
1033 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001034 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001035
Anders Carlsson6cabf312010-01-23 23:23:01 +00001036 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001038 Entity);
1039 // Check this element.
1040 CheckSubElementType(ElementEntity, IList, elementType, Index,
1041 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001042 ++elementIndex;
1043
1044 // If the array is of incomplete type, keep track of the number of
1045 // elements in the initializer.
1046 if (!maxElementsKnown && elementIndex > maxElements)
1047 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001048 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001049 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001050 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001051 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001052 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001053 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001054 // Sizing an array implicitly to zero is not allowed by ISO C,
1055 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001056 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001057 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001058 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001059
Mike Stump11289f42009-09-09 15:08:12 +00001060 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001061 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001062 }
1063}
1064
Anders Carlsson6cabf312010-01-23 23:23:01 +00001065void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001066 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001067 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001068 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001069 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001070 unsigned &Index,
1071 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001072 unsigned &StructuredIndex,
1073 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001074 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001075
Eli Friedman23a9e312008-05-19 19:16:24 +00001076 // If the record is invalid, some of it's members are invalid. To avoid
1077 // confusion, we forgo checking the intializer for the entire record.
1078 if (structDecl->isInvalidDecl()) {
1079 hadError = true;
1080 return;
Mike Stump11289f42009-09-09 15:08:12 +00001081 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001082
1083 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1084 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001085 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001086 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001087 Field != FieldEnd; ++Field) {
1088 if (Field->getDeclName()) {
1089 StructuredList->setInitializedFieldInUnion(*Field);
1090 break;
1091 }
1092 }
1093 return;
1094 }
1095
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001096 // If structDecl is a forward declaration, this loop won't do
1097 // anything except look at designated initializers; That's okay,
1098 // because an error should get printed out elsewhere. It might be
1099 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001100 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001101 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001102 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001103 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001104 while (Index < IList->getNumInits()) {
1105 Expr *Init = IList->getInit(Index);
1106
1107 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001108 // If we're not the subobject that matches up with the '{' for
1109 // the designator, we shouldn't be handling the
1110 // designator. Return immediately.
1111 if (!SubobjectIsDesignatorContext)
1112 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001113
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001114 // Handle this designated initializer. Field will be updated to
1115 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001116 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001117 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001118 StructuredList, StructuredIndex,
1119 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001120 hadError = true;
1121
Douglas Gregora9add4e2009-02-12 19:00:39 +00001122 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001123
1124 // Disable check for missing fields when designators are used.
1125 // This matches gcc behaviour.
1126 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001127 continue;
1128 }
1129
1130 if (Field == FieldEnd) {
1131 // We've run out of fields. We're done.
1132 break;
1133 }
1134
Douglas Gregora9add4e2009-02-12 19:00:39 +00001135 // We've already initialized a member of a union. We're done.
1136 if (InitializedSomething && DeclType->isUnionType())
1137 break;
1138
Douglas Gregor91f84212008-12-11 16:49:14 +00001139 // If we've hit the flexible array member at the end, we're done.
1140 if (Field->getType()->isIncompleteArrayType())
1141 break;
1142
Douglas Gregor51695702009-01-29 16:53:55 +00001143 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001144 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001145 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001146 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001147 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001148
Anders Carlsson6cabf312010-01-23 23:23:01 +00001149 InitializedEntity MemberEntity =
1150 InitializedEntity::InitializeMember(*Field, &Entity);
1151 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1152 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001153 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001154
1155 if (DeclType->isUnionType()) {
1156 // Initialize the first field within the union.
1157 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001158 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001159
1160 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001161 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001162
John McCalle40b58e2010-03-11 19:32:38 +00001163 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001164 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001165 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1166 // It is possible we have one or more unnamed bitfields remaining.
1167 // Find first (if any) named field and emit warning.
1168 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1169 it != end; ++it) {
1170 if (!it->isUnnamedBitfield()) {
1171 SemaRef.Diag(IList->getSourceRange().getEnd(),
1172 diag::warn_missing_field_initializers) << it->getName();
1173 break;
1174 }
1175 }
1176 }
1177
Mike Stump11289f42009-09-09 15:08:12 +00001178 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001179 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001180 return;
1181
1182 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001183 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001184 (!isa<InitListExpr>(IList->getInit(Index)) ||
1185 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001186 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001187 diag::err_flexible_array_init_nonempty)
1188 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001189 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001190 << *Field;
1191 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001192 ++Index;
1193 return;
1194 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001195 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001196 diag::ext_flexible_array_init)
1197 << IList->getInit(Index)->getSourceRange().getBegin();
1198 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1199 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001200 }
1201
Anders Carlsson6cabf312010-01-23 23:23:01 +00001202 InitializedEntity MemberEntity =
1203 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001204
Anders Carlsson6cabf312010-01-23 23:23:01 +00001205 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001206 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001207 StructuredList, StructuredIndex);
1208 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001210 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001211}
Steve Narofff8ecff22008-05-01 22:18:59 +00001212
Douglas Gregord5846a12009-04-15 06:41:24 +00001213/// \brief Expand a field designator that refers to a member of an
1214/// anonymous struct or union into a series of field designators that
1215/// refers to the field within the appropriate subobject.
1216///
Douglas Gregord5846a12009-04-15 06:41:24 +00001217static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001218 DesignatedInitExpr *DIE,
1219 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001220 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001221 typedef DesignatedInitExpr::Designator Designator;
1222
Douglas Gregord5846a12009-04-15 06:41:24 +00001223 // Build the replacement designators.
1224 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001225 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1226 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1227 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001228 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001229 DIE->getDesignator(DesigIdx)->getDotLoc(),
1230 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1231 else
1232 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1233 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001234 assert(isa<FieldDecl>(*PI));
1235 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001236 }
1237
1238 // Expand the current designator into the set of replacement
1239 // designators, so we have a full subobject path down to where the
1240 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001241 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001242 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001243}
Mike Stump11289f42009-09-09 15:08:12 +00001244
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001245/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001246/// corresponds to FieldName.
1247static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1248 IdentifierInfo *FieldName) {
1249 assert(AnonField->isAnonymousStructOrUnion());
1250 Decl *NextDecl = AnonField->getNextDeclInContext();
1251 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1252 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1253 return IF;
1254 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001255 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001256 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001257}
1258
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001259/// @brief Check the well-formedness of a C99 designated initializer.
1260///
1261/// Determines whether the designated initializer @p DIE, which
1262/// resides at the given @p Index within the initializer list @p
1263/// IList, is well-formed for a current object of type @p DeclType
1264/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001265/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001266/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001267///
1268/// @param IList The initializer list in which this designated
1269/// initializer occurs.
1270///
Douglas Gregora5324162009-04-15 04:56:10 +00001271/// @param DIE The designated initializer expression.
1272///
1273/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001274///
1275/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1276/// into which the designation in @p DIE should refer.
1277///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001278/// @param NextField If non-NULL and the first designator in @p DIE is
1279/// a field, this will be set to the field declaration corresponding
1280/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001281///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001282/// @param NextElementIndex If non-NULL and the first designator in @p
1283/// DIE is an array designator or GNU array-range designator, this
1284/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001285///
1286/// @param Index Index into @p IList where the designated initializer
1287/// @p DIE occurs.
1288///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001289/// @param StructuredList The initializer list expression that
1290/// describes all of the subobject initializers in the order they'll
1291/// actually be initialized.
1292///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001293/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001294bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001295InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001296 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001297 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001298 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001299 QualType &CurrentObjectType,
1300 RecordDecl::field_iterator *NextField,
1301 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001302 unsigned &Index,
1303 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001304 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001305 bool FinishSubobjectInit,
1306 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001307 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001308 // Check the actual initialization for the designated object type.
1309 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001310
1311 // Temporarily remove the designator expression from the
1312 // initializer list that the child calls see, so that we don't try
1313 // to re-process the designator.
1314 unsigned OldIndex = Index;
1315 IList->setInit(OldIndex, DIE->getInit());
1316
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001317 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001318 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001319
1320 // Restore the designated initializer expression in the syntactic
1321 // form of the initializer list.
1322 if (IList->getInit(OldIndex) != DIE->getInit())
1323 DIE->setInit(IList->getInit(OldIndex));
1324 IList->setInit(OldIndex, DIE);
1325
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001326 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001327 }
1328
Douglas Gregora5324162009-04-15 04:56:10 +00001329 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001330 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001331 "Need a non-designated initializer list to start from");
1332
Douglas Gregora5324162009-04-15 04:56:10 +00001333 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001334 // Determine the structural initializer list that corresponds to the
1335 // current subobject.
1336 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001337 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001338 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001339 SourceRange(D->getStartLocation(),
1340 DIE->getSourceRange().getEnd()));
1341 assert(StructuredList && "Expected a structured initializer list");
1342
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001343 if (D->isFieldDesignator()) {
1344 // C99 6.7.8p7:
1345 //
1346 // If a designator has the form
1347 //
1348 // . identifier
1349 //
1350 // then the current object (defined below) shall have
1351 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001352 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001353 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001354 if (!RT) {
1355 SourceLocation Loc = D->getDotLoc();
1356 if (Loc.isInvalid())
1357 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001358 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1359 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001360 ++Index;
1361 return true;
1362 }
1363
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001364 // Note: we perform a linear search of the fields here, despite
1365 // the fact that we have a faster lookup method, because we always
1366 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001367 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001368 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001369 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001370 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001371 Field = RT->getDecl()->field_begin(),
1372 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001373 for (; Field != FieldEnd; ++Field) {
1374 if (Field->isUnnamedBitfield())
1375 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001376
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001377 // If we find a field representing an anonymous field, look in the
1378 // IndirectFieldDecl that follow for the designated initializer.
1379 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1380 if (IndirectFieldDecl *IF =
1381 FindIndirectFieldDesignator(*Field, FieldName)) {
1382 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1383 D = DIE->getDesignator(DesigIdx);
1384 break;
1385 }
1386 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001387 if (KnownField && KnownField == *Field)
1388 break;
1389 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001390 break;
1391
1392 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001393 }
1394
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001395 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001396 // There was no normal field in the struct with the designated
1397 // name. Perform another lookup for this name, which may find
1398 // something that we can't designate (e.g., a member function),
1399 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001400 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001401 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001402 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001403 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001404 // Name lookup didn't find anything. Determine whether this
1405 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001407 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001408 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001409 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001410 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001411 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001412 ->Equals(RT->getDecl())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001414 diag::err_field_designator_unknown_suggest)
1415 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001416 << FixItHint::CreateReplacement(D->getFieldLoc(),
1417 R.getLookupName().getAsString());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001418 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregor6da83622010-01-07 00:17:44 +00001419 diag::note_previous_decl)
1420 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001421 } else {
1422 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1423 << FieldName << CurrentObjectType;
1424 ++Index;
1425 return true;
1426 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001428
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001429 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001430 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001431 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001432 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001433 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001434 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001435 ++Index;
1436 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001437 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001438
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001439 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001440 // The replacement field comes from typo correction; find it
1441 // in the list of fields.
1442 FieldIndex = 0;
1443 Field = RT->getDecl()->field_begin();
1444 for (; Field != FieldEnd; ++Field) {
1445 if (Field->isUnnamedBitfield())
1446 continue;
1447
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001448 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001449 Field->getIdentifier() == ReplacementField->getIdentifier())
1450 break;
1451
1452 ++FieldIndex;
1453 }
1454 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001455 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001456
1457 // All of the fields of a union are located at the same place in
1458 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001459 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001460 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001461 StructuredList->setInitializedFieldInUnion(*Field);
1462 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001463
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001464 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001465 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001466
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001467 // Make sure that our non-designated initializer list has space
1468 // for a subobject corresponding to this field.
1469 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001470 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001471
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001472 // This designator names a flexible array member.
1473 if (Field->getType()->isIncompleteArrayType()) {
1474 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001475 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001476 // We can't designate an object within the flexible array
1477 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001478 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001479 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001480 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001481 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001482 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001483 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001484 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001485 << *Field;
1486 Invalid = true;
1487 }
1488
Chris Lattner001b29c2010-10-10 17:49:49 +00001489 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1490 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001491 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001492 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001493 diag::err_flexible_array_init_needs_braces)
1494 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001495 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001496 << *Field;
1497 Invalid = true;
1498 }
1499
1500 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001501 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001502 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001503 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001504 diag::err_flexible_array_init_nonempty)
1505 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001506 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001507 << *Field;
1508 Invalid = true;
1509 }
1510
1511 if (Invalid) {
1512 ++Index;
1513 return true;
1514 }
1515
1516 // Initialize the array.
1517 bool prevHadError = hadError;
1518 unsigned newStructuredIndex = FieldIndex;
1519 unsigned OldIndex = Index;
1520 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001521
1522 InitializedEntity MemberEntity =
1523 InitializedEntity::InitializeMember(*Field, &Entity);
1524 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001525 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001526
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001527 IList->setInit(OldIndex, DIE);
1528 if (hadError && !prevHadError) {
1529 ++Field;
1530 ++FieldIndex;
1531 if (NextField)
1532 *NextField = Field;
1533 StructuredIndex = FieldIndex;
1534 return true;
1535 }
1536 } else {
1537 // Recurse to check later designated subobjects.
1538 QualType FieldType = (*Field)->getType();
1539 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001540
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001541 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001542 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001543 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1544 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001545 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001546 true, false))
1547 return true;
1548 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001549
1550 // Find the position of the next field to be initialized in this
1551 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001552 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001553 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001554
1555 // If this the first designator, our caller will continue checking
1556 // the rest of this struct/class/union subobject.
1557 if (IsFirstDesignator) {
1558 if (NextField)
1559 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001560 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001561 return false;
1562 }
1563
Douglas Gregor17bd0942009-01-28 23:36:17 +00001564 if (!FinishSubobjectInit)
1565 return false;
1566
Douglas Gregord5846a12009-04-15 06:41:24 +00001567 // We've already initialized something in the union; we're done.
1568 if (RT->getDecl()->isUnion())
1569 return hadError;
1570
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571 // Check the remaining fields within this class/struct/union subobject.
1572 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001573
Anders Carlsson6cabf312010-01-23 23:23:01 +00001574 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001575 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001576 return hadError && !prevHadError;
1577 }
1578
1579 // C99 6.7.8p6:
1580 //
1581 // If a designator has the form
1582 //
1583 // [ constant-expression ]
1584 //
1585 // then the current object (defined below) shall have array
1586 // type and the expression shall be an integer constant
1587 // expression. If the array is of unknown size, any
1588 // nonnegative value is valid.
1589 //
1590 // Additionally, cope with the GNU extension that permits
1591 // designators of the form
1592 //
1593 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001594 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001595 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001596 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001597 << CurrentObjectType;
1598 ++Index;
1599 return true;
1600 }
1601
1602 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001603 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1604 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001605 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001606 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001607 DesignatedEndIndex = DesignatedStartIndex;
1608 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001609 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001610
Mike Stump11289f42009-09-09 15:08:12 +00001611 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001612 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001613 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001614 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001615 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001616
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001617 // Codegen can't handle evaluating array range designators that have side
1618 // effects, because we replicate the AST value for each initialized element.
1619 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1620 // elements with something that has a side effect, so codegen can emit an
1621 // "error unsupported" error instead of miscompiling the app.
1622 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1623 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001624 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001625 }
1626
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001627 if (isa<ConstantArrayType>(AT)) {
1628 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001629 DesignatedStartIndex
1630 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001631 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001632 DesignatedEndIndex
1633 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001634 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1635 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001636 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001637 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001638 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001639 << IndexExpr->getSourceRange();
1640 ++Index;
1641 return true;
1642 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001643 } else {
1644 // Make sure the bit-widths and signedness match.
1645 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001646 DesignatedEndIndex
1647 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001648 else if (DesignatedStartIndex.getBitWidth() <
1649 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001650 DesignatedStartIndex
1651 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001652 DesignatedStartIndex.setIsUnsigned(true);
1653 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001654 }
Mike Stump11289f42009-09-09 15:08:12 +00001655
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001656 // Make sure that our non-designated initializer list has space
1657 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001658 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001659 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001660 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001661
Douglas Gregor17bd0942009-01-28 23:36:17 +00001662 // Repeatedly perform subobject initializations in the range
1663 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001664
Douglas Gregor17bd0942009-01-28 23:36:17 +00001665 // Move to the next designator
1666 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1667 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001669 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001670 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001671
Douglas Gregor17bd0942009-01-28 23:36:17 +00001672 while (DesignatedStartIndex <= DesignatedEndIndex) {
1673 // Recurse to check later designated subobjects.
1674 QualType ElementType = AT->getElementType();
1675 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001677 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1679 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001680 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001681 (DesignatedStartIndex == DesignatedEndIndex),
1682 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001683 return true;
1684
1685 // Move to the next index in the array that we'll be initializing.
1686 ++DesignatedStartIndex;
1687 ElementIndex = DesignatedStartIndex.getZExtValue();
1688 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001689
1690 // If this the first designator, our caller will continue checking
1691 // the rest of this array subobject.
1692 if (IsFirstDesignator) {
1693 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001694 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001695 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001696 return false;
1697 }
Mike Stump11289f42009-09-09 15:08:12 +00001698
Douglas Gregor17bd0942009-01-28 23:36:17 +00001699 if (!FinishSubobjectInit)
1700 return false;
1701
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001702 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001703 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001705 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001706 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001707 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001708}
1709
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001710// Get the structured initializer list for a subobject of type
1711// @p CurrentObjectType.
1712InitListExpr *
1713InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1714 QualType CurrentObjectType,
1715 InitListExpr *StructuredList,
1716 unsigned StructuredIndex,
1717 SourceRange InitRange) {
1718 Expr *ExistingInit = 0;
1719 if (!StructuredList)
1720 ExistingInit = SyntacticToSemantic[IList];
1721 else if (StructuredIndex < StructuredList->getNumInits())
1722 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001723
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001724 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1725 return Result;
1726
1727 if (ExistingInit) {
1728 // We are creating an initializer list that initializes the
1729 // subobjects of the current object, but there was already an
1730 // initialization that completely initialized the current
1731 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001732 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001733 // struct X { int a, b; };
1734 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001735 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001736 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1737 // designated initializer re-initializes the whole
1738 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001739 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001740 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001742 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001744 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001745 << ExistingInit->getSourceRange();
1746 }
1747
Mike Stump11289f42009-09-09 15:08:12 +00001748 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001749 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1750 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001751 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001752
Douglas Gregora8a089b2010-07-13 18:40:04 +00001753 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001754
Douglas Gregor6d00c992009-03-20 23:58:33 +00001755 // Pre-allocate storage for the structured initializer list.
1756 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001757 unsigned NumInits = 0;
1758 if (!StructuredList)
1759 NumInits = IList->getNumInits();
1760 else if (Index < IList->getNumInits()) {
1761 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1762 NumInits = SubList->getNumInits();
1763 }
1764
Mike Stump11289f42009-09-09 15:08:12 +00001765 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001766 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1767 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1768 NumElements = CAType->getSize().getZExtValue();
1769 // Simple heuristic so that we don't allocate a very large
1770 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001771 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001772 NumElements = 0;
1773 }
John McCall9dd450b2009-09-21 23:43:11 +00001774 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001775 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001776 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001777 RecordDecl *RDecl = RType->getDecl();
1778 if (RDecl->isUnion())
1779 NumElements = 1;
1780 else
Mike Stump11289f42009-09-09 15:08:12 +00001781 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001782 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001783 }
1784
Douglas Gregor221c9a52009-03-21 18:13:52 +00001785 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001786 NumElements = IList->getNumInits();
1787
Ted Kremenekac034612010-04-13 23:39:13 +00001788 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001789
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001790 // Link this new initializer list into the structured initializer
1791 // lists.
1792 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001793 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794 else {
1795 Result->setSyntacticForm(IList);
1796 SyntacticToSemantic[IList] = Result;
1797 }
1798
1799 return Result;
1800}
1801
1802/// Update the initializer at index @p StructuredIndex within the
1803/// structured initializer list to the value @p expr.
1804void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1805 unsigned &StructuredIndex,
1806 Expr *expr) {
1807 // No structured initializer list to update
1808 if (!StructuredList)
1809 return;
1810
Ted Kremenekac034612010-04-13 23:39:13 +00001811 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1812 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001813 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001814 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001815 diag::warn_initializer_overrides)
1816 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001817 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001818 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001819 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001820 << PrevInit->getSourceRange();
1821 }
Mike Stump11289f42009-09-09 15:08:12 +00001822
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001823 ++StructuredIndex;
1824}
1825
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001826/// Check that the given Index expression is a valid array designator
1827/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001828/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001829/// and produces a reasonable diagnostic if there is a
1830/// failure. Returns true if there was an error, false otherwise. If
1831/// everything went okay, Value will receive the value of the constant
1832/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001833static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001834CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001835 SourceLocation Loc = Index->getSourceRange().getBegin();
1836
1837 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001838 if (S.VerifyIntegerConstantExpression(Index, &Value))
1839 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001840
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001841 if (Value.isSigned() && Value.isNegative())
1842 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001843 << Value.toString(10) << Index->getSourceRange();
1844
Douglas Gregor51650d32009-01-23 21:04:18 +00001845 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001846 return false;
1847}
1848
John McCalldadc5752010-08-24 06:29:42 +00001849ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001850 SourceLocation Loc,
1851 bool GNUSyntax,
1852 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001853 typedef DesignatedInitExpr::Designator ASTDesignator;
1854
1855 bool Invalid = false;
1856 llvm::SmallVector<ASTDesignator, 32> Designators;
1857 llvm::SmallVector<Expr *, 32> InitExpressions;
1858
1859 // Build designators and check array designator expressions.
1860 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1861 const Designator &D = Desig.getDesignator(Idx);
1862 switch (D.getKind()) {
1863 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001864 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001865 D.getFieldLoc()));
1866 break;
1867
1868 case Designator::ArrayDesignator: {
1869 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1870 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001871 if (!Index->isTypeDependent() &&
1872 !Index->isValueDependent() &&
1873 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001874 Invalid = true;
1875 else {
1876 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001877 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001878 D.getRBracketLoc()));
1879 InitExpressions.push_back(Index);
1880 }
1881 break;
1882 }
1883
1884 case Designator::ArrayRangeDesignator: {
1885 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1886 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1887 llvm::APSInt StartValue;
1888 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001889 bool StartDependent = StartIndex->isTypeDependent() ||
1890 StartIndex->isValueDependent();
1891 bool EndDependent = EndIndex->isTypeDependent() ||
1892 EndIndex->isValueDependent();
1893 if ((!StartDependent &&
1894 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1895 (!EndDependent &&
1896 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001897 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001898 else {
1899 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001900 if (StartDependent || EndDependent) {
1901 // Nothing to compute.
1902 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001903 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001904 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001905 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001906
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001907 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001908 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001909 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001910 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1911 Invalid = true;
1912 } else {
1913 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001914 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001915 D.getEllipsisLoc(),
1916 D.getRBracketLoc()));
1917 InitExpressions.push_back(StartIndex);
1918 InitExpressions.push_back(EndIndex);
1919 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001920 }
1921 break;
1922 }
1923 }
1924 }
1925
1926 if (Invalid || Init.isInvalid())
1927 return ExprError();
1928
1929 // Clear out the expressions within the designation.
1930 Desig.ClearExprs(*this);
1931
1932 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001933 = DesignatedInitExpr::Create(Context,
1934 Designators.data(), Designators.size(),
1935 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001936 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937
Douglas Gregorc124e592011-01-16 16:13:16 +00001938 if (getLangOptions().CPlusPlus)
1939 Diag(DIE->getLocStart(), diag::ext_designated_init)
1940 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001942 return Owned(DIE);
1943}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001944
Douglas Gregor723796a2009-12-16 06:35:08 +00001945bool Sema::CheckInitList(const InitializedEntity &Entity,
1946 InitListExpr *&InitList, QualType &DeclType) {
1947 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001948 if (!CheckInitList.HadError())
1949 InitList = CheckInitList.getFullyStructuredList();
1950
1951 return CheckInitList.HadError();
1952}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001953
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001954//===----------------------------------------------------------------------===//
1955// Initialization entity
1956//===----------------------------------------------------------------------===//
1957
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00001959 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001960 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001961{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001962 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1963 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001964 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001965 } else {
1966 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001967 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001968 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001969}
1970
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001972 CXXBaseSpecifier *Base,
1973 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001974{
1975 InitializedEntity Result;
1976 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001977 Result.Base = reinterpret_cast<uintptr_t>(Base);
1978 if (IsInheritedVirtualBase)
1979 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Douglas Gregor1b303932009-12-22 15:35:07 +00001981 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001982 return Result;
1983}
1984
Douglas Gregor85dabae2009-12-16 01:38:02 +00001985DeclarationName InitializedEntity::getName() const {
1986 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001987 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001988 if (!VariableOrMember)
1989 return DeclarationName();
1990 // Fall through
1991
1992 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001993 case EK_Member:
1994 return VariableOrMember->getDeclName();
1995
1996 case EK_Result:
1997 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001998 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001999 case EK_Temporary:
2000 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002001 case EK_ArrayElement:
2002 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002003 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002004 return DeclarationName();
2005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006
Douglas Gregor85dabae2009-12-16 01:38:02 +00002007 // Silence GCC warning
2008 return DeclarationName();
2009}
2010
Douglas Gregora4b592a2009-12-19 03:01:41 +00002011DeclaratorDecl *InitializedEntity::getDecl() const {
2012 switch (getKind()) {
2013 case EK_Variable:
2014 case EK_Parameter:
2015 case EK_Member:
2016 return VariableOrMember;
2017
2018 case EK_Result:
2019 case EK_Exception:
2020 case EK_New:
2021 case EK_Temporary:
2022 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002023 case EK_ArrayElement:
2024 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002025 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002026 return 0;
2027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028
Douglas Gregora4b592a2009-12-19 03:01:41 +00002029 // Silence GCC warning
2030 return 0;
2031}
2032
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002033bool InitializedEntity::allowsNRVO() const {
2034 switch (getKind()) {
2035 case EK_Result:
2036 case EK_Exception:
2037 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002039 case EK_Variable:
2040 case EK_Parameter:
2041 case EK_Member:
2042 case EK_New:
2043 case EK_Temporary:
2044 case EK_Base:
2045 case EK_ArrayElement:
2046 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002047 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002048 break;
2049 }
2050
2051 return false;
2052}
2053
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002054//===----------------------------------------------------------------------===//
2055// Initialization sequence
2056//===----------------------------------------------------------------------===//
2057
2058void InitializationSequence::Step::Destroy() {
2059 switch (Kind) {
2060 case SK_ResolveAddressOfOverloadedFunction:
2061 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002062 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002063 case SK_CastDerivedToBaseLValue:
2064 case SK_BindReference:
2065 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002066 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002067 case SK_UserConversion:
2068 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002069 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002070 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002071 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002072 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002073 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002074 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002075 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002076 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002077 case SK_ArrayInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002078 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002080 case SK_ConversionSequence:
2081 delete ICS;
2082 }
2083}
2084
Douglas Gregor838fcc32010-03-26 20:14:36 +00002085bool InitializationSequence::isDirectReferenceBinding() const {
2086 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2087}
2088
2089bool InitializationSequence::isAmbiguous() const {
2090 if (getKind() != FailedSequence)
2091 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002092
Douglas Gregor838fcc32010-03-26 20:14:36 +00002093 switch (getFailureKind()) {
2094 case FK_TooManyInitsForReference:
2095 case FK_ArrayNeedsInitList:
2096 case FK_ArrayNeedsInitListOrStringLiteral:
2097 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2098 case FK_NonConstLValueReferenceBindingToTemporary:
2099 case FK_NonConstLValueReferenceBindingToUnrelated:
2100 case FK_RValueReferenceBindingToLValue:
2101 case FK_ReferenceInitDropsQualifiers:
2102 case FK_ReferenceInitFailed:
2103 case FK_ConversionFailed:
2104 case FK_TooManyInitsForScalar:
2105 case FK_ReferenceBindingToInitList:
2106 case FK_InitListBadDestinationType:
2107 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002108 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002109 case FK_ArrayTypeMismatch:
2110 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002111 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Douglas Gregor838fcc32010-03-26 20:14:36 +00002113 case FK_ReferenceInitOverloadFailed:
2114 case FK_UserConversionOverloadFailed:
2115 case FK_ConstructorOverloadFailed:
2116 return FailedOverloadResult == OR_Ambiguous;
2117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002118
Douglas Gregor838fcc32010-03-26 20:14:36 +00002119 return false;
2120}
2121
Douglas Gregorb33eed02010-04-16 22:09:46 +00002122bool InitializationSequence::isConstructorInitialization() const {
2123 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2124}
2125
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002126void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002127 FunctionDecl *Function,
2128 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002129 Step S;
2130 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2131 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002132 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002133 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002134 Steps.push_back(S);
2135}
2136
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002138 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002139 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002140 switch (VK) {
2141 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2142 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2143 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002144 default: llvm_unreachable("No such category");
2145 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002146 S.Type = BaseType;
2147 Steps.push_back(S);
2148}
2149
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002151 bool BindingTemporary) {
2152 Step S;
2153 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2154 S.Type = T;
2155 Steps.push_back(S);
2156}
2157
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002158void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2159 Step S;
2160 S.Kind = SK_ExtraneousCopyToTemporary;
2161 S.Type = T;
2162 Steps.push_back(S);
2163}
2164
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002165void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002166 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002167 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002168 Step S;
2169 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002170 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002171 S.Function.Function = Function;
2172 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002173 Steps.push_back(S);
2174}
2175
2176void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002177 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002178 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002179 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002180 switch (VK) {
2181 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002182 S.Kind = SK_QualificationConversionRValue;
2183 break;
John McCall2536c6d2010-08-25 10:28:54 +00002184 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002185 S.Kind = SK_QualificationConversionXValue;
2186 break;
John McCall2536c6d2010-08-25 10:28:54 +00002187 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002188 S.Kind = SK_QualificationConversionLValue;
2189 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002190 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002191 S.Type = Ty;
2192 Steps.push_back(S);
2193}
2194
2195void InitializationSequence::AddConversionSequenceStep(
2196 const ImplicitConversionSequence &ICS,
2197 QualType T) {
2198 Step S;
2199 S.Kind = SK_ConversionSequence;
2200 S.Type = T;
2201 S.ICS = new ImplicitConversionSequence(ICS);
2202 Steps.push_back(S);
2203}
2204
Douglas Gregor51e77d52009-12-10 17:56:55 +00002205void InitializationSequence::AddListInitializationStep(QualType T) {
2206 Step S;
2207 S.Kind = SK_ListInitialization;
2208 S.Type = T;
2209 Steps.push_back(S);
2210}
2211
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002212void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002213InitializationSequence::AddConstructorInitializationStep(
2214 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002215 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002216 QualType T) {
2217 Step S;
2218 S.Kind = SK_ConstructorInitialization;
2219 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002220 S.Function.Function = Constructor;
2221 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002222 Steps.push_back(S);
2223}
2224
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002225void InitializationSequence::AddZeroInitializationStep(QualType T) {
2226 Step S;
2227 S.Kind = SK_ZeroInitialization;
2228 S.Type = T;
2229 Steps.push_back(S);
2230}
2231
Douglas Gregore1314a62009-12-18 05:02:21 +00002232void InitializationSequence::AddCAssignmentStep(QualType T) {
2233 Step S;
2234 S.Kind = SK_CAssignment;
2235 S.Type = T;
2236 Steps.push_back(S);
2237}
2238
Eli Friedman78275202009-12-19 08:11:05 +00002239void InitializationSequence::AddStringInitStep(QualType T) {
2240 Step S;
2241 S.Kind = SK_StringInit;
2242 S.Type = T;
2243 Steps.push_back(S);
2244}
2245
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002246void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2247 Step S;
2248 S.Kind = SK_ObjCObjectConversion;
2249 S.Type = T;
2250 Steps.push_back(S);
2251}
2252
Douglas Gregore2f943b2011-02-22 18:29:51 +00002253void InitializationSequence::AddArrayInitStep(QualType T) {
2254 Step S;
2255 S.Kind = SK_ArrayInit;
2256 S.Type = T;
2257 Steps.push_back(S);
2258}
2259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002261 OverloadingResult Result) {
2262 SequenceKind = FailedSequence;
2263 this->Failure = Failure;
2264 this->FailedOverloadResult = Result;
2265}
2266
2267//===----------------------------------------------------------------------===//
2268// Attempt initialization
2269//===----------------------------------------------------------------------===//
2270
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002271/// \brief Attempt list initialization (C++0x [dcl.init.list])
2272static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002273 const InitializedEntity &Entity,
2274 const InitializationKind &Kind,
2275 InitListExpr *InitList,
2276 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002277 // FIXME: We only perform rudimentary checking of list
2278 // initializations at this point, then assume that any list
2279 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002280 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002281 // do all of the necessary checking. C++0x initializer lists will
2282 // force us to perform more checking here.
2283 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2284
Douglas Gregor1b303932009-12-22 15:35:07 +00002285 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002286
2287 // C++ [dcl.init]p13:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002288 // If T is a scalar type, then a declaration of the form
Douglas Gregor51e77d52009-12-10 17:56:55 +00002289 //
2290 // T x = { a };
2291 //
2292 // is equivalent to
2293 //
2294 // T x = a;
2295 if (DestType->isScalarType()) {
2296 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2297 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2298 return;
2299 }
2300
2301 // Assume scalar initialization from a single value works.
2302 } else if (DestType->isAggregateType()) {
2303 // Assume aggregate initialization works.
2304 } else if (DestType->isVectorType()) {
2305 // Assume vector initialization works.
2306 } else if (DestType->isReferenceType()) {
2307 // FIXME: C++0x defines behavior for this.
2308 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2309 return;
2310 } else if (DestType->isRecordType()) {
2311 // FIXME: C++0x defines behavior for this
2312 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2313 }
2314
2315 // Add a general "list initialization" step.
2316 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317}
2318
2319/// \brief Try a reference initialization that involves calling a conversion
2320/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002321static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2322 const InitializedEntity &Entity,
2323 const InitializationKind &Kind,
2324 Expr *Initializer,
2325 bool AllowRValues,
2326 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002327 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002328 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2329 QualType T1 = cv1T1.getUnqualifiedType();
2330 QualType cv2T2 = Initializer->getType();
2331 QualType T2 = cv2T2.getUnqualifiedType();
2332
2333 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002334 bool ObjCConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002335 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002336 T1, T2, DerivedToBase,
2337 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002338 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002339 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002340 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002341
2342 // Build the candidate set directly in the initialization sequence
2343 // structure, so that it will persist if we fail.
2344 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2345 CandidateSet.clear();
2346
2347 // Determine whether we are allowed to call explicit constructors or
2348 // explicit conversion operators.
2349 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002350
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002351 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002352 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2353 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002354 // The type we're converting to is a class type. Enumerate its constructors
2355 // to see if there is a suitable conversion.
2356 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002357
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002358 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002359 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002360 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002361 NamedDecl *D = *Con;
2362 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2363
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002364 // Find the constructor (which may be a template).
2365 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002366 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002367 if (ConstructorTmpl)
2368 Constructor = cast<CXXConstructorDecl>(
2369 ConstructorTmpl->getTemplatedDecl());
2370 else
John McCalla0296f72010-03-19 07:35:19 +00002371 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002372
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002373 if (!Constructor->isInvalidDecl() &&
2374 Constructor->isConvertingConstructor(AllowExplicit)) {
2375 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002376 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002377 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002378 &Initializer, 1, CandidateSet,
2379 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002380 else
John McCalla0296f72010-03-19 07:35:19 +00002381 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002382 &Initializer, 1, CandidateSet,
2383 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002385 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002386 }
John McCall3696dcb2010-08-17 07:23:57 +00002387 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2388 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002389
Douglas Gregor496e8b342010-05-07 19:42:26 +00002390 const RecordType *T2RecordType = 0;
2391 if ((T2RecordType = T2->getAs<RecordType>()) &&
2392 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002393 // The type we're converting from is a class type, enumerate its conversion
2394 // functions.
2395 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2396
John McCallad371252010-01-20 00:46:10 +00002397 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002398 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002399 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2400 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002401 NamedDecl *D = *I;
2402 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2403 if (isa<UsingShadowDecl>(D))
2404 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002405
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002406 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2407 CXXConversionDecl *Conv;
2408 if (ConvTemplate)
2409 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2410 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002411 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002412
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002413 // If the conversion function doesn't return a reference type,
2414 // it can't be considered for this conversion unless we're allowed to
2415 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002416 // FIXME: Do we need to make sure that we only consider conversion
2417 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 // break recursion.
2419 if ((AllowExplicit || !Conv->isExplicit()) &&
2420 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2421 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002422 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002423 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002424 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002425 else
John McCalla0296f72010-03-19 07:35:19 +00002426 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002427 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002428 }
2429 }
2430 }
John McCall3696dcb2010-08-17 07:23:57 +00002431 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2432 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002433
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002434 SourceLocation DeclLoc = Initializer->getLocStart();
2435
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002436 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002437 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002438 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002439 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002440 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002441
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002442 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002443
2444 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002445 if (isa<CXXConversionDecl>(Function))
2446 T2 = Function->getResultType();
2447 else
2448 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002449
2450 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002451 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002452 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002453
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002454 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002455 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002456 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002457 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002458 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002459 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002460 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002461
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002462 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002463 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002464 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002465 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002466 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002467 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002468 if (NewRefRelationship == Sema::Ref_Incompatible) {
2469 // If the type we've converted to is not reference-related to the
2470 // type we're looking for, then there is another conversion step
2471 // we need to perform to produce a temporary of the right type
2472 // that we'll be binding to.
2473 ImplicitConversionSequence ICS;
2474 ICS.setStandard();
2475 ICS.Standard = Best->FinalConversion;
2476 T2 = ICS.Standard.getToType(2);
2477 Sequence.AddConversionSequenceStep(ICS, T2);
2478 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002479 Sequence.AddDerivedToBaseCastStep(
2480 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002481 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002482 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002483 else if (NewObjCConversion)
2484 Sequence.AddObjCObjectConversionStep(
2485 S.Context.getQualifiedType(T1,
2486 T2.getNonReferenceType().getQualifiers()));
2487
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002489 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002490
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002491 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2492 return OR_Success;
2493}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002494
2495/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2496static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002497 const InitializedEntity &Entity,
2498 const InitializationKind &Kind,
2499 Expr *Initializer,
2500 InitializationSequence &Sequence) {
2501 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002502
Douglas Gregor1b303932009-12-22 15:35:07 +00002503 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002504 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002505 Qualifiers T1Quals;
2506 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002507 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002508 Qualifiers T2Quals;
2509 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002510 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002511
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002512 // If the initializer is the address of an overloaded function, try
2513 // to resolve the overloaded function. If all goes well, T2 is the
2514 // type of the resulting function.
2515 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002516 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002517 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002518 T1,
2519 false,
2520 Found)) {
2521 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2522 cv2T2 = Fn->getType();
2523 T2 = cv2T2.getUnqualifiedType();
2524 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002525 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2526 return;
2527 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002528 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002529
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002530 // Compute some basic properties of the types and the initializer.
2531 bool isLValueRef = DestType->isLValueReferenceType();
2532 bool isRValueRef = !isLValueRef;
2533 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002534 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002535 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002536 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002537 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2538 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002539
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002540 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002541 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002542 // "cv2 T2" as follows:
2543 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002545 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002546 // Note the analogous bullet points for rvlaue refs to functions. Because
2547 // there are no function rvalues in C++, rvalue refs to functions are treated
2548 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002549 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002550 bool T1Function = T1->isFunctionType();
2551 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002553 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002554 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002555 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002557 // reference-compatible with "cv2 T2," or
2558 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002559 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002560 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002561 // can occur. However, we do pay attention to whether it is a bit-field
2562 // to decide whether we're actually binding to a temporary created from
2563 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002564 if (DerivedToBase)
2565 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002566 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002567 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002568 else if (ObjCConversion)
2569 Sequence.AddObjCObjectConversionStep(
2570 S.Context.getQualifiedType(T1, T2Quals));
2571
Chandler Carruth04bdce62010-01-12 20:32:25 +00002572 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002573 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002574 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002575 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002576 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002577 return;
2578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002579
2580 // - has a class type (i.e., T2 is a class type), where T1 is not
2581 // reference-related to T2, and can be implicitly converted to an
2582 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2583 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002584 // applicable conversion functions (13.3.1.6) and choosing the best
2585 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002586 // If we have an rvalue ref to function type here, the rhs must be
2587 // an rvalue.
2588 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2589 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002590 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002591 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002592 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002593 Sequence);
2594 if (ConvOvlResult == OR_Success)
2595 return;
John McCall0d1da222010-01-12 00:44:57 +00002596 if (ConvOvlResult != OR_No_Viable_Function) {
2597 Sequence.SetOverloadFailure(
2598 InitializationSequence::FK_ReferenceInitOverloadFailed,
2599 ConvOvlResult);
2600 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002601 }
2602 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002603
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002604 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002605 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002606 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002607 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002608 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2609 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2610 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002611 Sequence.SetOverloadFailure(
2612 InitializationSequence::FK_ReferenceInitOverloadFailed,
2613 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002614 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002615 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002616 ? (RefRelationship == Sema::Ref_Related
2617 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2618 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2619 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002621 return;
2622 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002623
Douglas Gregor92e460e2011-01-20 16:44:54 +00002624 // - If the initializer expression
2625 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2626 // "cv1 T1" is reference-compatible with "cv2 T2"
2627 // Note: functions are handled below.
2628 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002629 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002630 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002631 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002632 (InitCategory.isXValue() ||
2633 (InitCategory.isPRValue() && T2->isRecordType()) ||
2634 (InitCategory.isPRValue() && T2->isArrayType()))) {
2635 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2636 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002637 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2638 // compiler the freedom to perform a copy here or bind to the
2639 // object, while C++0x requires that we bind directly to the
2640 // object. Hence, we always bind to the object without making an
2641 // extra copy. However, in C++03 requires that we check for the
2642 // presence of a suitable copy constructor:
2643 //
2644 // The constructor that would be used to make the copy shall
2645 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002646 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002647 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002648 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649
Douglas Gregor92e460e2011-01-20 16:44:54 +00002650 if (DerivedToBase)
2651 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2652 ValueKind);
2653 else if (ObjCConversion)
2654 Sequence.AddObjCObjectConversionStep(
2655 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656
Douglas Gregor92e460e2011-01-20 16:44:54 +00002657 if (T1Quals != T2Quals)
2658 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002659 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002660 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002663
2664 // - has a class type (i.e., T2 is a class type), where T1 is not
2665 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002666 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2667 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002668 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002669 if (RefRelationship == Sema::Ref_Incompatible) {
2670 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2671 Kind, Initializer,
2672 /*AllowRValues=*/true,
2673 Sequence);
2674 if (ConvOvlResult)
2675 Sequence.SetOverloadFailure(
2676 InitializationSequence::FK_ReferenceInitOverloadFailed,
2677 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002678
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002679 return;
2680 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002681
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2683 return;
2684 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002685
2686 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002687 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002688 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002689 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002690
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002691 // Determine whether we are allowed to call explicit constructors or
2692 // explicit conversion operators.
2693 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002694
2695 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2696
2697 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2698 /*SuppressUserConversions*/ false,
2699 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002700 /*FIXME:InOverloadResolution=*/false,
2701 /*CStyle=*/Kind.isCStyleOrFunctionalCast())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002702 // FIXME: Use the conversion function set stored in ICS to turn
2703 // this into an overloading ambiguity diagnostic. However, we need
2704 // to keep that set as an OverloadCandidateSet rather than as some
2705 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002706 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2707 Sequence.SetOverloadFailure(
2708 InitializationSequence::FK_ReferenceInitOverloadFailed,
2709 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002710 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2711 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002712 else
2713 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002714 return;
2715 }
2716
2717 // [...] If T1 is reference-related to T2, cv1 must be the
2718 // same cv-qualification as, or greater cv-qualification
2719 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002720 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2721 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002722 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002723 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002724 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2725 return;
2726 }
2727
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002728 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002729 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002730 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002731 InitCategory.isLValue()) {
2732 Sequence.SetFailed(
2733 InitializationSequence::FK_RValueReferenceBindingToLValue);
2734 return;
2735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002736
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002737 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2738 return;
2739}
2740
2741/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002742/// (C++ [dcl.init.string], C99 6.7.8).
2743static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002744 const InitializedEntity &Entity,
2745 const InitializationKind &Kind,
2746 Expr *Initializer,
2747 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002748 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002749 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002750}
2751
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002752/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2753/// enumerates the constructors of the initialized entity and performs overload
2754/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002755static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002756 const InitializedEntity &Entity,
2757 const InitializationKind &Kind,
2758 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002759 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002760 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002761 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002762
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002763 // Build the candidate set directly in the initialization sequence
2764 // structure, so that it will persist if we fail.
2765 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2766 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002768 // Determine whether we are allowed to call explicit constructors or
2769 // explicit conversion operators.
2770 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2771 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002772 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002773
2774 // The type we're constructing needs to be complete.
2775 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002776 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002777 return;
2778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002779
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002780 // The type we're converting to is a class type. Enumerate its constructors
2781 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002782 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002783 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002784 CXXRecordDecl *DestRecordDecl
2785 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002786
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002787 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002788 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002789 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002790 NamedDecl *D = *Con;
2791 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002792 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002793
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002794 // Find the constructor (which may be a template).
2795 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002796 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002797 if (ConstructorTmpl)
2798 Constructor = cast<CXXConstructorDecl>(
2799 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002800 else {
John McCalla0296f72010-03-19 07:35:19 +00002801 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002802
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00002804 // suppress user-defined conversions on the arguments.
2805 // FIXME: Move constructors?
2806 if (Kind.getKind() == InitializationKind::IK_Copy &&
2807 Constructor->isCopyConstructor())
2808 SuppressUserConversions = true;
2809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002810
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002811 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002812 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002813 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002814 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002815 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002816 Args, NumArgs, CandidateSet,
2817 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002818 else
John McCalla0296f72010-03-19 07:35:19 +00002819 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002820 Args, NumArgs, CandidateSet,
2821 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002823 }
2824
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002825 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826
2827 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002828 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002830 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002831 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002832 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002833 Result);
2834 return;
2835 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002836
2837 // C++0x [dcl.init]p6:
2838 // If a program calls for the default initialization of an object
2839 // of a const-qualified type T, T shall be a class type with a
2840 // user-provided default constructor.
2841 if (Kind.getKind() == InitializationKind::IK_Default &&
2842 Entity.getType().isConstQualified() &&
2843 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2844 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2845 return;
2846 }
2847
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002848 // Add the constructor initialization step. Any cv-qualification conversion is
2849 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002850 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002851 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002852 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002853 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002854}
2855
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002856/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002858 const InitializedEntity &Entity,
2859 const InitializationKind &Kind,
2860 InitializationSequence &Sequence) {
2861 // C++ [dcl.init]p5:
2862 //
2863 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002864 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002865
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002866 // -- if T is an array type, then each element is value-initialized;
2867 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2868 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002869
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002870 if (const RecordType *RT = T->getAs<RecordType>()) {
2871 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2872 // -- if T is a class type (clause 9) with a user-declared
2873 // constructor (12.1), then the default constructor for T is
2874 // called (and the initialization is ill-formed if T has no
2875 // accessible default constructor);
2876 //
2877 // FIXME: we really want to refer to a single subobject of the array,
2878 // but Entity doesn't have a way to capture that (yet).
2879 if (ClassDecl->hasUserDeclaredConstructor())
2880 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002881
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002882 // -- if T is a (possibly cv-qualified) non-union class type
2883 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002884 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002885 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002886 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002887 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002888 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002889 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002890 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002891 }
2892 }
2893
Douglas Gregor1b303932009-12-22 15:35:07 +00002894 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002895 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2896}
2897
Douglas Gregor85dabae2009-12-16 01:38:02 +00002898/// \brief Attempt default initialization (C++ [dcl.init]p6).
2899static void TryDefaultInitialization(Sema &S,
2900 const InitializedEntity &Entity,
2901 const InitializationKind &Kind,
2902 InitializationSequence &Sequence) {
2903 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002904
Douglas Gregor85dabae2009-12-16 01:38:02 +00002905 // C++ [dcl.init]p6:
2906 // To default-initialize an object of type T means:
2907 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002908 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002909 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2910 DestType = Array->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911
Douglas Gregor85dabae2009-12-16 01:38:02 +00002912 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2913 // constructor for T is called (and the initialization is ill-formed if
2914 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002915 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002916 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2917 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919
Douglas Gregor85dabae2009-12-16 01:38:02 +00002920 // - otherwise, no initialization is performed.
2921 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002922
Douglas Gregor85dabae2009-12-16 01:38:02 +00002923 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002924 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00002925 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002926 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002927 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2928}
2929
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002930/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2931/// which enumerates all conversion functions and performs overload resolution
2932/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002933static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002934 const InitializedEntity &Entity,
2935 const InitializationKind &Kind,
2936 Expr *Initializer,
2937 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002938 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939
Douglas Gregor1b303932009-12-22 15:35:07 +00002940 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002941 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2942 QualType SourceType = Initializer->getType();
2943 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2944 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945
Douglas Gregor540c3b02009-12-14 17:27:33 +00002946 // Build the candidate set directly in the initialization sequence
2947 // structure, so that it will persist if we fail.
2948 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2949 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950
Douglas Gregor540c3b02009-12-14 17:27:33 +00002951 // Determine whether we are allowed to call explicit constructors or
2952 // explicit conversion operators.
2953 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954
Douglas Gregor540c3b02009-12-14 17:27:33 +00002955 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2956 // The type we're converting to is a class type. Enumerate its constructors
2957 // to see if there is a suitable conversion.
2958 CXXRecordDecl *DestRecordDecl
2959 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002960
Douglas Gregord9848152010-04-26 14:36:57 +00002961 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002962 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002963 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002964 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002965 Con != ConEnd; ++Con) {
2966 NamedDecl *D = *Con;
2967 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002968
Douglas Gregord9848152010-04-26 14:36:57 +00002969 // Find the constructor (which may be a template).
2970 CXXConstructorDecl *Constructor = 0;
2971 FunctionTemplateDecl *ConstructorTmpl
2972 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002973 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002974 Constructor = cast<CXXConstructorDecl>(
2975 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002976 else
Douglas Gregord9848152010-04-26 14:36:57 +00002977 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978
Douglas Gregord9848152010-04-26 14:36:57 +00002979 if (!Constructor->isInvalidDecl() &&
2980 Constructor->isConvertingConstructor(AllowExplicit)) {
2981 if (ConstructorTmpl)
2982 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2983 /*ExplicitArgs*/ 0,
2984 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002985 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002986 else
2987 S.AddOverloadCandidate(Constructor, FoundDecl,
2988 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002989 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002990 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002991 }
Douglas Gregord9848152010-04-26 14:36:57 +00002992 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002993 }
Eli Friedman78275202009-12-19 08:11:05 +00002994
2995 SourceLocation DeclLoc = Initializer->getLocStart();
2996
Douglas Gregor540c3b02009-12-14 17:27:33 +00002997 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2998 // The type we're converting from is a class type, enumerate its conversion
2999 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003000
Eli Friedman4afe9a32009-12-20 22:12:03 +00003001 // We can only enumerate the conversion functions for a complete type; if
3002 // the type isn't complete, simply skip this step.
3003 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3004 CXXRecordDecl *SourceRecordDecl
3005 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003006
John McCallad371252010-01-20 00:46:10 +00003007 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003008 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003009 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003010 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003011 I != E; ++I) {
3012 NamedDecl *D = *I;
3013 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3014 if (isa<UsingShadowDecl>(D))
3015 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003016
Eli Friedman4afe9a32009-12-20 22:12:03 +00003017 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3018 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003019 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003020 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003021 else
John McCallda4458e2010-03-31 01:36:47 +00003022 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023
Eli Friedman4afe9a32009-12-20 22:12:03 +00003024 if (AllowExplicit || !Conv->isExplicit()) {
3025 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003026 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003027 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003028 CandidateSet);
3029 else
John McCalla0296f72010-03-19 07:35:19 +00003030 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003031 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003032 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003033 }
3034 }
3035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036
3037 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003038 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003039 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003040 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003041 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003042 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003043 Result);
3044 return;
3045 }
John McCall0d1da222010-01-12 00:44:57 +00003046
Douglas Gregor540c3b02009-12-14 17:27:33 +00003047 FunctionDecl *Function = Best->Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
Douglas Gregor540c3b02009-12-14 17:27:33 +00003049 if (isa<CXXConstructorDecl>(Function)) {
3050 // Add the user-defined conversion step. Any cv-qualification conversion is
3051 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003052 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003053 return;
3054 }
3055
3056 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003057 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003058 if (ConvType->getAs<RecordType>()) {
3059 // If we're converting to a class type, there may be an copy if
3060 // the resulting temporary object (possible to create an object of
3061 // a base class type). That copy is not a separate conversion, so
3062 // we just make a note of the actual destination type (possibly a
3063 // base class of the type returned by the conversion function) and
3064 // let the user-defined conversion step handle the conversion.
3065 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3066 return;
3067 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003068
Douglas Gregor5ab11652010-04-17 22:01:05 +00003069 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003070
Douglas Gregor5ab11652010-04-17 22:01:05 +00003071 // If the conversion following the call to the conversion function
3072 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003073 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3074 Best->FinalConversion.Third) {
3075 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003076 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003077 ICS.Standard = Best->FinalConversion;
3078 Sequence.AddConversionSequenceStep(ICS, DestType);
3079 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003080}
3081
Douglas Gregore2f943b2011-02-22 18:29:51 +00003082/// \brief Determine whether we have compatible array types for the
3083/// purposes of GNU by-copy array initialization.
3084static bool hasCompatibleArrayTypes(ASTContext &Context,
3085 const ArrayType *Dest,
3086 const ArrayType *Source) {
3087 // If the source and destination array types are equivalent, we're
3088 // done.
3089 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3090 return true;
3091
3092 // Make sure that the element types are the same.
3093 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3094 return false;
3095
3096 // The only mismatch we allow is when the destination is an
3097 // incomplete array type and the source is a constant array type.
3098 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3099}
3100
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003101InitializationSequence::InitializationSequence(Sema &S,
3102 const InitializedEntity &Entity,
3103 const InitializationKind &Kind,
3104 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003105 unsigned NumArgs)
3106 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003107 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003108
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003109 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003110 // The semantics of initializers are as follows. The destination type is
3111 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003112 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003113 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003114 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003115 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003116
3117 if (DestType->isDependentType() ||
3118 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3119 SequenceKind = DependentSequence;
3120 return;
3121 }
3122
John McCalled75c092010-12-07 22:54:16 +00003123 for (unsigned I = 0; I != NumArgs; ++I)
3124 if (Args[I]->getObjectKind() == OK_ObjCProperty)
3125 S.ConvertPropertyForRValue(Args[I]);
3126
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003127 QualType SourceType;
3128 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003129 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003130 Initializer = Args[0];
3131 if (!isa<InitListExpr>(Initializer))
3132 SourceType = Initializer->getType();
3133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134
3135 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003136 // list-initialized (8.5.4).
3137 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3138 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003139 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003140 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003141
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003142 // - If the destination type is a reference type, see 8.5.3.
3143 if (DestType->isReferenceType()) {
3144 // C++0x [dcl.init.ref]p1:
3145 // A variable declared to be a T& or T&&, that is, "reference to type T"
3146 // (8.3.2), shall be initialized by an object, or function, of type T or
3147 // by an object that can be converted into a T.
3148 // (Therefore, multiple arguments are not permitted.)
3149 if (NumArgs != 1)
3150 SetFailed(FK_TooManyInitsForReference);
3151 else
3152 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3153 return;
3154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003156 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003157 if (Kind.getKind() == InitializationKind::IK_Value ||
3158 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003159 TryValueInitialization(S, Entity, Kind, *this);
3160 return;
3161 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003162
Douglas Gregor85dabae2009-12-16 01:38:02 +00003163 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003164 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003165 TryDefaultInitialization(S, Entity, Kind, *this);
3166 return;
3167 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003168
John McCall66884dd2011-02-21 07:22:22 +00003169 // - If the destination type is an array of characters, an array of
3170 // char16_t, an array of char32_t, or an array of wchar_t, and the
3171 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003173 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003174 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3175 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCall66884dd2011-02-21 07:22:22 +00003176 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3177 return;
3178 }
3179
Douglas Gregore2f943b2011-02-22 18:29:51 +00003180 // Note: as an GNU C extension, we allow initialization of an
3181 // array from a compound literal that creates an array of the same
3182 // type, so long as the initializer has no side effects.
3183 if (!S.getLangOptions().CPlusPlus && Initializer &&
3184 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3185 Initializer->getType()->isArrayType()) {
3186 const ArrayType *SourceAT
3187 = Context.getAsArrayType(Initializer->getType());
3188 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3189 SetFailed(FK_ArrayTypeMismatch);
3190 else if (Initializer->HasSideEffects(S.Context))
3191 SetFailed(FK_NonConstantArrayInit);
3192 else {
3193 setSequenceKind(ArrayInit);
3194 AddArrayInitStep(DestType);
3195 }
3196 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003197 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3198 else
3199 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003201 return;
3202 }
Eli Friedman78275202009-12-19 08:11:05 +00003203
3204 // Handle initialization in C
3205 if (!S.getLangOptions().CPlusPlus) {
3206 setSequenceKind(CAssignment);
3207 AddCAssignmentStep(DestType);
3208 return;
3209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003211 // - If the destination type is a (possibly cv-qualified) class type:
3212 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213 // - If the initialization is direct-initialization, or if it is
3214 // copy-initialization where the cv-unqualified version of the
3215 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003216 // class of the destination, constructors are considered. [...]
3217 if (Kind.getKind() == InitializationKind::IK_Direct ||
3218 (Kind.getKind() == InitializationKind::IK_Copy &&
3219 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3220 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003222 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003223 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003224 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 // used) to a derived class thereof are enumerated as described in
3227 // 13.3.1.4, and the best one is chosen through overload resolution
3228 // (13.3).
3229 else
3230 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3231 return;
3232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233
Douglas Gregor85dabae2009-12-16 01:38:02 +00003234 if (NumArgs > 1) {
3235 SetFailed(FK_TooManyInitsForScalar);
3236 return;
3237 }
3238 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239
3240 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003241 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003242 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3244 return;
3245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003247 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003248 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003249 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003251 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003252 if (S.TryImplicitConversion(*this, Entity, Initializer,
3253 /*SuppressUserConversions*/ true,
3254 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003255 /*InOverloadResolution*/ false,
3256 /*CStyle=*/Kind.isCStyleOrFunctionalCast()))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003257 {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003258 DeclAccessPair dap;
3259 if (Initializer->getType() == Context.OverloadTy &&
3260 !S.ResolveAddressOfOverloadedFunction(Initializer
3261 , DestType, false, dap))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003262 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3263 else
3264 SetFailed(InitializationSequence::FK_ConversionFailed);
3265 }
John McCallec6f4e92010-06-04 02:29:22 +00003266 else
3267 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003268}
3269
3270InitializationSequence::~InitializationSequence() {
3271 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3272 StepEnd = Steps.end();
3273 Step != StepEnd; ++Step)
3274 Step->Destroy();
3275}
3276
3277//===----------------------------------------------------------------------===//
3278// Perform initialization
3279//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003281getAssignmentAction(const InitializedEntity &Entity) {
3282 switch(Entity.getKind()) {
3283 case InitializedEntity::EK_Variable:
3284 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003285 case InitializedEntity::EK_Exception:
3286 case InitializedEntity::EK_Base:
Douglas Gregore1314a62009-12-18 05:02:21 +00003287 return Sema::AA_Initializing;
3288
3289 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003291 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3292 return Sema::AA_Sending;
3293
Douglas Gregore1314a62009-12-18 05:02:21 +00003294 return Sema::AA_Passing;
3295
3296 case InitializedEntity::EK_Result:
3297 return Sema::AA_Returning;
3298
Douglas Gregore1314a62009-12-18 05:02:21 +00003299 case InitializedEntity::EK_Temporary:
3300 // FIXME: Can we tell apart casting vs. converting?
3301 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003302
Douglas Gregore1314a62009-12-18 05:02:21 +00003303 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003304 case InitializedEntity::EK_ArrayElement:
3305 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003306 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003307 return Sema::AA_Initializing;
3308 }
3309
3310 return Sema::AA_Converting;
3311}
3312
Douglas Gregor95562572010-04-24 23:45:46 +00003313/// \brief Whether we should binding a created object as a temporary when
3314/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003315static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003316 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003317 case InitializedEntity::EK_ArrayElement:
3318 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003319 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003320 case InitializedEntity::EK_New:
3321 case InitializedEntity::EK_Variable:
3322 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003323 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003324 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003325 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003326 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327
Douglas Gregore1314a62009-12-18 05:02:21 +00003328 case InitializedEntity::EK_Parameter:
3329 case InitializedEntity::EK_Temporary:
3330 return true;
3331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332
Douglas Gregore1314a62009-12-18 05:02:21 +00003333 llvm_unreachable("missed an InitializedEntity kind?");
3334}
3335
Douglas Gregor95562572010-04-24 23:45:46 +00003336/// \brief Whether the given entity, when initialized with an object
3337/// created for that initialization, requires destruction.
3338static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3339 switch (Entity.getKind()) {
3340 case InitializedEntity::EK_Member:
3341 case InitializedEntity::EK_Result:
3342 case InitializedEntity::EK_New:
3343 case InitializedEntity::EK_Base:
3344 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003345 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003346 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003347
Douglas Gregor95562572010-04-24 23:45:46 +00003348 case InitializedEntity::EK_Variable:
3349 case InitializedEntity::EK_Parameter:
3350 case InitializedEntity::EK_Temporary:
3351 case InitializedEntity::EK_ArrayElement:
3352 case InitializedEntity::EK_Exception:
3353 return true;
3354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355
3356 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003357}
3358
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003359/// \brief Make a (potentially elidable) temporary copy of the object
3360/// provided by the given initializer by calling the appropriate copy
3361/// constructor.
3362///
3363/// \param S The Sema object used for type-checking.
3364///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003365/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003366/// the type of the initializer expression or a superclass thereof.
3367///
3368/// \param Enter The entity being initialized.
3369///
3370/// \param CurInit The initializer expression.
3371///
3372/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3373/// is permitted in C++03 (but not C++0x) when binding a reference to
3374/// an rvalue.
3375///
3376/// \returns An expression that copies the initializer expression into
3377/// a temporary object, or an error expression if a copy could not be
3378/// created.
John McCalldadc5752010-08-24 06:29:42 +00003379static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003380 QualType T,
3381 const InitializedEntity &Entity,
3382 ExprResult CurInit,
3383 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003384 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003385 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003387 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003388 Class = cast<CXXRecordDecl>(Record->getDecl());
3389 if (!Class)
3390 return move(CurInit);
3391
Douglas Gregor5d369002011-01-21 18:05:27 +00003392 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003393 // When certain criteria are met, an implementation is allowed to
3394 // omit the copy/move construction of a class object, even if the
3395 // copy/move constructor and/or destructor for the object have
3396 // side effects. [...]
3397 // - when a temporary class object that has not been bound to a
3398 // reference (12.2) would be copied/moved to a class object
3399 // with the same cv-unqualified type, the copy/move operation
3400 // can be omitted by constructing the temporary object
3401 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003403 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003404 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003406 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003407 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003408 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003409 switch (Entity.getKind()) {
3410 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003411 Loc = Entity.getReturnLoc();
3412 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
Douglas Gregore1314a62009-12-18 05:02:21 +00003414 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003415 Loc = Entity.getThrowLoc();
3416 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417
Douglas Gregore1314a62009-12-18 05:02:21 +00003418 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003419 Loc = Entity.getDecl()->getLocation();
3420 break;
3421
Anders Carlsson0bd52402010-01-24 00:19:41 +00003422 case InitializedEntity::EK_ArrayElement:
3423 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003424 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003425 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003426 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003427 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003428 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003429 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003430 Loc = CurInitExpr->getLocStart();
3431 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003432 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003433
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003435 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3436 return move(CurInit);
3437
Douglas Gregorf282a762011-01-21 19:38:21 +00003438 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003439 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003440 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003441 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003442 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003443 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003444 // C++0x [dcl.init]p16, second bullet to class types, this
3445 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003446 CXXConstructorDecl *Constructor = 0;
3447
3448 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003449 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003450 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003451 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003452 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003453 continue;
3454
3455 DeclAccessPair FoundDecl
3456 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3457 S.AddOverloadCandidate(Constructor, FoundDecl,
3458 &CurInitExpr, 1, CandidateSet);
3459 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003461
3462 // Handle constructor templates.
3463 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3464 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003465 continue;
John McCalla0296f72010-03-19 07:35:19 +00003466
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003467 Constructor = cast<CXXConstructorDecl>(
3468 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003469 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003470 continue;
3471
3472 // FIXME: Do we need to limit this to copy-constructor-like
3473 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003474 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003475 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3476 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3477 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003479
Douglas Gregore1314a62009-12-18 05:02:21 +00003480 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00003481 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003482 case OR_Success:
3483 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484
Douglas Gregore1314a62009-12-18 05:02:21 +00003485 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003486 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3487 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3488 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003489 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003490 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003491 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003492 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003493 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003494 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495
Douglas Gregore1314a62009-12-18 05:02:21 +00003496 case OR_Ambiguous:
3497 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003498 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003499 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003500 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003501 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregore1314a62009-12-18 05:02:21 +00003503 case OR_Deleted:
3504 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003505 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003506 << CurInitExpr->getSourceRange();
3507 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3508 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003509 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003510 }
3511
Douglas Gregor5ab11652010-04-17 22:01:05 +00003512 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003513 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003514 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003515
Anders Carlssona01874b2010-04-21 18:47:17 +00003516 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003517 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003518
3519 if (IsExtraneousCopy) {
3520 // If this is a totally extraneous copy for C++03 reference
3521 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003522 // expression. We don't generate an (elided) copy operation here
3523 // because doing so would require us to pass down a flag to avoid
3524 // infinite recursion, where each step adds another extraneous,
3525 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003526
Douglas Gregor30b52772010-04-18 07:57:34 +00003527 // Instantiate the default arguments of any extra parameters in
3528 // the selected copy constructor, as if we were going to create a
3529 // proper call to the copy constructor.
3530 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3531 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3532 if (S.RequireCompleteType(Loc, Parm->getType(),
3533 S.PDiag(diag::err_call_incomplete_argument)))
3534 break;
3535
3536 // Build the default argument expression; we don't actually care
3537 // if this succeeds or not, because this routine will complain
3538 // if there was a problem.
3539 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3540 }
3541
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003542 return S.Owned(CurInitExpr);
3543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544
Douglas Gregor5ab11652010-04-17 22:01:05 +00003545 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003546 // constructor call (we might have derived-to-base conversions, or
3547 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003548 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003549 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003550 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003551
Douglas Gregord0ace022010-04-25 00:55:24 +00003552 // Actually perform the constructor call.
3553 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003554 move_arg(ConstructorArgs),
3555 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003556 CXXConstructExpr::CK_Complete,
3557 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Douglas Gregord0ace022010-04-25 00:55:24 +00003559 // If we're supposed to bind temporaries, do so.
3560 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3561 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3562 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003563}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003564
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003565void InitializationSequence::PrintInitLocationNote(Sema &S,
3566 const InitializedEntity &Entity) {
3567 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3568 if (Entity.getDecl()->getLocation().isInvalid())
3569 return;
3570
3571 if (Entity.getDecl()->getDeclName())
3572 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3573 << Entity.getDecl()->getDeclName();
3574 else
3575 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3576 }
3577}
3578
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003580InitializationSequence::Perform(Sema &S,
3581 const InitializedEntity &Entity,
3582 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003583 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003584 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003585 if (SequenceKind == FailedSequence) {
3586 unsigned NumArgs = Args.size();
3587 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003588 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003591 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003592 // If the declaration is a non-dependent, incomplete array type
3593 // that has an initializer, then its type will be completed once
3594 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003595 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003596 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003597 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003598 if (const IncompleteArrayType *ArrayT
3599 = S.Context.getAsIncompleteArrayType(DeclType)) {
3600 // FIXME: We don't currently have the ability to accurately
3601 // compute the length of an initializer list without
3602 // performing full type-checking of the initializer list
3603 // (since we have to determine where braces are implicitly
3604 // introduced and such). So, we fall back to making the array
3605 // type a dependently-sized array type with no specified
3606 // bound.
3607 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3608 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003609
Douglas Gregor51e77d52009-12-10 17:56:55 +00003610 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003611 if (DeclaratorDecl *DD = Entity.getDecl()) {
3612 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3613 TypeLoc TL = TInfo->getTypeLoc();
3614 if (IncompleteArrayTypeLoc *ArrayLoc
3615 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3616 Brackets = ArrayLoc->getBracketsRange();
3617 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003618 }
3619
3620 *ResultType
3621 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3622 /*NumElts=*/0,
3623 ArrayT->getSizeModifier(),
3624 ArrayT->getIndexTypeCVRQualifiers(),
3625 Brackets);
3626 }
3627
3628 }
3629 }
3630
Eli Friedmana553d4a2009-12-22 02:35:53 +00003631 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003632 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003633
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003634 if (Args.size() == 0)
3635 return S.Owned((Expr *)0);
3636
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003637 unsigned NumArgs = Args.size();
3638 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3639 SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640 (Expr **)Args.release(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003641 NumArgs,
3642 SourceLocation()));
3643 }
3644
Douglas Gregor85dabae2009-12-16 01:38:02 +00003645 if (SequenceKind == NoInitialization)
3646 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647
Douglas Gregor1b303932009-12-22 15:35:07 +00003648 QualType DestType = Entity.getType().getNonReferenceType();
3649 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003650 // the same as Entity.getDecl()->getType() in cases involving type merging,
3651 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003652 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003653 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003654 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003655
John McCalldadc5752010-08-24 06:29:42 +00003656 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657
Douglas Gregor85dabae2009-12-16 01:38:02 +00003658 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659
3660 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00003661 // grab the only argument out the Args and place it into the "current"
3662 // initializer.
3663 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003664 case SK_ResolveAddressOfOverloadedFunction:
3665 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003666 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003667 case SK_CastDerivedToBaseLValue:
3668 case SK_BindReference:
3669 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003670 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003671 case SK_UserConversion:
3672 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003673 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003674 case SK_QualificationConversionRValue:
3675 case SK_ConversionSequence:
3676 case SK_ListInitialization:
3677 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003678 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003679 case SK_ObjCObjectConversion:
3680 case SK_ArrayInit: {
Douglas Gregore1314a62009-12-18 05:02:21 +00003681 assert(Args.size() == 1);
John McCall34376a62010-12-04 03:47:34 +00003682 Expr *CurInitExpr = Args.get()[0];
3683 if (!CurInitExpr) return ExprError();
3684
3685 // Read from a property when initializing something with it.
3686 if (CurInitExpr->getObjectKind() == OK_ObjCProperty)
3687 S.ConvertPropertyForRValue(CurInitExpr);
3688
3689 CurInit = ExprResult(CurInitExpr);
Douglas Gregore1314a62009-12-18 05:02:21 +00003690 break;
John McCall34376a62010-12-04 03:47:34 +00003691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003692
Douglas Gregore1314a62009-12-18 05:02:21 +00003693 case SK_ConstructorInitialization:
3694 case SK_ZeroInitialization:
3695 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697
3698 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003699 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003700 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003701 for (step_iterator Step = step_begin(), StepEnd = step_end();
3702 Step != StepEnd; ++Step) {
3703 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003704 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003705
John McCall34376a62010-12-04 03:47:34 +00003706 Expr *CurInitExpr = CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003707 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003709 switch (Step->Kind) {
3710 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003712 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003713 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003714 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003715 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003716 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003717 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003718 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003720 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003721 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003722 case SK_CastDerivedToBaseLValue: {
3723 // We have a derived-to-base cast that produces either an rvalue or an
3724 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725
John McCallcf142162010-08-07 06:22:56 +00003726 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003727
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003728 // Casts to inaccessible base classes are allowed with C-style casts.
3729 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3730 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3731 CurInitExpr->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732 CurInitExpr->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003733 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003734 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735
Douglas Gregor88d292c2010-05-13 16:44:06 +00003736 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3737 QualType T = SourceType;
3738 if (const PointerType *Pointer = T->getAs<PointerType>())
3739 T = Pointer->getPointeeType();
3740 if (const RecordType *RecordTy = T->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741 S.MarkVTableUsed(CurInitExpr->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003742 cast<CXXRecordDecl>(RecordTy->getDecl()));
3743 }
3744
John McCall2536c6d2010-08-25 10:28:54 +00003745 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003746 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003747 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003748 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003749 VK_XValue :
3750 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003751 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3752 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003753 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003754 CurInit.get(),
3755 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003756 break;
3757 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003759 case SK_BindReference:
3760 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3761 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3762 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003763 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003764 << BitField->getDeclName()
3765 << CurInitExpr->getSourceRange();
3766 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003767 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003768 }
Anders Carlssona91be642010-01-29 02:47:33 +00003769
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003770 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003771 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003772 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3773 << Entity.getType().isVolatileQualified()
3774 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003775 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003776 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003779 // Reference binding does not have any corresponding ASTs.
3780
3781 // Check exception specifications
3782 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003783 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003784
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003785 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003786
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003787 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003788 // Reference binding does not have any corresponding ASTs.
3789
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003790 // Check exception specifications
3791 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003792 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003793
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003796 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003798 /*IsExtraneousCopy=*/true);
3799 break;
3800
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003801 case SK_UserConversion: {
3802 // We have a user-defined conversion that invokes either a constructor
3803 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00003804 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00003805 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003806 FunctionDecl *Fn = Step->Function.Function;
3807 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003808 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003809 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003810 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003811 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003812 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003813 SourceLocation Loc = CurInitExpr->getLocStart();
3814 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003815
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003816 // Determine the arguments required to actually perform the constructor
3817 // call.
3818 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00003819 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003820 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003821 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003823 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003825 move_arg(ConstructorArgs),
3826 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003827 CXXConstructExpr::CK_Complete,
3828 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003829 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003830 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003831
Anders Carlssona01874b2010-04-21 18:47:17 +00003832 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003833 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003834 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835
John McCalle3027922010-08-25 11:45:40 +00003836 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003837 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3838 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3839 S.IsDerivedFrom(SourceType, Class))
3840 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003841
Douglas Gregor95562572010-04-24 23:45:46 +00003842 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003843 } else {
3844 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003845 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003846 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003847 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003848 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003849 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850
3851 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003852 // derived-to-base conversion? I believe the answer is "no", because
3853 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003854 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003855 FoundFn, Conversion))
John McCallfaf5fb42010-08-26 23:41:50 +00003856 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003857
3858 // Do a little dance to make sure that CurInit has the proper
3859 // pointer.
3860 CurInit.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003862 // Build the actual call to the conversion function.
Douglas Gregor668443e2011-01-20 00:18:04 +00003863 CurInit = S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003864 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003865 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003866
John McCalle3027922010-08-25 11:45:40 +00003867 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003868
Douglas Gregor95562572010-04-24 23:45:46 +00003869 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003870 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871
3872 bool RequiresCopy = !IsCopy &&
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003873 getKind() != InitializationSequence::ReferenceBinding;
3874 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003875 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003876 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3877 CurInitExpr = static_cast<Expr *>(CurInit.get());
3878 QualType T = CurInitExpr->getType();
3879 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00003881 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00003883 S.PDiag(diag::err_access_dtor_temp) << T);
3884 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003885 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00003886 }
3887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003888
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003889 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003890 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003891 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3892 CurInitExpr->getType(),
3893 CastKind, CurInitExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00003894 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003896 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003897 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3898 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003899
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900 break;
3901 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003902
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003903 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003904 case SK_QualificationConversionXValue:
3905 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003906 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003907 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003908 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003909 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003910 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003911 VK_XValue :
3912 VK_RValue);
John McCalle3027922010-08-25 11:45:40 +00003913 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003914 CurInit.release();
3915 CurInit = S.Owned(CurInitExpr);
3916 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003917 }
3918
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003919 case SK_ConversionSequence: {
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003920 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003921 getAssignmentAction(Entity),
Douglas Gregor58281352011-01-27 00:58:17 +00003922 Kind.isCStyleOrFunctionalCast()))
John McCallfaf5fb42010-08-26 23:41:50 +00003923 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003925 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003926 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003927 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929
Douglas Gregor51e77d52009-12-10 17:56:55 +00003930 case SK_ListInitialization: {
3931 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3932 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003933 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003934 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003935
3936 CurInit.release();
3937 CurInit = S.Owned(InitList);
3938 break;
3939 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003940
3941 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003942 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003943 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003944 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003945
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003946 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003947 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003948 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3949 ? Kind.getEqualLoc()
3950 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003951
3952 if (Kind.getKind() == InitializationKind::IK_Default) {
3953 // Force even a trivial, implicit default constructor to be
3954 // semantically checked. We do this explicitly because we don't build
3955 // the definition for completely trivial constructors.
3956 CXXRecordDecl *ClassDecl = Constructor->getParent();
3957 assert(ClassDecl && "No parent class for constructor.");
3958 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3959 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3960 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3961 }
3962
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003963 // Determine the arguments required to actually perform the constructor
3964 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003966 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003967 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968
3969
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003970 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003971 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003972 (Kind.getKind() == InitializationKind::IK_Direct ||
3973 Kind.getKind() == InitializationKind::IK_Value)) {
3974 // An explicitly-constructed temporary, e.g., X(1, 2).
3975 unsigned NumExprs = ConstructorArgs.size();
3976 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003977 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003978 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003979
Douglas Gregor2b88c112010-09-08 00:15:04 +00003980 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3981 if (!TSInfo)
3982 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003984 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3985 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00003986 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003987 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003988 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00003989 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00003990 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003991 } else {
3992 CXXConstructExpr::ConstructionKind ConstructKind =
3993 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003994
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003995 if (Entity.getKind() == InitializedEntity::EK_Base) {
3996 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003998 CXXConstructExpr::CK_NonVirtualBase;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999 }
4000
Chandler Carruth01718152010-10-25 08:47:36 +00004001 // Only get the parenthesis range if it is a direct construction.
4002 SourceRange parenRange =
4003 Kind.getKind() == InitializationKind::IK_Direct ?
4004 Kind.getParenRange() : SourceRange();
4005
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004006 // If the entity allows NRVO, mark the construction as elidable
4007 // unconditionally.
4008 if (Entity.allowsNRVO())
4009 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4010 Constructor, /*Elidable=*/true,
4011 move_arg(ConstructorArgs),
4012 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004013 ConstructKind,
4014 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004015 else
4016 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004018 move_arg(ConstructorArgs),
4019 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004020 ConstructKind,
4021 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004022 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004023 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004024 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004025
4026 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004027 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004028 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004029 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004031 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004032 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004034 break;
4035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004036
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004037 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004038 step_iterator NextStep = Step;
4039 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004041 NextStep->Kind == SK_ConstructorInitialization) {
4042 // The need for zero-initialization is recorded directly into
4043 // the call to the object's constructor within the next step.
4044 ConstructorInitRequiresZeroInit = true;
4045 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4046 S.getLangOptions().CPlusPlus &&
4047 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004048 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4049 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004051 Kind.getRange().getBegin());
4052
4053 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4054 TSInfo->getType().getNonLValueExprType(S.Context),
4055 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004056 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004057 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004058 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004059 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004060 break;
4061 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004062
4063 case SK_CAssignment: {
4064 QualType SourceType = CurInitExpr->getType();
4065 Sema::AssignConvertType ConvTy =
4066 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00004067
4068 // If this is a call, allow conversion to a transparent union.
4069 if (ConvTy != Sema::Compatible &&
4070 Entity.getKind() == InitializedEntity::EK_Parameter &&
4071 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4072 == Sema::Compatible)
4073 ConvTy = Sema::Compatible;
4074
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004075 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004076 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4077 Step->Type, SourceType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004078 CurInitExpr,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004079 getAssignmentAction(Entity),
4080 &Complained)) {
4081 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004082 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004083 } else if (Complained)
4084 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004085
4086 CurInit.release();
4087 CurInit = S.Owned(CurInitExpr);
4088 break;
4089 }
Eli Friedman78275202009-12-19 08:11:05 +00004090
4091 case SK_StringInit: {
4092 QualType Ty = Step->Type;
John McCall5decec92011-02-21 07:57:55 +00004093 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty,
4094 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004095 break;
4096 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004097
4098 case SK_ObjCObjectConversion:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004099 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004100 CK_ObjCObjectLValueCast,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004101 S.CastCategory(CurInitExpr));
4102 CurInit.release();
4103 CurInit = S.Owned(CurInitExpr);
4104 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004105
4106 case SK_ArrayInit:
4107 // Okay: we checked everything before creating this step. Note that
4108 // this is a GNU extension.
4109 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
4110 << Step->Type << CurInitExpr->getType()
4111 << CurInitExpr->getSourceRange();
4112
4113 // If the destination type is an incomplete array type, update the
4114 // type accordingly.
4115 if (ResultType) {
4116 if (const IncompleteArrayType *IncompleteDest
4117 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4118 if (const ConstantArrayType *ConstantSource
4119 = S.Context.getAsConstantArrayType(CurInitExpr->getType())) {
4120 *ResultType = S.Context.getConstantArrayType(
4121 IncompleteDest->getElementType(),
4122 ConstantSource->getSize(),
4123 ArrayType::Normal, 0);
4124 }
4125 }
4126 }
4127
4128 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004129 }
4130 }
John McCall1f425642010-11-11 03:21:53 +00004131
4132 // Diagnose non-fatal problems with the completed initialization.
4133 if (Entity.getKind() == InitializedEntity::EK_Member &&
4134 cast<FieldDecl>(Entity.getDecl())->isBitField())
4135 S.CheckBitFieldInitialization(Kind.getLocation(),
4136 cast<FieldDecl>(Entity.getDecl()),
4137 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004139 return move(CurInit);
4140}
4141
4142//===----------------------------------------------------------------------===//
4143// Diagnose initialization failures
4144//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004146 const InitializedEntity &Entity,
4147 const InitializationKind &Kind,
4148 Expr **Args, unsigned NumArgs) {
4149 if (SequenceKind != FailedSequence)
4150 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151
Douglas Gregor1b303932009-12-22 15:35:07 +00004152 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004153 switch (Failure) {
4154 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004155 // FIXME: Customize for the initialized entity?
4156 if (NumArgs == 0)
4157 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4158 << DestType.getNonReferenceType();
4159 else // FIXME: diagnostic below could be better!
4160 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4161 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004162 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004163
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004164 case FK_ArrayNeedsInitList:
4165 case FK_ArrayNeedsInitListOrStringLiteral:
4166 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4167 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4168 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169
Douglas Gregore2f943b2011-02-22 18:29:51 +00004170 case FK_ArrayTypeMismatch:
4171 case FK_NonConstantArrayInit:
4172 S.Diag(Kind.getLocation(),
4173 (Failure == FK_ArrayTypeMismatch
4174 ? diag::err_array_init_different_type
4175 : diag::err_array_init_non_constant_array))
4176 << DestType.getNonReferenceType()
4177 << Args[0]->getType()
4178 << Args[0]->getSourceRange();
4179 break;
4180
John McCall16df1e52010-03-30 21:47:33 +00004181 case FK_AddressOfOverloadFailed: {
4182 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004184 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004185 true,
4186 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004187 break;
John McCall16df1e52010-03-30 21:47:33 +00004188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004190 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004191 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004192 switch (FailedOverloadResult) {
4193 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004194 if (Failure == FK_UserConversionOverloadFailed)
4195 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4196 << Args[0]->getType() << DestType
4197 << Args[0]->getSourceRange();
4198 else
4199 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4200 << DestType << Args[0]->getType()
4201 << Args[0]->getSourceRange();
4202
John McCall5c32be02010-08-24 20:38:10 +00004203 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004204 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004206 case OR_No_Viable_Function:
4207 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4208 << Args[0]->getType() << DestType.getNonReferenceType()
4209 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004210 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004211 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004213 case OR_Deleted: {
4214 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4215 << Args[0]->getType() << DestType.getNonReferenceType()
4216 << Args[0]->getSourceRange();
4217 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004218 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004219 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4220 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004221 if (Ovl == OR_Deleted) {
4222 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4223 << Best->Function->isDeleted();
4224 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004225 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004226 }
4227 break;
4228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004230 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004231 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004232 break;
4233 }
4234 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004236 case FK_NonConstLValueReferenceBindingToTemporary:
4237 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004239 Failure == FK_NonConstLValueReferenceBindingToTemporary
4240 ? diag::err_lvalue_reference_bind_to_temporary
4241 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004242 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004243 << DestType.getNonReferenceType()
4244 << Args[0]->getType()
4245 << Args[0]->getSourceRange();
4246 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004248 case FK_RValueReferenceBindingToLValue:
4249 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004250 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004251 << Args[0]->getSourceRange();
4252 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004253
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004254 case FK_ReferenceInitDropsQualifiers:
4255 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4256 << DestType.getNonReferenceType()
4257 << Args[0]->getType()
4258 << Args[0]->getSourceRange();
4259 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004261 case FK_ReferenceInitFailed:
4262 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4263 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004264 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004265 << Args[0]->getType()
4266 << Args[0]->getSourceRange();
4267 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregorb491ed32011-02-19 21:32:49 +00004269 case FK_ConversionFailed: {
4270 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004271 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4272 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273 << DestType
John McCall086a4642010-11-24 05:12:34 +00004274 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004275 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004276 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004277 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004278 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004279 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004280 SourceRange R;
4281
4282 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004283 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004284 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004286 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004287
Douglas Gregor8ec51732010-09-08 21:40:08 +00004288 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4289 if (Kind.isCStyleOrFunctionalCast())
4290 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4291 << R;
4292 else
4293 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4294 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004295 break;
4296 }
4297
4298 case FK_ReferenceBindingToInitList:
4299 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4300 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4301 break;
4302
4303 case FK_InitListBadDestinationType:
4304 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4305 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4306 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004308 case FK_ConstructorOverloadFailed: {
4309 SourceRange ArgsRange;
4310 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004312 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004314 // FIXME: Using "DestType" for the entity we're printing is probably
4315 // bad.
4316 switch (FailedOverloadResult) {
4317 case OR_Ambiguous:
4318 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4319 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004320 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4321 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004322 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004324 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004325 if (Kind.getKind() == InitializationKind::IK_Default &&
4326 (Entity.getKind() == InitializedEntity::EK_Base ||
4327 Entity.getKind() == InitializedEntity::EK_Member) &&
4328 isa<CXXConstructorDecl>(S.CurContext)) {
4329 // This is implicit default initialization of a member or
4330 // base within a constructor. If no viable function was
4331 // found, notify the user that she needs to explicitly
4332 // initialize this base/member.
4333 CXXConstructorDecl *Constructor
4334 = cast<CXXConstructorDecl>(S.CurContext);
4335 if (Entity.getKind() == InitializedEntity::EK_Base) {
4336 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4337 << Constructor->isImplicit()
4338 << S.Context.getTypeDeclType(Constructor->getParent())
4339 << /*base=*/0
4340 << Entity.getType();
4341
4342 RecordDecl *BaseDecl
4343 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4344 ->getDecl();
4345 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4346 << S.Context.getTagDeclType(BaseDecl);
4347 } else {
4348 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4349 << Constructor->isImplicit()
4350 << S.Context.getTypeDeclType(Constructor->getParent())
4351 << /*member=*/1
4352 << Entity.getName();
4353 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4354
4355 if (const RecordType *Record
4356 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004358 diag::note_previous_decl)
4359 << S.Context.getTagDeclType(Record->getDecl());
4360 }
4361 break;
4362 }
4363
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004364 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4365 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004366 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004367 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004369 case OR_Deleted: {
4370 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4371 << true << DestType << ArgsRange;
4372 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004373 OverloadingResult Ovl
4374 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004375 if (Ovl == OR_Deleted) {
4376 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4377 << Best->Function->isDeleted();
4378 } else {
4379 llvm_unreachable("Inconsistent overload resolution?");
4380 }
4381 break;
4382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004384 case OR_Success:
4385 llvm_unreachable("Conversion did not fail!");
4386 break;
4387 }
4388 break;
4389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390
Douglas Gregor85dabae2009-12-16 01:38:02 +00004391 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004392 if (Entity.getKind() == InitializedEntity::EK_Member &&
4393 isa<CXXConstructorDecl>(S.CurContext)) {
4394 // This is implicit default-initialization of a const member in
4395 // a constructor. Complain that it needs to be explicitly
4396 // initialized.
4397 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4398 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4399 << Constructor->isImplicit()
4400 << S.Context.getTypeDeclType(Constructor->getParent())
4401 << /*const=*/1
4402 << Entity.getName();
4403 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4404 << Entity.getName();
4405 } else {
4406 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4407 << DestType << (bool)DestType->getAs<RecordType>();
4408 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004409 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004411 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004413 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004414 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004417 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004418 return true;
4419}
Douglas Gregore1314a62009-12-18 05:02:21 +00004420
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004421void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4422 switch (SequenceKind) {
4423 case FailedSequence: {
4424 OS << "Failed sequence: ";
4425 switch (Failure) {
4426 case FK_TooManyInitsForReference:
4427 OS << "too many initializers for reference";
4428 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004430 case FK_ArrayNeedsInitList:
4431 OS << "array requires initializer list";
4432 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004434 case FK_ArrayNeedsInitListOrStringLiteral:
4435 OS << "array requires initializer list or string literal";
4436 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437
Douglas Gregore2f943b2011-02-22 18:29:51 +00004438 case FK_ArrayTypeMismatch:
4439 OS << "array type mismatch";
4440 break;
4441
4442 case FK_NonConstantArrayInit:
4443 OS << "non-constant array initializer";
4444 break;
4445
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004446 case FK_AddressOfOverloadFailed:
4447 OS << "address of overloaded function failed";
4448 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004450 case FK_ReferenceInitOverloadFailed:
4451 OS << "overload resolution for reference initialization failed";
4452 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004454 case FK_NonConstLValueReferenceBindingToTemporary:
4455 OS << "non-const lvalue reference bound to temporary";
4456 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004458 case FK_NonConstLValueReferenceBindingToUnrelated:
4459 OS << "non-const lvalue reference bound to unrelated type";
4460 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004461
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004462 case FK_RValueReferenceBindingToLValue:
4463 OS << "rvalue reference bound to an lvalue";
4464 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004466 case FK_ReferenceInitDropsQualifiers:
4467 OS << "reference initialization drops qualifiers";
4468 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004469
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004470 case FK_ReferenceInitFailed:
4471 OS << "reference initialization failed";
4472 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004474 case FK_ConversionFailed:
4475 OS << "conversion failed";
4476 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004478 case FK_TooManyInitsForScalar:
4479 OS << "too many initializers for scalar";
4480 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004482 case FK_ReferenceBindingToInitList:
4483 OS << "referencing binding to initializer list";
4484 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004486 case FK_InitListBadDestinationType:
4487 OS << "initializer list for non-aggregate, non-scalar type";
4488 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004490 case FK_UserConversionOverloadFailed:
4491 OS << "overloading failed for user-defined conversion";
4492 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004494 case FK_ConstructorOverloadFailed:
4495 OS << "constructor overloading failed";
4496 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004497
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004498 case FK_DefaultInitOfConst:
4499 OS << "default initialization of a const variable";
4500 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004502 case FK_Incomplete:
4503 OS << "initialization of incomplete type";
4504 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004506 OS << '\n';
4507 return;
4508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004510 case DependentSequence:
4511 OS << "Dependent sequence: ";
4512 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004514 case UserDefinedConversion:
4515 OS << "User-defined conversion sequence: ";
4516 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004518 case ConstructorInitialization:
4519 OS << "Constructor initialization sequence: ";
4520 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004522 case ReferenceBinding:
4523 OS << "Reference binding: ";
4524 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004526 case ListInitialization:
4527 OS << "List initialization: ";
4528 break;
4529
4530 case ZeroInitialization:
4531 OS << "Zero initialization\n";
4532 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004534 case NoInitialization:
4535 OS << "No initialization\n";
4536 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004538 case StandardConversion:
4539 OS << "Standard conversion: ";
4540 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004542 case CAssignment:
4543 OS << "C assignment: ";
4544 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004546 case StringInit:
4547 OS << "String initialization: ";
4548 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004549
4550 case ArrayInit:
4551 OS << "Array initialization: ";
4552 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004555 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4556 if (S != step_begin()) {
4557 OS << " -> ";
4558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004560 switch (S->Kind) {
4561 case SK_ResolveAddressOfOverloadedFunction:
4562 OS << "resolve address of overloaded function";
4563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004565 case SK_CastDerivedToBaseRValue:
4566 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4567 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004569 case SK_CastDerivedToBaseXValue:
4570 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4571 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004573 case SK_CastDerivedToBaseLValue:
4574 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4575 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004577 case SK_BindReference:
4578 OS << "bind reference to lvalue";
4579 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004581 case SK_BindReferenceToTemporary:
4582 OS << "bind reference to a temporary";
4583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004585 case SK_ExtraneousCopyToTemporary:
4586 OS << "extraneous C++03 copy to temporary";
4587 break;
4588
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004589 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004590 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004591 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004592
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004593 case SK_QualificationConversionRValue:
4594 OS << "qualification conversion (rvalue)";
4595
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004596 case SK_QualificationConversionXValue:
4597 OS << "qualification conversion (xvalue)";
4598
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004599 case SK_QualificationConversionLValue:
4600 OS << "qualification conversion (lvalue)";
4601 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004603 case SK_ConversionSequence:
4604 OS << "implicit conversion sequence (";
4605 S->ICS->DebugPrint(); // FIXME: use OS
4606 OS << ")";
4607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004609 case SK_ListInitialization:
4610 OS << "list initialization";
4611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004613 case SK_ConstructorInitialization:
4614 OS << "constructor initialization";
4615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004617 case SK_ZeroInitialization:
4618 OS << "zero initialization";
4619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004620
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004621 case SK_CAssignment:
4622 OS << "C assignment";
4623 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004624
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004625 case SK_StringInit:
4626 OS << "string initialization";
4627 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004628
4629 case SK_ObjCObjectConversion:
4630 OS << "Objective-C object conversion";
4631 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004632
4633 case SK_ArrayInit:
4634 OS << "array initialization";
4635 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004636 }
4637 }
4638}
4639
4640void InitializationSequence::dump() const {
4641 dump(llvm::errs());
4642}
4643
Douglas Gregore1314a62009-12-18 05:02:21 +00004644//===----------------------------------------------------------------------===//
4645// Initialization helper functions
4646//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004648Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4649 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004650 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004651 if (Init.isInvalid())
4652 return ExprError();
4653
John McCall1f425642010-11-11 03:21:53 +00004654 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00004655 assert(InitE && "No initialization expression?");
4656
4657 if (EqualLoc.isInvalid())
4658 EqualLoc = InitE->getLocStart();
4659
4660 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4661 EqualLoc);
4662 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4663 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004664 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004665}