blob: 9fbcbab0b7d0aa9f21a610c3a9bddfa302871c71 [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//
Rafael Espindola699fc4d2011-07-14 22:58:04 +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.
Chris Lattner0cb78032009-02-24 22:27:37 +000013//
Steve Narofff8ecff22008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
John McCall66884dd2011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattnera9196812009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnera9196812009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000055
Eli Friedman42a84652009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000062 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner0cb78032009-02-24 22:27:37 +000064 return 0;
65}
66
John McCall66884dd2011-02-21 07:22:22 +000067static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
68 const ArrayType *arrayType = Context.getAsArrayType(declType);
69 if (!arrayType) return 0;
70
71 return IsStringInit(init, arrayType, Context);
72}
73
John McCall5decec92011-02-21 07:57:55 +000074static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
75 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000076 // Get the length of the string as parsed.
77 uint64_t StrLength =
78 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
79
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner0cb78032009-02-24 22:27:37 +000081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000082 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000083 // being initialized to a string literal.
84 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000085 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000086 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000087 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
88 ConstVal,
89 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000090 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000091 }
Mike Stump11289f42009-09-09 15:08:12 +000092
Eli Friedman893abe42009-05-29 18:22:49 +000093 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000094
Eli Friedman554eba92011-04-11 00:23:45 +000095 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +000096 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +000098 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +000099 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
100 // For Pascal strings it's OK to strip off the terminating null character,
101 // so the example below is valid:
102 //
103 // unsigned char a[2] = "\pa";
104 if (SL->isPascal())
105 StrLength--;
106 }
107
Eli Friedman554eba92011-04-11 00:23:45 +0000108 // [dcl.init.string]p2
109 if (StrLength > CAT->getSize().getZExtValue())
110 S.Diag(Str->getSourceRange().getBegin(),
111 diag::err_initializer_string_for_char_array_too_long)
112 << Str->getSourceRange();
113 } else {
114 // C99 6.7.8p14.
115 if (StrLength-1 > CAT->getSize().getZExtValue())
116 S.Diag(Str->getSourceRange().getBegin(),
117 diag::warn_initializer_string_for_char_array_too_long)
118 << Str->getSourceRange();
119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Eli Friedman893abe42009-05-29 18:22:49 +0000121 // Set the type to the actual size that we are initializing. If we have
122 // something like:
123 // char x[1] = "foo";
124 // then this will set the string literal's type to char[1].
125 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000126}
127
Chris Lattner0cb78032009-02-24 22:27:37 +0000128//===----------------------------------------------------------------------===//
129// Semantic checking for initializer lists.
130//===----------------------------------------------------------------------===//
131
Douglas Gregorcde232f2009-01-29 01:05:33 +0000132/// @brief Semantic checking for initializer lists.
133///
134/// The InitListChecker class contains a set of routines that each
135/// handle the initialization of a certain kind of entity, e.g.,
136/// arrays, vectors, struct/union types, scalars, etc. The
137/// InitListChecker itself performs a recursive walk of the subobject
138/// structure of the type to be initialized, while stepping through
139/// the initializer list one element at a time. The IList and Index
140/// parameters to each of the Check* routines contain the active
141/// (syntactic) initializer list and the index into that initializer
142/// list that represents the current initializer. Each routine is
143/// responsible for moving that Index forward as it consumes elements.
144///
145/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000146/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000147/// initializer list and the index into that initializer list where we
148/// are copying initializers as we map them over to the semantic
149/// list. Once we have completed our recursive walk of the subobject
150/// structure, we will have constructed a full semantic initializer
151/// list.
152///
153/// C99 designators cause changes in the initializer list traversal,
154/// because they make the initialization "jump" into a specific
155/// subobject and then continue the initialization from that
156/// point. CheckDesignatedInitializer() recursively steps into the
157/// designated subobject and manages backing out the recursion to
158/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000159namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000160class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000161 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000162 bool hadError;
163 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
164 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000165
Anders Carlsson6cabf312010-01-23 23:23:01 +0000166 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000167 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000168 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000169 unsigned &StructuredIndex,
170 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000171 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000172 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000173 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000174 unsigned &StructuredIndex,
175 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000178 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000179 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000180 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000181 unsigned &StructuredIndex,
182 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000185 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000186 InitListExpr *StructuredList,
187 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckReferenceType(const InitializedEntity &Entity,
194 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000195 unsigned &Index,
196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000198 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000202 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000203 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000204 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000209 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000210 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000211 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000212 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000216 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
227 QualType CurrentObjectType,
228 InitListExpr *StructuredList,
229 unsigned StructuredIndex,
230 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000236
Douglas Gregor2bb07652009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000245 bool HadError() { return hadError; }
246
247 // @brief Retrieves the fully-structured initializer list used for
248 // semantic analysis and code generation.
249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
250};
Chris Lattner9ececce2009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000252
Douglas Gregor2bb07652009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000260 = InitializedEntity::InitializeMember(Field, &ParentEntity);
261 if (Init >= NumInits || !ILE->getInit(Init)) {
262 // FIXME: We probably don't need to handle references
263 // specially here, since value-initialization of references is
264 // handled in InitializationSequence.
265 if (Field->getType()->isReferenceType()) {
266 // C++ [dcl.init.aggr]p9:
267 // If an incomplete or empty initializer-list leaves a
268 // member of reference type uninitialized, the program is
269 // ill-formed.
270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
271 << Field->getType()
272 << ILE->getSyntacticForm()->getSourceRange();
273 SemaRef.Diag(Field->getLocation(),
274 diag::note_uninit_reference_member);
275 hadError = true;
276 return;
277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
Douglas Gregor2bb07652009-12-22 00:05:34 +0000279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
282 if (!InitSeq) {
283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
284 hadError = true;
285 return;
286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
John McCalldadc5752010-08-24 06:29:42 +0000288 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000290 if (MemberInit.isInvalid()) {
291 hadError = true;
292 return;
293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 if (hadError) {
296 // Do nothing
297 } else if (Init < NumInits) {
298 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000299 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000300 // Value-initialization requires a constructor call, so
301 // extend the initializer list to include the constructor
302 // call and make a note that we'll need to take another pass
303 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000304 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000305 RequiresSecondPass = true;
306 }
307 } else if (InitListExpr *InnerILE
308 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000309 FillInValueInitializations(MemberEntity, InnerILE,
310 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000311}
312
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000313/// Recursively replaces NULL values within the given initializer list
314/// with expressions that perform value-initialization of the
315/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000316void
Douglas Gregor723796a2009-12-16 06:35:08 +0000317InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
318 InitListExpr *ILE,
319 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000320 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000321 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000322 SourceLocation Loc = ILE->getSourceRange().getBegin();
323 if (ILE->getSyntacticForm())
324 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000325
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000326 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000327 if (RType->getDecl()->isUnion() &&
328 ILE->getInitializedFieldInUnion())
329 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
330 Entity, ILE, RequiresSecondPass);
331 else {
332 unsigned Init = 0;
333 for (RecordDecl::field_iterator
334 Field = RType->getDecl()->field_begin(),
335 FieldEnd = RType->getDecl()->field_end();
336 Field != FieldEnd; ++Field) {
337 if (Field->isUnnamedBitfield())
338 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000339
Douglas Gregor2bb07652009-12-22 00:05:34 +0000340 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000341 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000342
343 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
344 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000345 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000346
Douglas Gregor2bb07652009-12-22 00:05:34 +0000347 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000348
Douglas Gregor2bb07652009-12-22 00:05:34 +0000349 // Only look at the first initialization of a union.
350 if (RType->getDecl()->isUnion())
351 break;
352 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000353 }
354
355 return;
Mike Stump11289f42009-09-09 15:08:12 +0000356 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000357
358 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Douglas Gregor723796a2009-12-16 06:35:08 +0000360 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000361 unsigned NumInits = ILE->getNumInits();
362 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000363 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000364 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000365 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
366 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000367 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000368 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000369 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000370 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000371 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000372 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000373 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000374 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000375 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000376
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000378 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000379 if (hadError)
380 return;
381
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000382 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
383 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000384 ElementEntity.setElementIndex(Init);
385
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000386 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000387 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
388 true);
389 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
390 if (!InitSeq) {
391 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000392 hadError = true;
393 return;
394 }
395
John McCalldadc5752010-08-24 06:29:42 +0000396 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000397 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000398 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000399 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000400 return;
401 }
402
403 if (hadError) {
404 // Do nothing
405 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000406 // For arrays, just set the expression used for value-initialization
407 // of the "holes" in the array.
408 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
409 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
410 else
411 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000412 } else {
413 // For arrays, just set the expression used for value-initialization
414 // of the rest of elements and exit.
415 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
416 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
417 return;
418 }
419
Sebastian Redld201edf2011-06-05 13:59:11 +0000420 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000421 // Value-initialization requires a constructor call, so
422 // extend the initializer list to include the constructor
423 // call and make a note that we'll need to take another pass
424 // through the initializer list.
425 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
426 RequiresSecondPass = true;
427 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000428 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000429 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000430 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
431 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000432 }
433}
434
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000435
Douglas Gregor723796a2009-12-16 06:35:08 +0000436InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
437 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000438 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000439 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000440
Eli Friedman23a9e312008-05-19 19:16:24 +0000441 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000442 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000443 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000444 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000446 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000447 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000448
Douglas Gregor723796a2009-12-16 06:35:08 +0000449 if (!hadError) {
450 bool RequiresSecondPass = false;
451 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000452 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000454 RequiresSecondPass);
455 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000456}
457
458int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000459 // FIXME: use a proper constant
460 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000461 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000462 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000463 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
464 }
465 return maxElements;
466}
467
468int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000469 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000470 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000471 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000472 Field = structDecl->field_begin(),
473 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000474 Field != FieldEnd; ++Field) {
475 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
476 ++InitializableMembers;
477 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000478 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000479 return std::min(InitializableMembers, 1);
480 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000481}
482
Anders Carlsson6cabf312010-01-23 23:23:01 +0000483void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000484 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000485 QualType T, unsigned &Index,
486 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000487 unsigned &StructuredIndex,
488 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000489 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000490
Steve Narofff8ecff22008-05-01 22:18:59 +0000491 if (T->isArrayType())
492 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000493 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000494 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000495 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000496 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000497 else
498 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000499
Eli Friedmane0f832b2008-05-25 13:49:22 +0000500 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000501 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000502 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000503 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000504 hadError = true;
505 return;
506 }
507
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000508 // Build a structured initializer list corresponding to this subobject.
509 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000510 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
511 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000512 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
513 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000514 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000515
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000516 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000517 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000519 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000520 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000521 StructuredSubobjectInitIndex,
522 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000523 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000524 StructuredSubobjectInitList->setType(T);
525
Douglas Gregor5741efb2009-03-01 17:12:46 +0000526 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000527 // range corresponds with the end of the last initializer it used.
528 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000529 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000530 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
531 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Tanya Lattner5029d562010-03-07 04:17:15 +0000534 // Warn about missing braces.
535 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000536 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
537 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000538 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000540 "{")
541 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000543 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000544 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000545}
546
Anders Carlsson6cabf312010-01-23 23:23:01 +0000547void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000548 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000549 unsigned &Index,
550 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000551 unsigned &StructuredIndex,
552 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000553 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000554 SyntacticToSemantic[IList] = StructuredList;
555 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000557 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000558 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
559 IList->setType(ExprTy);
560 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000561 if (hadError)
562 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000563
Eli Friedman85f54972008-05-25 13:22:35 +0000564 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000565 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000566 if (StructuredIndex == 1 &&
567 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000568 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000569 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000570 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000571 hadError = true;
572 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000573 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000574 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000575 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000576 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000577 // Don't complain for incomplete types, since we'll get an error
578 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000579 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000580 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000581 CurrentObjectType->isArrayType()? 0 :
582 CurrentObjectType->isVectorType()? 1 :
583 CurrentObjectType->isScalarType()? 2 :
584 CurrentObjectType->isUnionType()? 3 :
585 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000586
587 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000588 if (SemaRef.getLangOptions().CPlusPlus) {
589 DK = diag::err_excess_initializers;
590 hadError = true;
591 }
Nate Begeman425038c2009-07-07 21:53:06 +0000592 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
593 DK = diag::err_excess_initializers;
594 hadError = true;
595 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000596
Chris Lattnerb0912a52009-02-24 22:50:46 +0000597 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000598 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000599 }
600 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000601
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000602 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000603 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000604 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000605 << FixItHint::CreateRemoval(IList->getLocStart())
606 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000607}
608
Anders Carlsson6cabf312010-01-23 23:23:01 +0000609void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000610 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000611 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000612 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000613 unsigned &Index,
614 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000615 unsigned &StructuredIndex,
616 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000617 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000618 CheckScalarType(Entity, IList, DeclType, Index,
619 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000620 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000621 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000622 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000623 } else if (DeclType->isAggregateType()) {
624 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000625 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000626 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000627 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000628 StructuredList, StructuredIndex,
629 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000630 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000631 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000632 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000633 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000635 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000636 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000637 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000638 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000639 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
640 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000641 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000642 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000643 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000644 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000645 } else if (DeclType->isRecordType()) {
646 // C++ [dcl.init]p14:
647 // [...] If the class is an aggregate (8.5.1), and the initializer
648 // is a brace-enclosed list, see 8.5.1.
649 //
650 // Note: 8.5.1 is handled below; here, we diagnose the case where
651 // we have an initializer list and a destination type that is not
652 // an aggregate.
653 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000654 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000655 << DeclType << IList->getSourceRange();
656 hadError = true;
657 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000658 CheckReferenceType(Entity, IList, DeclType, Index,
659 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000660 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000661 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
662 << DeclType;
663 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000664 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000665 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
666 << DeclType;
667 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000668 }
669}
670
Anders Carlsson6cabf312010-01-23 23:23:01 +0000671void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000672 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000673 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000674 unsigned &Index,
675 InitListExpr *StructuredList,
676 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000677 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000678 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
679 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000680 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000681 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000682 = getStructuredSubobjectInit(IList, Index, ElemType,
683 StructuredList, StructuredIndex,
684 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000685 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000686 newStructuredList, newStructuredIndex);
687 ++StructuredIndex;
688 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000689 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000690 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000691 return CheckScalarType(Entity, IList, ElemType, Index,
692 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000693 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000694 return CheckReferenceType(Entity, IList, ElemType, Index,
695 StructuredList, StructuredIndex);
696 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000697
John McCall5decec92011-02-21 07:57:55 +0000698 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
699 // arrayType can be incomplete if we're initializing a flexible
700 // array member. There's nothing we can do with the completed
701 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
John McCall5decec92011-02-21 07:57:55 +0000703 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
704 CheckStringInit(Str, ElemType, arrayType, SemaRef);
705 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000706 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000707 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000708 }
John McCall5decec92011-02-21 07:57:55 +0000709
710 // Fall through for subaggregate initialization.
711
712 } else if (SemaRef.getLangOptions().CPlusPlus) {
713 // C++ [dcl.init.aggr]p12:
714 // All implicit type conversions (clause 4) are considered when
Rafael Espindola699fc4d2011-07-14 22:58:04 +0000715 // initializing the aggregate member with an ini- tializer from
John McCall5decec92011-02-21 07:57:55 +0000716 // an initializer-list. If the initializer can initialize a
717 // member, the member is initialized. [...]
718
719 // FIXME: Better EqualLoc?
720 InitializationKind Kind =
721 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
722 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
723
724 if (Seq) {
725 ExprResult Result =
726 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
727 if (Result.isInvalid())
728 hadError = true;
729
730 UpdateStructuredListElement(StructuredList, StructuredIndex,
731 Result.takeAs<Expr>());
732 ++Index;
733 return;
734 }
735
736 // Fall through for subaggregate initialization
737 } else {
738 // C99 6.7.8p13:
739 //
740 // The initializer for a structure or union object that has
741 // automatic storage duration shall be either an initializer
742 // list as described below, or a single expression that has
743 // compatible structure or union type. In the latter case, the
744 // initial value of the object, including unnamed members, is
745 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000746 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000747 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000748 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000749 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000750 if (ExprRes.isInvalid())
751 hadError = true;
752 else {
753 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
754 if (ExprRes.isInvalid())
755 hadError = true;
756 }
757 UpdateStructuredListElement(StructuredList, StructuredIndex,
758 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000759 ++Index;
760 return;
761 }
John Wiegley01296292011-04-08 18:41:53 +0000762 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000763 // Fall through for subaggregate initialization
764 }
765
766 // C++ [dcl.init.aggr]p12:
767 //
768 // [...] Otherwise, if the member is itself a non-empty
769 // subaggregate, brace elision is assumed and the initializer is
770 // considered for the initialization of the first member of
771 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000772 if (!SemaRef.getLangOptions().OpenCL &&
773 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000774 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
775 StructuredIndex);
776 ++StructuredIndex;
777 } else {
778 // We cannot initialize this element, so let
779 // PerformCopyInitialization produce the appropriate diagnostic.
780 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
781 SemaRef.Owned(expr));
782 hadError = true;
783 ++Index;
784 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000785 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000786}
787
Anders Carlsson6cabf312010-01-23 23:23:01 +0000788void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000789 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000790 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000791 InitListExpr *StructuredList,
792 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000793 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000794 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000795 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000796 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000797 ++Index;
798 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000799 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000800 }
John McCall643169b2010-11-11 00:46:36 +0000801
802 Expr *expr = IList->getInit(Index);
803 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
804 SemaRef.Diag(SubIList->getLocStart(),
805 diag::warn_many_braces_around_scalar_init)
806 << SubIList->getSourceRange();
807
808 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
809 StructuredIndex);
810 return;
811 } else if (isa<DesignatedInitExpr>(expr)) {
812 SemaRef.Diag(expr->getSourceRange().getBegin(),
813 diag::err_designator_for_scalar_init)
814 << DeclType << expr->getSourceRange();
815 hadError = true;
816 ++Index;
817 ++StructuredIndex;
818 return;
819 }
820
821 ExprResult Result =
822 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
823 SemaRef.Owned(expr));
824
825 Expr *ResultExpr = 0;
826
827 if (Result.isInvalid())
828 hadError = true; // types weren't compatible.
829 else {
830 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831
John McCall643169b2010-11-11 00:46:36 +0000832 if (ResultExpr != expr) {
833 // The type was promoted, update initializer list.
834 IList->setInit(Index, ResultExpr);
835 }
836 }
837 if (hadError)
838 ++StructuredIndex;
839 else
840 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
841 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000842}
843
Anders Carlsson6cabf312010-01-23 23:23:01 +0000844void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
845 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000846 unsigned &Index,
847 InitListExpr *StructuredList,
848 unsigned &StructuredIndex) {
849 if (Index < IList->getNumInits()) {
850 Expr *expr = IList->getInit(Index);
851 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000852 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000853 << DeclType << IList->getSourceRange();
854 hadError = true;
855 ++Index;
856 ++StructuredIndex;
857 return;
Mike Stump11289f42009-09-09 15:08:12 +0000858 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000859
John McCalldadc5752010-08-24 06:29:42 +0000860 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000861 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
862 SemaRef.Owned(expr));
863
864 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000865 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000866
867 expr = Result.takeAs<Expr>();
868 IList->setInit(Index, expr);
869
Douglas Gregord14247a2009-01-30 22:09:00 +0000870 if (hadError)
871 ++StructuredIndex;
872 else
873 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
874 ++Index;
875 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000876 // FIXME: It would be wonderful if we could point at the actual member. In
877 // general, it would be useful to pass location information down the stack,
878 // so that we know the location (or decl) of the "current object" being
879 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000880 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000881 diag::err_init_reference_member_uninitialized)
882 << DeclType
883 << IList->getSourceRange();
884 hadError = true;
885 ++Index;
886 ++StructuredIndex;
887 return;
888 }
889}
890
Anders Carlsson6cabf312010-01-23 23:23:01 +0000891void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000892 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000893 unsigned &Index,
894 InitListExpr *StructuredList,
895 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000896 if (Index >= IList->getNumInits())
897 return;
Mike Stump11289f42009-09-09 15:08:12 +0000898
John McCall6a16b2f2010-10-30 00:11:39 +0000899 const VectorType *VT = DeclType->getAs<VectorType>();
900 unsigned maxElements = VT->getNumElements();
901 unsigned numEltsInit = 0;
902 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000903
John McCall6a16b2f2010-10-30 00:11:39 +0000904 if (!SemaRef.getLangOptions().OpenCL) {
905 // If the initializing element is a vector, try to copy-initialize
906 // instead of breaking it apart (which is doomed to failure anyway).
907 Expr *Init = IList->getInit(Index);
908 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
909 ExprResult Result =
910 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
911 SemaRef.Owned(Init));
912
913 Expr *ResultExpr = 0;
914 if (Result.isInvalid())
915 hadError = true; // types weren't compatible.
916 else {
917 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
John McCall6a16b2f2010-10-30 00:11:39 +0000919 if (ResultExpr != Init) {
920 // The type was promoted, update initializer list.
921 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000922 }
923 }
John McCall6a16b2f2010-10-30 00:11:39 +0000924 if (hadError)
925 ++StructuredIndex;
926 else
927 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
928 ++Index;
929 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
John McCall6a16b2f2010-10-30 00:11:39 +0000932 InitializedEntity ElementEntity =
933 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934
John McCall6a16b2f2010-10-30 00:11:39 +0000935 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
936 // Don't attempt to go past the end of the init list
937 if (Index >= IList->getNumInits())
938 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000939
John McCall6a16b2f2010-10-30 00:11:39 +0000940 ElementEntity.setElementIndex(Index);
941 CheckSubElementType(ElementEntity, IList, elementType, Index,
942 StructuredList, StructuredIndex);
943 }
944 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000945 }
John McCall6a16b2f2010-10-30 00:11:39 +0000946
947 InitializedEntity ElementEntity =
948 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000949
John McCall6a16b2f2010-10-30 00:11:39 +0000950 // OpenCL initializers allows vectors to be constructed from vectors.
951 for (unsigned i = 0; i < maxElements; ++i) {
952 // Don't attempt to go past the end of the init list
953 if (Index >= IList->getNumInits())
954 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000955
John McCall6a16b2f2010-10-30 00:11:39 +0000956 ElementEntity.setElementIndex(Index);
957
958 QualType IType = IList->getInit(Index)->getType();
959 if (!IType->isVectorType()) {
960 CheckSubElementType(ElementEntity, IList, elementType, Index,
961 StructuredList, StructuredIndex);
962 ++numEltsInit;
963 } else {
964 QualType VecType;
965 const VectorType *IVT = IType->getAs<VectorType>();
966 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
John McCall6a16b2f2010-10-30 00:11:39 +0000968 if (IType->isExtVectorType())
969 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
970 else
971 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000972 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000973 CheckSubElementType(ElementEntity, IList, VecType, Index,
974 StructuredList, StructuredIndex);
975 numEltsInit += numIElts;
976 }
977 }
978
979 // OpenCL requires all elements to be initialized.
980 if (numEltsInit != maxElements)
981 if (SemaRef.getLangOptions().OpenCL)
982 SemaRef.Diag(IList->getSourceRange().getBegin(),
983 diag::err_vector_incorrect_num_initializers)
984 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000985}
986
Anders Carlsson6cabf312010-01-23 23:23:01 +0000987void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000988 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000989 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000990 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000991 unsigned &Index,
992 InitListExpr *StructuredList,
993 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000994 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
995
Steve Narofff8ecff22008-05-01 22:18:59 +0000996 // Check for the special-case of initializing an array with a string.
997 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +0000998 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000999 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +00001000 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001001 // We place the string literal directly into the resulting
1002 // initializer list. This is the only place where the structure
1003 // of the structured initializer list doesn't match exactly,
1004 // because doing so would involve allocating one character
1005 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +00001006 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +00001007 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001008 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001009 return;
1010 }
1011 }
John McCall66884dd2011-02-21 07:22:22 +00001012 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001013 // Check for VLAs; in standard C it would be possible to check this
1014 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1015 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001016 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001017 diag::err_variable_object_no_init)
1018 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001019 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001020 ++Index;
1021 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001022 return;
1023 }
1024
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001025 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001026 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1027 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001028 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001029 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001030 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001031 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001032 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001033 maxElementsKnown = true;
1034 }
1035
John McCall66884dd2011-02-21 07:22:22 +00001036 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001037 while (Index < IList->getNumInits()) {
1038 Expr *Init = IList->getInit(Index);
1039 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001040 // If we're not the subobject that matches up with the '{' for
1041 // the designator, we shouldn't be handling the
1042 // designator. Return immediately.
1043 if (!SubobjectIsDesignatorContext)
1044 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001045
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001046 // Handle this designated initializer. elementIndex will be
1047 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001048 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001049 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001050 StructuredList, StructuredIndex, true,
1051 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001052 hadError = true;
1053 continue;
1054 }
1055
Douglas Gregor033d1252009-01-23 16:54:12 +00001056 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001057 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001058 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001059 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001060 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001061
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001062 // If the array is of incomplete type, keep track of the number of
1063 // elements in the initializer.
1064 if (!maxElementsKnown && elementIndex > maxElements)
1065 maxElements = elementIndex;
1066
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001067 continue;
1068 }
1069
1070 // If we know the maximum number of elements, and we've already
1071 // hit it, stop consuming elements in the initializer list.
1072 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001073 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001074
Anders Carlsson6cabf312010-01-23 23:23:01 +00001075 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001076 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001077 Entity);
1078 // Check this element.
1079 CheckSubElementType(ElementEntity, IList, elementType, Index,
1080 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001081 ++elementIndex;
1082
1083 // If the array is of incomplete type, keep track of the number of
1084 // elements in the initializer.
1085 if (!maxElementsKnown && elementIndex > maxElements)
1086 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001087 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001088 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001089 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001090 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001091 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001092 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001093 // Sizing an array implicitly to zero is not allowed by ISO C,
1094 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001095 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001096 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001097 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001098
Mike Stump11289f42009-09-09 15:08:12 +00001099 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001100 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001101 }
1102}
1103
Anders Carlsson6cabf312010-01-23 23:23:01 +00001104void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001105 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001106 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001107 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001108 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001109 unsigned &Index,
1110 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001111 unsigned &StructuredIndex,
1112 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001113 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001114
Eli Friedman23a9e312008-05-19 19:16:24 +00001115 // If the record is invalid, some of it's members are invalid. To avoid
1116 // confusion, we forgo checking the intializer for the entire record.
1117 if (structDecl->isInvalidDecl()) {
1118 hadError = true;
1119 return;
Mike Stump11289f42009-09-09 15:08:12 +00001120 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001121
1122 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1123 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001124 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001125 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001126 Field != FieldEnd; ++Field) {
1127 if (Field->getDeclName()) {
1128 StructuredList->setInitializedFieldInUnion(*Field);
1129 break;
1130 }
1131 }
1132 return;
1133 }
1134
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001135 // If structDecl is a forward declaration, this loop won't do
1136 // anything except look at designated initializers; That's okay,
1137 // because an error should get printed out elsewhere. It might be
1138 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001139 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001140 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001141 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001142 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001143 while (Index < IList->getNumInits()) {
1144 Expr *Init = IList->getInit(Index);
1145
1146 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001147 // If we're not the subobject that matches up with the '{' for
1148 // the designator, we shouldn't be handling the
1149 // designator. Return immediately.
1150 if (!SubobjectIsDesignatorContext)
1151 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001152
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001153 // Handle this designated initializer. Field will be updated to
1154 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001155 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001156 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001157 StructuredList, StructuredIndex,
1158 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001159 hadError = true;
1160
Douglas Gregora9add4e2009-02-12 19:00:39 +00001161 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001162
1163 // Disable check for missing fields when designators are used.
1164 // This matches gcc behaviour.
1165 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001166 continue;
1167 }
1168
1169 if (Field == FieldEnd) {
1170 // We've run out of fields. We're done.
1171 break;
1172 }
1173
Douglas Gregora9add4e2009-02-12 19:00:39 +00001174 // We've already initialized a member of a union. We're done.
1175 if (InitializedSomething && DeclType->isUnionType())
1176 break;
1177
Douglas Gregor91f84212008-12-11 16:49:14 +00001178 // If we've hit the flexible array member at the end, we're done.
1179 if (Field->getType()->isIncompleteArrayType())
1180 break;
1181
Douglas Gregor51695702009-01-29 16:53:55 +00001182 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001183 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001184 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001185 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001186 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001187
Douglas Gregora82064c2011-06-29 21:51:31 +00001188 // Make sure we can use this declaration.
1189 if (SemaRef.DiagnoseUseOfDecl(*Field,
1190 IList->getInit(Index)->getLocStart())) {
1191 ++Index;
1192 ++Field;
1193 hadError = true;
1194 continue;
1195 }
1196
Anders Carlsson6cabf312010-01-23 23:23:01 +00001197 InitializedEntity MemberEntity =
1198 InitializedEntity::InitializeMember(*Field, &Entity);
1199 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1200 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001201 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001202
1203 if (DeclType->isUnionType()) {
1204 // Initialize the first field within the union.
1205 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001206 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001207
1208 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001209 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001210
John McCalle40b58e2010-03-11 19:32:38 +00001211 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001212 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001213 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1214 // It is possible we have one or more unnamed bitfields remaining.
1215 // Find first (if any) named field and emit warning.
1216 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1217 it != end; ++it) {
1218 if (!it->isUnnamedBitfield()) {
1219 SemaRef.Diag(IList->getSourceRange().getEnd(),
1220 diag::warn_missing_field_initializers) << it->getName();
1221 break;
1222 }
1223 }
1224 }
1225
Mike Stump11289f42009-09-09 15:08:12 +00001226 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001227 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001228 return;
1229
1230 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001231 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001232 (!isa<InitListExpr>(IList->getInit(Index)) ||
1233 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001234 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001235 diag::err_flexible_array_init_nonempty)
1236 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001237 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001238 << *Field;
1239 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001240 ++Index;
1241 return;
1242 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001243 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001244 diag::ext_flexible_array_init)
1245 << IList->getInit(Index)->getSourceRange().getBegin();
1246 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1247 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001248 }
1249
Anders Carlsson6cabf312010-01-23 23:23:01 +00001250 InitializedEntity MemberEntity =
1251 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001252
Anders Carlsson6cabf312010-01-23 23:23:01 +00001253 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001255 StructuredList, StructuredIndex);
1256 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001257 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001258 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001259}
Steve Narofff8ecff22008-05-01 22:18:59 +00001260
Douglas Gregord5846a12009-04-15 06:41:24 +00001261/// \brief Expand a field designator that refers to a member of an
1262/// anonymous struct or union into a series of field designators that
1263/// refers to the field within the appropriate subobject.
1264///
Douglas Gregord5846a12009-04-15 06:41:24 +00001265static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001266 DesignatedInitExpr *DIE,
1267 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001268 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001269 typedef DesignatedInitExpr::Designator Designator;
1270
Douglas Gregord5846a12009-04-15 06:41:24 +00001271 // Build the replacement designators.
1272 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001273 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1274 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1275 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001276 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001277 DIE->getDesignator(DesigIdx)->getDotLoc(),
1278 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1279 else
1280 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1281 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001282 assert(isa<FieldDecl>(*PI));
1283 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001284 }
1285
1286 // Expand the current designator into the set of replacement
1287 // designators, so we have a full subobject path down to where the
1288 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001289 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001290 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001291}
Mike Stump11289f42009-09-09 15:08:12 +00001292
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001293/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001294/// corresponds to FieldName.
1295static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1296 IdentifierInfo *FieldName) {
1297 assert(AnonField->isAnonymousStructOrUnion());
1298 Decl *NextDecl = AnonField->getNextDeclInContext();
1299 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1300 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1301 return IF;
1302 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001303 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001304 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001305}
1306
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001307/// @brief Check the well-formedness of a C99 designated initializer.
1308///
1309/// Determines whether the designated initializer @p DIE, which
1310/// resides at the given @p Index within the initializer list @p
1311/// IList, is well-formed for a current object of type @p DeclType
1312/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001313/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001314/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001315///
1316/// @param IList The initializer list in which this designated
1317/// initializer occurs.
1318///
Douglas Gregora5324162009-04-15 04:56:10 +00001319/// @param DIE The designated initializer expression.
1320///
1321/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001322///
1323/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1324/// into which the designation in @p DIE should refer.
1325///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001326/// @param NextField If non-NULL and the first designator in @p DIE is
1327/// a field, this will be set to the field declaration corresponding
1328/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001329///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001330/// @param NextElementIndex If non-NULL and the first designator in @p
1331/// DIE is an array designator or GNU array-range designator, this
1332/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001333///
1334/// @param Index Index into @p IList where the designated initializer
1335/// @p DIE occurs.
1336///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001337/// @param StructuredList The initializer list expression that
1338/// describes all of the subobject initializers in the order they'll
1339/// actually be initialized.
1340///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001341/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001342bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001343InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001344 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001345 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001346 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001347 QualType &CurrentObjectType,
1348 RecordDecl::field_iterator *NextField,
1349 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001350 unsigned &Index,
1351 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001352 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001353 bool FinishSubobjectInit,
1354 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001355 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001356 // Check the actual initialization for the designated object type.
1357 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001358
1359 // Temporarily remove the designator expression from the
1360 // initializer list that the child calls see, so that we don't try
1361 // to re-process the designator.
1362 unsigned OldIndex = Index;
1363 IList->setInit(OldIndex, DIE->getInit());
1364
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001365 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001366 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001367
1368 // Restore the designated initializer expression in the syntactic
1369 // form of the initializer list.
1370 if (IList->getInit(OldIndex) != DIE->getInit())
1371 DIE->setInit(IList->getInit(OldIndex));
1372 IList->setInit(OldIndex, DIE);
1373
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001374 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001375 }
1376
Douglas Gregora5324162009-04-15 04:56:10 +00001377 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001378 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001379 "Need a non-designated initializer list to start from");
1380
Douglas Gregora5324162009-04-15 04:56:10 +00001381 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001382 // Determine the structural initializer list that corresponds to the
1383 // current subobject.
1384 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001385 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001386 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001387 SourceRange(D->getStartLocation(),
1388 DIE->getSourceRange().getEnd()));
1389 assert(StructuredList && "Expected a structured initializer list");
1390
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001391 if (D->isFieldDesignator()) {
1392 // C99 6.7.8p7:
1393 //
1394 // If a designator has the form
1395 //
1396 // . identifier
1397 //
1398 // then the current object (defined below) shall have
1399 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001400 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001401 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001402 if (!RT) {
1403 SourceLocation Loc = D->getDotLoc();
1404 if (Loc.isInvalid())
1405 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001406 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1407 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001408 ++Index;
1409 return true;
1410 }
1411
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001412 // Note: we perform a linear search of the fields here, despite
1413 // the fact that we have a faster lookup method, because we always
1414 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001415 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001416 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001417 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001418 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001419 Field = RT->getDecl()->field_begin(),
1420 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001421 for (; Field != FieldEnd; ++Field) {
1422 if (Field->isUnnamedBitfield())
1423 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001424
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001425 // If we find a field representing an anonymous field, look in the
1426 // IndirectFieldDecl that follow for the designated initializer.
1427 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1428 if (IndirectFieldDecl *IF =
1429 FindIndirectFieldDesignator(*Field, FieldName)) {
1430 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1431 D = DIE->getDesignator(DesigIdx);
1432 break;
1433 }
1434 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001435 if (KnownField && KnownField == *Field)
1436 break;
1437 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001438 break;
1439
1440 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001441 }
1442
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001443 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001444 // There was no normal field in the struct with the designated
1445 // name. Perform another lookup for this name, which may find
1446 // something that we can't designate (e.g., a member function),
1447 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001448 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001449 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001450 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001451 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001452 // Name lookup didn't find anything. Determine whether this
1453 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001454 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001455 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001456 TypoCorrection Corrected = SemaRef.CorrectTypo(
1457 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1458 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1459 RT->getDecl(), false, Sema::CTC_NoKeywords);
1460 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001461 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001462 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001463 std::string CorrectedStr(
1464 Corrected.getAsString(SemaRef.getLangOptions()));
1465 std::string CorrectedQuotedStr(
1466 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001468 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001469 << FieldName << CurrentObjectType << CorrectedQuotedStr
1470 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001471 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001472 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001473 } else {
1474 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1475 << FieldName << CurrentObjectType;
1476 ++Index;
1477 return true;
1478 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001481 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001482 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001483 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001484 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001485 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001486 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001487 ++Index;
1488 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001489 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001490
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001491 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001492 // The replacement field comes from typo correction; find it
1493 // in the list of fields.
1494 FieldIndex = 0;
1495 Field = RT->getDecl()->field_begin();
1496 for (; Field != FieldEnd; ++Field) {
1497 if (Field->isUnnamedBitfield())
1498 continue;
1499
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001500 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001501 Field->getIdentifier() == ReplacementField->getIdentifier())
1502 break;
1503
1504 ++FieldIndex;
1505 }
1506 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001507 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001508
1509 // All of the fields of a union are located at the same place in
1510 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001511 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001512 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001513 StructuredList->setInitializedFieldInUnion(*Field);
1514 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001515
Douglas Gregora82064c2011-06-29 21:51:31 +00001516 // Make sure we can use this declaration.
1517 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1518 ++Index;
1519 return true;
1520 }
1521
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001522 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001523 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001524
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001525 // Make sure that our non-designated initializer list has space
1526 // for a subobject corresponding to this field.
1527 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001528 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001529
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001530 // This designator names a flexible array member.
1531 if (Field->getType()->isIncompleteArrayType()) {
1532 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001533 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001534 // We can't designate an object within the flexible array
1535 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001536 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001537 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001538 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001539 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001540 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001541 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001542 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001543 << *Field;
1544 Invalid = true;
1545 }
1546
Chris Lattner001b29c2010-10-10 17:49:49 +00001547 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1548 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001549 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001550 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001551 diag::err_flexible_array_init_needs_braces)
1552 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001553 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001554 << *Field;
1555 Invalid = true;
1556 }
1557
1558 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001559 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001560 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001561 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001562 diag::err_flexible_array_init_nonempty)
1563 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001564 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001565 << *Field;
1566 Invalid = true;
1567 }
1568
1569 if (Invalid) {
1570 ++Index;
1571 return true;
1572 }
1573
1574 // Initialize the array.
1575 bool prevHadError = hadError;
1576 unsigned newStructuredIndex = FieldIndex;
1577 unsigned OldIndex = Index;
1578 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001579
1580 InitializedEntity MemberEntity =
1581 InitializedEntity::InitializeMember(*Field, &Entity);
1582 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001583 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001584
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001585 IList->setInit(OldIndex, DIE);
1586 if (hadError && !prevHadError) {
1587 ++Field;
1588 ++FieldIndex;
1589 if (NextField)
1590 *NextField = Field;
1591 StructuredIndex = FieldIndex;
1592 return true;
1593 }
1594 } else {
1595 // Recurse to check later designated subobjects.
1596 QualType FieldType = (*Field)->getType();
1597 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001598
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001599 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001600 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001601 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1602 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001603 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001604 true, false))
1605 return true;
1606 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001607
1608 // Find the position of the next field to be initialized in this
1609 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001610 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001611 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001612
1613 // If this the first designator, our caller will continue checking
1614 // the rest of this struct/class/union subobject.
1615 if (IsFirstDesignator) {
1616 if (NextField)
1617 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001618 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001619 return false;
1620 }
1621
Douglas Gregor17bd0942009-01-28 23:36:17 +00001622 if (!FinishSubobjectInit)
1623 return false;
1624
Douglas Gregord5846a12009-04-15 06:41:24 +00001625 // We've already initialized something in the union; we're done.
1626 if (RT->getDecl()->isUnion())
1627 return hadError;
1628
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001629 // Check the remaining fields within this class/struct/union subobject.
1630 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631
Anders Carlsson6cabf312010-01-23 23:23:01 +00001632 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001633 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001634 return hadError && !prevHadError;
1635 }
1636
1637 // C99 6.7.8p6:
1638 //
1639 // If a designator has the form
1640 //
1641 // [ constant-expression ]
1642 //
1643 // then the current object (defined below) shall have array
1644 // type and the expression shall be an integer constant
1645 // expression. If the array is of unknown size, any
1646 // nonnegative value is valid.
1647 //
1648 // Additionally, cope with the GNU extension that permits
1649 // designators of the form
1650 //
1651 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001652 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001653 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001654 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001655 << CurrentObjectType;
1656 ++Index;
1657 return true;
1658 }
1659
1660 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001661 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1662 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001663 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001664 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001665 DesignatedEndIndex = DesignatedStartIndex;
1666 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001667 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001668
Mike Stump11289f42009-09-09 15:08:12 +00001669 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001670 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001671 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001672 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001673 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001674
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001675 // Codegen can't handle evaluating array range designators that have side
1676 // effects, because we replicate the AST value for each initialized element.
1677 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1678 // elements with something that has a side effect, so codegen can emit an
1679 // "error unsupported" error instead of miscompiling the app.
1680 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1681 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001682 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001683 }
1684
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001685 if (isa<ConstantArrayType>(AT)) {
1686 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001687 DesignatedStartIndex
1688 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001689 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001690 DesignatedEndIndex
1691 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001692 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1693 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001694 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001695 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001696 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001697 << IndexExpr->getSourceRange();
1698 ++Index;
1699 return true;
1700 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001701 } else {
1702 // Make sure the bit-widths and signedness match.
1703 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001704 DesignatedEndIndex
1705 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001706 else if (DesignatedStartIndex.getBitWidth() <
1707 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001708 DesignatedStartIndex
1709 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001710 DesignatedStartIndex.setIsUnsigned(true);
1711 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001714 // Make sure that our non-designated initializer list has space
1715 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001716 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001717 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001718 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001719
Douglas Gregor17bd0942009-01-28 23:36:17 +00001720 // Repeatedly perform subobject initializations in the range
1721 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001722
Douglas Gregor17bd0942009-01-28 23:36:17 +00001723 // Move to the next designator
1724 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1725 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001727 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001728 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001729
Douglas Gregor17bd0942009-01-28 23:36:17 +00001730 while (DesignatedStartIndex <= DesignatedEndIndex) {
1731 // Recurse to check later designated subobjects.
1732 QualType ElementType = AT->getElementType();
1733 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001735 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1737 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001738 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001739 (DesignatedStartIndex == DesignatedEndIndex),
1740 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001741 return true;
1742
1743 // Move to the next index in the array that we'll be initializing.
1744 ++DesignatedStartIndex;
1745 ElementIndex = DesignatedStartIndex.getZExtValue();
1746 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001747
1748 // If this the first designator, our caller will continue checking
1749 // the rest of this array subobject.
1750 if (IsFirstDesignator) {
1751 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001752 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001753 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001754 return false;
1755 }
Mike Stump11289f42009-09-09 15:08:12 +00001756
Douglas Gregor17bd0942009-01-28 23:36:17 +00001757 if (!FinishSubobjectInit)
1758 return false;
1759
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001760 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001761 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001762 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001763 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001764 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001765 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001766}
1767
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001768// Get the structured initializer list for a subobject of type
1769// @p CurrentObjectType.
1770InitListExpr *
1771InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1772 QualType CurrentObjectType,
1773 InitListExpr *StructuredList,
1774 unsigned StructuredIndex,
1775 SourceRange InitRange) {
1776 Expr *ExistingInit = 0;
1777 if (!StructuredList)
1778 ExistingInit = SyntacticToSemantic[IList];
1779 else if (StructuredIndex < StructuredList->getNumInits())
1780 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001781
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001782 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1783 return Result;
1784
1785 if (ExistingInit) {
1786 // We are creating an initializer list that initializes the
1787 // subobjects of the current object, but there was already an
1788 // initialization that completely initialized the current
1789 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001790 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001791 // struct X { int a, b; };
1792 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001793 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1795 // designated initializer re-initializes the whole
1796 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001797 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001798 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001799 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001800 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001801 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001802 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001803 << ExistingInit->getSourceRange();
1804 }
1805
Mike Stump11289f42009-09-09 15:08:12 +00001806 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001807 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1808 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001809 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001810
Douglas Gregora8a089b2010-07-13 18:40:04 +00001811 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001812
Douglas Gregor6d00c992009-03-20 23:58:33 +00001813 // Pre-allocate storage for the structured initializer list.
1814 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001815 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001816 bool GotNumInits = false;
1817 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001818 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001819 GotNumInits = true;
1820 } else if (Index < IList->getNumInits()) {
1821 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001822 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001823 GotNumInits = true;
1824 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00001825 }
1826
Mike Stump11289f42009-09-09 15:08:12 +00001827 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001828 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1829 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1830 NumElements = CAType->getSize().getZExtValue();
1831 // Simple heuristic so that we don't allocate a very large
1832 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001833 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001834 NumElements = 0;
1835 }
John McCall9dd450b2009-09-21 23:43:11 +00001836 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001837 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001838 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001839 RecordDecl *RDecl = RType->getDecl();
1840 if (RDecl->isUnion())
1841 NumElements = 1;
1842 else
Mike Stump11289f42009-09-09 15:08:12 +00001843 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001844 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001845 }
1846
Douglas Gregor221c9a52009-03-21 18:13:52 +00001847 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001848 NumElements = IList->getNumInits();
1849
Ted Kremenekac034612010-04-13 23:39:13 +00001850 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001851
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001852 // Link this new initializer list into the structured initializer
1853 // lists.
1854 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001855 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001856 else {
1857 Result->setSyntacticForm(IList);
1858 SyntacticToSemantic[IList] = Result;
1859 }
1860
1861 return Result;
1862}
1863
1864/// Update the initializer at index @p StructuredIndex within the
1865/// structured initializer list to the value @p expr.
1866void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1867 unsigned &StructuredIndex,
1868 Expr *expr) {
1869 // No structured initializer list to update
1870 if (!StructuredList)
1871 return;
1872
Ted Kremenekac034612010-04-13 23:39:13 +00001873 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1874 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001875 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001876 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001877 diag::warn_initializer_overrides)
1878 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001879 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001880 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001881 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001882 << PrevInit->getSourceRange();
1883 }
Mike Stump11289f42009-09-09 15:08:12 +00001884
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001885 ++StructuredIndex;
1886}
1887
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001888/// Check that the given Index expression is a valid array designator
1889/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001890/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001891/// and produces a reasonable diagnostic if there is a
1892/// failure. Returns true if there was an error, false otherwise. If
1893/// everything went okay, Value will receive the value of the constant
1894/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001895static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001896CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001897 SourceLocation Loc = Index->getSourceRange().getBegin();
1898
1899 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001900 if (S.VerifyIntegerConstantExpression(Index, &Value))
1901 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001902
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001903 if (Value.isSigned() && Value.isNegative())
1904 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905 << Value.toString(10) << Index->getSourceRange();
1906
Douglas Gregor51650d32009-01-23 21:04:18 +00001907 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001908 return false;
1909}
1910
John McCalldadc5752010-08-24 06:29:42 +00001911ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001912 SourceLocation Loc,
1913 bool GNUSyntax,
1914 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001915 typedef DesignatedInitExpr::Designator ASTDesignator;
1916
1917 bool Invalid = false;
1918 llvm::SmallVector<ASTDesignator, 32> Designators;
1919 llvm::SmallVector<Expr *, 32> InitExpressions;
1920
1921 // Build designators and check array designator expressions.
1922 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1923 const Designator &D = Desig.getDesignator(Idx);
1924 switch (D.getKind()) {
1925 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001926 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001927 D.getFieldLoc()));
1928 break;
1929
1930 case Designator::ArrayDesignator: {
1931 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1932 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001933 if (!Index->isTypeDependent() &&
1934 !Index->isValueDependent() &&
1935 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001936 Invalid = true;
1937 else {
1938 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001939 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001940 D.getRBracketLoc()));
1941 InitExpressions.push_back(Index);
1942 }
1943 break;
1944 }
1945
1946 case Designator::ArrayRangeDesignator: {
1947 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1948 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1949 llvm::APSInt StartValue;
1950 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001951 bool StartDependent = StartIndex->isTypeDependent() ||
1952 StartIndex->isValueDependent();
1953 bool EndDependent = EndIndex->isTypeDependent() ||
1954 EndIndex->isValueDependent();
1955 if ((!StartDependent &&
1956 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1957 (!EndDependent &&
1958 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001959 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001960 else {
1961 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001962 if (StartDependent || EndDependent) {
1963 // Nothing to compute.
1964 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001965 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001966 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001967 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001968
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001969 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001970 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001971 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001972 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1973 Invalid = true;
1974 } else {
1975 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001976 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001977 D.getEllipsisLoc(),
1978 D.getRBracketLoc()));
1979 InitExpressions.push_back(StartIndex);
1980 InitExpressions.push_back(EndIndex);
1981 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001982 }
1983 break;
1984 }
1985 }
1986 }
1987
1988 if (Invalid || Init.isInvalid())
1989 return ExprError();
1990
1991 // Clear out the expressions within the designation.
1992 Desig.ClearExprs(*this);
1993
1994 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001995 = DesignatedInitExpr::Create(Context,
1996 Designators.data(), Designators.size(),
1997 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001998 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999
Douglas Gregorc124e592011-01-16 16:13:16 +00002000 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002001 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2002 << DIE->getSourceRange();
2003 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002004 Diag(DIE->getLocStart(), diag::ext_designated_init)
2005 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002007 return Owned(DIE);
2008}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002009
Douglas Gregor723796a2009-12-16 06:35:08 +00002010bool Sema::CheckInitList(const InitializedEntity &Entity,
2011 InitListExpr *&InitList, QualType &DeclType) {
2012 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00002013 if (!CheckInitList.HadError())
2014 InitList = CheckInitList.getFullyStructuredList();
2015
2016 return CheckInitList.HadError();
2017}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00002018
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002019//===----------------------------------------------------------------------===//
2020// Initialization entity
2021//===----------------------------------------------------------------------===//
2022
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002023InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002024 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002026{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002027 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2028 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002029 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002030 } else {
2031 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002032 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002033 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002034}
2035
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002036InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002037 CXXBaseSpecifier *Base,
2038 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002039{
2040 InitializedEntity Result;
2041 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002042 Result.Base = reinterpret_cast<uintptr_t>(Base);
2043 if (IsInheritedVirtualBase)
2044 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002045
Douglas Gregor1b303932009-12-22 15:35:07 +00002046 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002047 return Result;
2048}
2049
Douglas Gregor85dabae2009-12-16 01:38:02 +00002050DeclarationName InitializedEntity::getName() const {
2051 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002052 case EK_Parameter: {
2053 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2054 return (D ? D->getDeclName() : DeclarationName());
2055 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002056
2057 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002058 case EK_Member:
2059 return VariableOrMember->getDeclName();
2060
2061 case EK_Result:
2062 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002063 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002064 case EK_Temporary:
2065 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002066 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002067 case EK_ArrayElement:
2068 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002069 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002070 return DeclarationName();
2071 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072
Douglas Gregor85dabae2009-12-16 01:38:02 +00002073 // Silence GCC warning
2074 return DeclarationName();
2075}
2076
Douglas Gregora4b592a2009-12-19 03:01:41 +00002077DeclaratorDecl *InitializedEntity::getDecl() const {
2078 switch (getKind()) {
2079 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002080 case EK_Member:
2081 return VariableOrMember;
2082
John McCall31168b02011-06-15 23:02:42 +00002083 case EK_Parameter:
2084 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2085
Douglas Gregora4b592a2009-12-19 03:01:41 +00002086 case EK_Result:
2087 case EK_Exception:
2088 case EK_New:
2089 case EK_Temporary:
2090 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002091 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002092 case EK_ArrayElement:
2093 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002094 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002095 return 0;
2096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097
Douglas Gregora4b592a2009-12-19 03:01:41 +00002098 // Silence GCC warning
2099 return 0;
2100}
2101
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002102bool InitializedEntity::allowsNRVO() const {
2103 switch (getKind()) {
2104 case EK_Result:
2105 case EK_Exception:
2106 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002108 case EK_Variable:
2109 case EK_Parameter:
2110 case EK_Member:
2111 case EK_New:
2112 case EK_Temporary:
2113 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002114 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002115 case EK_ArrayElement:
2116 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002117 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002118 break;
2119 }
2120
2121 return false;
2122}
2123
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002124//===----------------------------------------------------------------------===//
2125// Initialization sequence
2126//===----------------------------------------------------------------------===//
2127
2128void InitializationSequence::Step::Destroy() {
2129 switch (Kind) {
2130 case SK_ResolveAddressOfOverloadedFunction:
2131 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002132 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002133 case SK_CastDerivedToBaseLValue:
2134 case SK_BindReference:
2135 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002136 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002137 case SK_UserConversion:
2138 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002139 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002140 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002141 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002142 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002143 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002144 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002145 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002146 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002147 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002148 case SK_PassByIndirectCopyRestore:
2149 case SK_PassByIndirectRestore:
2150 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002151 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002152
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002153 case SK_ConversionSequence:
2154 delete ICS;
2155 }
2156}
2157
Douglas Gregor838fcc32010-03-26 20:14:36 +00002158bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002159 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002160}
2161
2162bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002163 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002164 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002165
Douglas Gregor838fcc32010-03-26 20:14:36 +00002166 switch (getFailureKind()) {
2167 case FK_TooManyInitsForReference:
2168 case FK_ArrayNeedsInitList:
2169 case FK_ArrayNeedsInitListOrStringLiteral:
2170 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2171 case FK_NonConstLValueReferenceBindingToTemporary:
2172 case FK_NonConstLValueReferenceBindingToUnrelated:
2173 case FK_RValueReferenceBindingToLValue:
2174 case FK_ReferenceInitDropsQualifiers:
2175 case FK_ReferenceInitFailed:
2176 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002177 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002178 case FK_TooManyInitsForScalar:
2179 case FK_ReferenceBindingToInitList:
2180 case FK_InitListBadDestinationType:
2181 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002182 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002183 case FK_ArrayTypeMismatch:
2184 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002185 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186
Douglas Gregor838fcc32010-03-26 20:14:36 +00002187 case FK_ReferenceInitOverloadFailed:
2188 case FK_UserConversionOverloadFailed:
2189 case FK_ConstructorOverloadFailed:
2190 return FailedOverloadResult == OR_Ambiguous;
2191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002192
Douglas Gregor838fcc32010-03-26 20:14:36 +00002193 return false;
2194}
2195
Douglas Gregorb33eed02010-04-16 22:09:46 +00002196bool InitializationSequence::isConstructorInitialization() const {
2197 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2198}
2199
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002200void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002201 FunctionDecl *Function,
2202 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002203 Step S;
2204 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2205 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002206 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002207 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002208 Steps.push_back(S);
2209}
2210
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002211void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002212 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002213 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002214 switch (VK) {
2215 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2216 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2217 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002218 default: llvm_unreachable("No such category");
2219 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002220 S.Type = BaseType;
2221 Steps.push_back(S);
2222}
2223
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002224void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002225 bool BindingTemporary) {
2226 Step S;
2227 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2228 S.Type = T;
2229 Steps.push_back(S);
2230}
2231
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002232void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2233 Step S;
2234 S.Kind = SK_ExtraneousCopyToTemporary;
2235 S.Type = T;
2236 Steps.push_back(S);
2237}
2238
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002239void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002240 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002241 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002242 Step S;
2243 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002244 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002245 S.Function.Function = Function;
2246 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002247 Steps.push_back(S);
2248}
2249
2250void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002251 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002252 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002253 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002254 switch (VK) {
2255 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002256 S.Kind = SK_QualificationConversionRValue;
2257 break;
John McCall2536c6d2010-08-25 10:28:54 +00002258 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002259 S.Kind = SK_QualificationConversionXValue;
2260 break;
John McCall2536c6d2010-08-25 10:28:54 +00002261 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002262 S.Kind = SK_QualificationConversionLValue;
2263 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002264 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002265 S.Type = Ty;
2266 Steps.push_back(S);
2267}
2268
2269void InitializationSequence::AddConversionSequenceStep(
2270 const ImplicitConversionSequence &ICS,
2271 QualType T) {
2272 Step S;
2273 S.Kind = SK_ConversionSequence;
2274 S.Type = T;
2275 S.ICS = new ImplicitConversionSequence(ICS);
2276 Steps.push_back(S);
2277}
2278
Douglas Gregor51e77d52009-12-10 17:56:55 +00002279void InitializationSequence::AddListInitializationStep(QualType T) {
2280 Step S;
2281 S.Kind = SK_ListInitialization;
2282 S.Type = T;
2283 Steps.push_back(S);
2284}
2285
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002286void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002287InitializationSequence::AddConstructorInitializationStep(
2288 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002289 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002290 QualType T) {
2291 Step S;
2292 S.Kind = SK_ConstructorInitialization;
2293 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002294 S.Function.Function = Constructor;
2295 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002296 Steps.push_back(S);
2297}
2298
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002299void InitializationSequence::AddZeroInitializationStep(QualType T) {
2300 Step S;
2301 S.Kind = SK_ZeroInitialization;
2302 S.Type = T;
2303 Steps.push_back(S);
2304}
2305
Douglas Gregore1314a62009-12-18 05:02:21 +00002306void InitializationSequence::AddCAssignmentStep(QualType T) {
2307 Step S;
2308 S.Kind = SK_CAssignment;
2309 S.Type = T;
2310 Steps.push_back(S);
2311}
2312
Eli Friedman78275202009-12-19 08:11:05 +00002313void InitializationSequence::AddStringInitStep(QualType T) {
2314 Step S;
2315 S.Kind = SK_StringInit;
2316 S.Type = T;
2317 Steps.push_back(S);
2318}
2319
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002320void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2321 Step S;
2322 S.Kind = SK_ObjCObjectConversion;
2323 S.Type = T;
2324 Steps.push_back(S);
2325}
2326
Douglas Gregore2f943b2011-02-22 18:29:51 +00002327void InitializationSequence::AddArrayInitStep(QualType T) {
2328 Step S;
2329 S.Kind = SK_ArrayInit;
2330 S.Type = T;
2331 Steps.push_back(S);
2332}
2333
John McCall31168b02011-06-15 23:02:42 +00002334void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2335 bool shouldCopy) {
2336 Step s;
2337 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2338 : SK_PassByIndirectRestore);
2339 s.Type = type;
2340 Steps.push_back(s);
2341}
2342
2343void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2344 Step S;
2345 S.Kind = SK_ProduceObjCObject;
2346 S.Type = T;
2347 Steps.push_back(S);
2348}
2349
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002350void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002351 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002352 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002353 this->Failure = Failure;
2354 this->FailedOverloadResult = Result;
2355}
2356
2357//===----------------------------------------------------------------------===//
2358// Attempt initialization
2359//===----------------------------------------------------------------------===//
2360
John McCall31168b02011-06-15 23:02:42 +00002361static void MaybeProduceObjCObject(Sema &S,
2362 InitializationSequence &Sequence,
2363 const InitializedEntity &Entity) {
2364 if (!S.getLangOptions().ObjCAutoRefCount) return;
2365
2366 /// When initializing a parameter, produce the value if it's marked
2367 /// __attribute__((ns_consumed)).
2368 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2369 if (!Entity.isParameterConsumed())
2370 return;
2371
2372 assert(Entity.getType()->isObjCRetainableType() &&
2373 "consuming an object of unretainable type?");
2374 Sequence.AddProduceObjCObjectStep(Entity.getType());
2375
2376 /// When initializing a return value, if the return type is a
2377 /// retainable type, then returns need to immediately retain the
2378 /// object. If an autorelease is required, it will be done at the
2379 /// last instant.
2380 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2381 if (!Entity.getType()->isObjCRetainableType())
2382 return;
2383
2384 Sequence.AddProduceObjCObjectStep(Entity.getType());
2385 }
2386}
2387
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002388/// \brief Attempt list initialization (C++0x [dcl.init.list])
2389static void TryListInitialization(Sema &S,
2390 const InitializedEntity &Entity,
2391 const InitializationKind &Kind,
2392 InitListExpr *InitList,
2393 InitializationSequence &Sequence) {
2394 // FIXME: We only perform rudimentary checking of list
2395 // initializations at this point, then assume that any list
2396 // initialization of an array, aggregate, or scalar will be
2397 // well-formed. When we actually "perform" list initialization, we'll
2398 // do all of the necessary checking. C++0x initializer lists will
2399 // force us to perform more checking here.
2400
2401 QualType DestType = Entity.getType();
2402
2403 // C++ [dcl.init]p13:
2404 // If T is a scalar type, then a declaration of the form
2405 //
2406 // T x = { a };
2407 //
2408 // is equivalent to
2409 //
2410 // T x = a;
2411 if (DestType->isScalarType()) {
2412 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2413 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2414 return;
2415 }
2416
2417 // Assume scalar initialization from a single value works.
2418 } else if (DestType->isAggregateType()) {
2419 // Assume aggregate initialization works.
2420 } else if (DestType->isVectorType()) {
2421 // Assume vector initialization works.
2422 } else if (DestType->isReferenceType()) {
2423 // FIXME: C++0x defines behavior for this.
2424 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2425 return;
2426 } else if (DestType->isRecordType()) {
2427 // FIXME: C++0x defines behavior for this
2428 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2429 }
2430
2431 // Add a general "list initialization" step.
2432 Sequence.AddListInitializationStep(DestType);
2433}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002434
2435/// \brief Try a reference initialization that involves calling a conversion
2436/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002437static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2438 const InitializedEntity &Entity,
2439 const InitializationKind &Kind,
2440 Expr *Initializer,
2441 bool AllowRValues,
2442 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002443 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002444 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2445 QualType T1 = cv1T1.getUnqualifiedType();
2446 QualType cv2T2 = Initializer->getType();
2447 QualType T2 = cv2T2.getUnqualifiedType();
2448
2449 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002450 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002451 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002453 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002454 ObjCConversion,
2455 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002456 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002457 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002458 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002459 (void)ObjCLifetimeConversion;
2460
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002461 // Build the candidate set directly in the initialization sequence
2462 // structure, so that it will persist if we fail.
2463 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2464 CandidateSet.clear();
2465
2466 // Determine whether we are allowed to call explicit constructors or
2467 // explicit conversion operators.
2468 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002469
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002470 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002471 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2472 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002473 // The type we're converting to is a class type. Enumerate its constructors
2474 // to see if there is a suitable conversion.
2475 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002476
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002478 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002479 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002480 NamedDecl *D = *Con;
2481 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2482
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 // Find the constructor (which may be a template).
2484 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002485 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002486 if (ConstructorTmpl)
2487 Constructor = cast<CXXConstructorDecl>(
2488 ConstructorTmpl->getTemplatedDecl());
2489 else
John McCalla0296f72010-03-19 07:35:19 +00002490 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002491
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002492 if (!Constructor->isInvalidDecl() &&
2493 Constructor->isConvertingConstructor(AllowExplicit)) {
2494 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002495 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002496 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002497 &Initializer, 1, CandidateSet,
2498 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 else
John McCalla0296f72010-03-19 07:35:19 +00002500 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002501 &Initializer, 1, CandidateSet,
2502 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002504 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002505 }
John McCall3696dcb2010-08-17 07:23:57 +00002506 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2507 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002508
Douglas Gregor496e8b342010-05-07 19:42:26 +00002509 const RecordType *T2RecordType = 0;
2510 if ((T2RecordType = T2->getAs<RecordType>()) &&
2511 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002512 // The type we're converting from is a class type, enumerate its conversion
2513 // functions.
2514 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2515
John McCallad371252010-01-20 00:46:10 +00002516 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002517 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002518 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2519 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002520 NamedDecl *D = *I;
2521 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2522 if (isa<UsingShadowDecl>(D))
2523 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002525 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2526 CXXConversionDecl *Conv;
2527 if (ConvTemplate)
2528 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2529 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002530 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002531
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002532 // If the conversion function doesn't return a reference type,
2533 // it can't be considered for this conversion unless we're allowed to
2534 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002535 // FIXME: Do we need to make sure that we only consider conversion
2536 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002537 // break recursion.
2538 if ((AllowExplicit || !Conv->isExplicit()) &&
2539 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2540 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002541 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002542 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002543 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002544 else
John McCalla0296f72010-03-19 07:35:19 +00002545 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002546 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002547 }
2548 }
2549 }
John McCall3696dcb2010-08-17 07:23:57 +00002550 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2551 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002553 SourceLocation DeclLoc = Initializer->getLocStart();
2554
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002555 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002556 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002558 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002559 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002560
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002561 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002562
Chandler Carruth30141632011-02-25 19:41:05 +00002563 // This is the overload that will actually be used for the initialization, so
2564 // mark it as used.
2565 S.MarkDeclarationReferenced(DeclLoc, Function);
2566
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002567 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002568 if (isa<CXXConversionDecl>(Function))
2569 T2 = Function->getResultType();
2570 else
2571 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002572
2573 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002574 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002575 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002576
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002577 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002578 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002579 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002580 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002581 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002582 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002583 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002584
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002585 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002586 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002587 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002588 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002589 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002590 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002591 NewDerivedToBase, NewObjCConversion,
2592 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002593 if (NewRefRelationship == Sema::Ref_Incompatible) {
2594 // If the type we've converted to is not reference-related to the
2595 // type we're looking for, then there is another conversion step
2596 // we need to perform to produce a temporary of the right type
2597 // that we'll be binding to.
2598 ImplicitConversionSequence ICS;
2599 ICS.setStandard();
2600 ICS.Standard = Best->FinalConversion;
2601 T2 = ICS.Standard.getToType(2);
2602 Sequence.AddConversionSequenceStep(ICS, T2);
2603 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002604 Sequence.AddDerivedToBaseCastStep(
2605 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002607 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002608 else if (NewObjCConversion)
2609 Sequence.AddObjCObjectConversionStep(
2610 S.Context.getQualifiedType(T1,
2611 T2.getNonReferenceType().getQualifiers()));
2612
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002613 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002614 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002615
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002616 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2617 return OR_Success;
2618}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002619
2620/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2621static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002622 const InitializedEntity &Entity,
2623 const InitializationKind &Kind,
2624 Expr *Initializer,
2625 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002626 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002627 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002628 Qualifiers T1Quals;
2629 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002630 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002631 Qualifiers T2Quals;
2632 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002633 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002634
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002635 // If the initializer is the address of an overloaded function, try
2636 // to resolve the overloaded function. If all goes well, T2 is the
2637 // type of the resulting function.
2638 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002639 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002640 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002641 T1,
2642 false,
2643 Found)) {
2644 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2645 cv2T2 = Fn->getType();
2646 T2 = cv2T2.getUnqualifiedType();
2647 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002648 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2649 return;
2650 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002651 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002652
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653 // Compute some basic properties of the types and the initializer.
2654 bool isLValueRef = DestType->isLValueReferenceType();
2655 bool isRValueRef = !isLValueRef;
2656 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002657 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002658 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002659 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002660 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002661 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002662 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002663
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002664 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002666 // "cv2 T2" as follows:
2667 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002668 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002669 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002670 // Note the analogous bullet points for rvlaue refs to functions. Because
2671 // there are no function rvalues in C++, rvalue refs to functions are treated
2672 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002673 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002674 bool T1Function = T1->isFunctionType();
2675 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002676 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002677 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002678 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002679 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002680 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002681 // reference-compatible with "cv2 T2," or
2682 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002683 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002684 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002685 // can occur. However, we do pay attention to whether it is a bit-field
2686 // to decide whether we're actually binding to a temporary created from
2687 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002688 if (DerivedToBase)
2689 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002690 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002691 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002692 else if (ObjCConversion)
2693 Sequence.AddObjCObjectConversionStep(
2694 S.Context.getQualifiedType(T1, T2Quals));
2695
Chandler Carruth04bdce62010-01-12 20:32:25 +00002696 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002697 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002698 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002699 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002700 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002701 return;
2702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703
2704 // - has a class type (i.e., T2 is a class type), where T1 is not
2705 // reference-related to T2, and can be implicitly converted to an
2706 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2707 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002708 // applicable conversion functions (13.3.1.6) and choosing the best
2709 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002710 // If we have an rvalue ref to function type here, the rhs must be
2711 // an rvalue.
2712 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2713 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002714 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002715 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002716 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002717 Sequence);
2718 if (ConvOvlResult == OR_Success)
2719 return;
John McCall0d1da222010-01-12 00:44:57 +00002720 if (ConvOvlResult != OR_No_Viable_Function) {
2721 Sequence.SetOverloadFailure(
2722 InitializationSequence::FK_ReferenceInitOverloadFailed,
2723 ConvOvlResult);
2724 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002725 }
2726 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002727
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002728 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002729 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002730 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002731 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002732 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2733 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2734 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002735 Sequence.SetOverloadFailure(
2736 InitializationSequence::FK_ReferenceInitOverloadFailed,
2737 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002738 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002739 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002740 ? (RefRelationship == Sema::Ref_Related
2741 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2742 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2743 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002744
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002745 return;
2746 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002747
Douglas Gregor92e460e2011-01-20 16:44:54 +00002748 // - If the initializer expression
2749 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2750 // "cv1 T1" is reference-compatible with "cv2 T2"
2751 // Note: functions are handled below.
2752 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002753 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002754 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002755 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002756 (InitCategory.isXValue() ||
2757 (InitCategory.isPRValue() && T2->isRecordType()) ||
2758 (InitCategory.isPRValue() && T2->isArrayType()))) {
2759 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2760 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002761 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2762 // compiler the freedom to perform a copy here or bind to the
2763 // object, while C++0x requires that we bind directly to the
2764 // object. Hence, we always bind to the object without making an
2765 // extra copy. However, in C++03 requires that we check for the
2766 // presence of a suitable copy constructor:
2767 //
2768 // The constructor that would be used to make the copy shall
2769 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002770 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002771 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002773
Douglas Gregor92e460e2011-01-20 16:44:54 +00002774 if (DerivedToBase)
2775 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2776 ValueKind);
2777 else if (ObjCConversion)
2778 Sequence.AddObjCObjectConversionStep(
2779 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780
Douglas Gregor92e460e2011-01-20 16:44:54 +00002781 if (T1Quals != T2Quals)
2782 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002783 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002784 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002785 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002787
2788 // - has a class type (i.e., T2 is a class type), where T1 is not
2789 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002790 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2791 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002792 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002793 if (RefRelationship == Sema::Ref_Incompatible) {
2794 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2795 Kind, Initializer,
2796 /*AllowRValues=*/true,
2797 Sequence);
2798 if (ConvOvlResult)
2799 Sequence.SetOverloadFailure(
2800 InitializationSequence::FK_ReferenceInitOverloadFailed,
2801 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002802
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002803 return;
2804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002806 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2807 return;
2808 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002809
2810 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002811 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002813 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002814
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002815 // Determine whether we are allowed to call explicit constructors or
2816 // explicit conversion operators.
2817 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002818
2819 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2820
John McCall31168b02011-06-15 23:02:42 +00002821 ImplicitConversionSequence ICS
2822 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00002823 /*SuppressUserConversions*/ false,
2824 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002825 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00002826 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2827 /*AllowObjCWritebackConversion=*/false);
2828
2829 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002830 // FIXME: Use the conversion function set stored in ICS to turn
2831 // this into an overloading ambiguity diagnostic. However, we need
2832 // to keep that set as an OverloadCandidateSet rather than as some
2833 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002834 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2835 Sequence.SetOverloadFailure(
2836 InitializationSequence::FK_ReferenceInitOverloadFailed,
2837 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002838 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2839 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002840 else
2841 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002842 return;
John McCall31168b02011-06-15 23:02:42 +00002843 } else {
2844 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002845 }
2846
2847 // [...] If T1 is reference-related to T2, cv1 must be the
2848 // same cv-qualification as, or greater cv-qualification
2849 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002850 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2851 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002852 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002853 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002854 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2855 return;
2856 }
2857
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002858 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002859 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002860 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002861 InitCategory.isLValue()) {
2862 Sequence.SetFailed(
2863 InitializationSequence::FK_RValueReferenceBindingToLValue);
2864 return;
2865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002867 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2868 return;
2869}
2870
2871/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002872/// (C++ [dcl.init.string], C99 6.7.8).
2873static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002874 const InitializedEntity &Entity,
2875 const InitializationKind &Kind,
2876 Expr *Initializer,
2877 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002878 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002879}
2880
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002881/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2882/// enumerates the constructors of the initialized entity and performs overload
2883/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002884static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002885 const InitializedEntity &Entity,
2886 const InitializationKind &Kind,
2887 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002888 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002889 InitializationSequence &Sequence) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002890 // Build the candidate set directly in the initialization sequence
2891 // structure, so that it will persist if we fail.
2892 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2893 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002894
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002895 // Determine whether we are allowed to call explicit constructors or
2896 // explicit conversion operators.
2897 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2898 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002899 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002900
2901 // The type we're constructing needs to be complete.
2902 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002903 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002904 return;
2905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002906
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002907 // The type we're converting to is a class type. Enumerate its constructors
2908 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002909 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002910 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002911 CXXRecordDecl *DestRecordDecl
2912 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002914 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002915 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002916 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002917 NamedDecl *D = *Con;
2918 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002919 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002920
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002921 // Find the constructor (which may be a template).
2922 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002923 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002924 if (ConstructorTmpl)
2925 Constructor = cast<CXXConstructorDecl>(
2926 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002927 else {
John McCalla0296f72010-03-19 07:35:19 +00002928 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002929
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00002931 // suppress user-defined conversions on the arguments.
2932 // FIXME: Move constructors?
2933 if (Kind.getKind() == InitializationKind::IK_Copy &&
2934 Constructor->isCopyConstructor())
2935 SuppressUserConversions = true;
2936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002937
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002938 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002939 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002940 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002941 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002942 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002943 Args, NumArgs, CandidateSet,
2944 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002945 else
John McCalla0296f72010-03-19 07:35:19 +00002946 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002947 Args, NumArgs, CandidateSet,
2948 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950 }
2951
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002952 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002953
2954 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002955 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002957 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002958 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002960 Result);
2961 return;
2962 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002963
2964 // C++0x [dcl.init]p6:
2965 // If a program calls for the default initialization of an object
2966 // of a const-qualified type T, T shall be a class type with a
2967 // user-provided default constructor.
2968 if (Kind.getKind() == InitializationKind::IK_Default &&
2969 Entity.getType().isConstQualified() &&
2970 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2971 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2972 return;
2973 }
2974
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002975 // Add the constructor initialization step. Any cv-qualification conversion is
2976 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002977 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002979 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002980 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002981}
2982
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002983/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002985 const InitializedEntity &Entity,
2986 const InitializationKind &Kind,
2987 InitializationSequence &Sequence) {
2988 // C++ [dcl.init]p5:
2989 //
2990 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002991 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002992
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002993 // -- if T is an array type, then each element is value-initialized;
2994 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2995 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002996
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002997 if (const RecordType *RT = T->getAs<RecordType>()) {
2998 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2999 // -- if T is a class type (clause 9) with a user-declared
3000 // constructor (12.1), then the default constructor for T is
3001 // called (and the initialization is ill-formed if T has no
3002 // accessible default constructor);
3003 //
3004 // FIXME: we really want to refer to a single subobject of the array,
3005 // but Entity doesn't have a way to capture that (yet).
3006 if (ClassDecl->hasUserDeclaredConstructor())
3007 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003008
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003009 // -- if T is a (possibly cv-qualified) non-union class type
3010 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003011 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003012 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003013 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003014 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003015 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003016 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003017 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003018 }
3019 }
3020
Douglas Gregor1b303932009-12-22 15:35:07 +00003021 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003022}
3023
Douglas Gregor85dabae2009-12-16 01:38:02 +00003024/// \brief Attempt default initialization (C++ [dcl.init]p6).
3025static void TryDefaultInitialization(Sema &S,
3026 const InitializedEntity &Entity,
3027 const InitializationKind &Kind,
3028 InitializationSequence &Sequence) {
3029 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030
Douglas Gregor85dabae2009-12-16 01:38:02 +00003031 // C++ [dcl.init]p6:
3032 // To default-initialize an object of type T means:
3033 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003034 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3035
Douglas Gregor85dabae2009-12-16 01:38:02 +00003036 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3037 // constructor for T is called (and the initialization is ill-formed if
3038 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003039 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003040 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3041 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043
Douglas Gregor85dabae2009-12-16 01:38:02 +00003044 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003045
Douglas Gregor85dabae2009-12-16 01:38:02 +00003046 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003047 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003048 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003049 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003050 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003051 return;
3052 }
3053
3054 // If the destination type has a lifetime property, zero-initialize it.
3055 if (DestType.getQualifiers().hasObjCLifetime()) {
3056 Sequence.AddZeroInitializationStep(Entity.getType());
3057 return;
3058 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003059}
3060
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003061/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3062/// which enumerates all conversion functions and performs overload resolution
3063/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003065 const InitializedEntity &Entity,
3066 const InitializationKind &Kind,
3067 Expr *Initializer,
3068 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003069 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003070 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3071 QualType SourceType = Initializer->getType();
3072 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3073 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074
Douglas Gregor540c3b02009-12-14 17:27:33 +00003075 // Build the candidate set directly in the initialization sequence
3076 // structure, so that it will persist if we fail.
3077 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3078 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003079
Douglas Gregor540c3b02009-12-14 17:27:33 +00003080 // Determine whether we are allowed to call explicit constructors or
3081 // explicit conversion operators.
3082 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003083
Douglas Gregor540c3b02009-12-14 17:27:33 +00003084 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3085 // The type we're converting to is a class type. Enumerate its constructors
3086 // to see if there is a suitable conversion.
3087 CXXRecordDecl *DestRecordDecl
3088 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089
Douglas Gregord9848152010-04-26 14:36:57 +00003090 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003091 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003092 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003093 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003094 Con != ConEnd; ++Con) {
3095 NamedDecl *D = *Con;
3096 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003097
Douglas Gregord9848152010-04-26 14:36:57 +00003098 // Find the constructor (which may be a template).
3099 CXXConstructorDecl *Constructor = 0;
3100 FunctionTemplateDecl *ConstructorTmpl
3101 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003102 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003103 Constructor = cast<CXXConstructorDecl>(
3104 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003105 else
Douglas Gregord9848152010-04-26 14:36:57 +00003106 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107
Douglas Gregord9848152010-04-26 14:36:57 +00003108 if (!Constructor->isInvalidDecl() &&
3109 Constructor->isConvertingConstructor(AllowExplicit)) {
3110 if (ConstructorTmpl)
3111 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3112 /*ExplicitArgs*/ 0,
3113 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003114 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003115 else
3116 S.AddOverloadCandidate(Constructor, FoundDecl,
3117 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003118 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003120 }
Douglas Gregord9848152010-04-26 14:36:57 +00003121 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003122 }
Eli Friedman78275202009-12-19 08:11:05 +00003123
3124 SourceLocation DeclLoc = Initializer->getLocStart();
3125
Douglas Gregor540c3b02009-12-14 17:27:33 +00003126 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3127 // The type we're converting from is a class type, enumerate its conversion
3128 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003129
Eli Friedman4afe9a32009-12-20 22:12:03 +00003130 // We can only enumerate the conversion functions for a complete type; if
3131 // the type isn't complete, simply skip this step.
3132 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3133 CXXRecordDecl *SourceRecordDecl
3134 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003135
John McCallad371252010-01-20 00:46:10 +00003136 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003137 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003138 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003139 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003140 I != E; ++I) {
3141 NamedDecl *D = *I;
3142 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3143 if (isa<UsingShadowDecl>(D))
3144 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145
Eli Friedman4afe9a32009-12-20 22:12:03 +00003146 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3147 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003148 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003149 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003150 else
John McCallda4458e2010-03-31 01:36:47 +00003151 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152
Eli Friedman4afe9a32009-12-20 22:12:03 +00003153 if (AllowExplicit || !Conv->isExplicit()) {
3154 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003155 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003156 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003157 CandidateSet);
3158 else
John McCalla0296f72010-03-19 07:35:19 +00003159 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003160 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003161 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003162 }
3163 }
3164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
3166 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003167 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003168 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003169 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003170 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003172 Result);
3173 return;
3174 }
John McCall0d1da222010-01-12 00:44:57 +00003175
Douglas Gregor540c3b02009-12-14 17:27:33 +00003176 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003177 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178
Douglas Gregor540c3b02009-12-14 17:27:33 +00003179 if (isa<CXXConstructorDecl>(Function)) {
3180 // Add the user-defined conversion step. Any cv-qualification conversion is
3181 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003182 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003183 return;
3184 }
3185
3186 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003187 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003188 if (ConvType->getAs<RecordType>()) {
3189 // If we're converting to a class type, there may be an copy if
3190 // the resulting temporary object (possible to create an object of
3191 // a base class type). That copy is not a separate conversion, so
3192 // we just make a note of the actual destination type (possibly a
3193 // base class of the type returned by the conversion function) and
3194 // let the user-defined conversion step handle the conversion.
3195 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3196 return;
3197 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003198
Douglas Gregor5ab11652010-04-17 22:01:05 +00003199 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200
Douglas Gregor5ab11652010-04-17 22:01:05 +00003201 // If the conversion following the call to the conversion function
3202 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003203 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3204 Best->FinalConversion.Third) {
3205 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003206 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003207 ICS.Standard = Best->FinalConversion;
3208 Sequence.AddConversionSequenceStep(ICS, DestType);
3209 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003210}
3211
John McCall31168b02011-06-15 23:02:42 +00003212/// The non-zero enum values here are indexes into diagnostic alternatives.
3213enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3214
3215/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003216static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3217 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003218 // Skip parens.
3219 e = e->IgnoreParens();
3220
3221 // Skip address-of nodes.
3222 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3223 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003224 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003225
3226 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003227 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3228 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003229 case CK_Dependent:
3230 case CK_BitCast:
3231 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003232 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003233 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003234
3235 case CK_ArrayToPointerDecay:
3236 return IIK_nonscalar;
3237
3238 case CK_NullToPointer:
3239 return IIK_okay;
3240
3241 default:
3242 break;
3243 }
3244
3245 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003246 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3247 if (!isAddressOf) return IIK_nonlocal;
3248
3249 VarDecl *var;
3250 if (isa<DeclRefExpr>(e)) {
3251 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3252 if (!var) return IIK_nonlocal;
3253 } else {
3254 var = cast<BlockDeclRefExpr>(e)->getDecl();
3255 }
3256
3257 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003258
3259 // If we have a conditional operator, check both sides.
3260 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003261 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003262 return iik;
3263
John McCall63f84442011-06-27 23:59:58 +00003264 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003265
3266 // These are never scalar.
3267 } else if (isa<ArraySubscriptExpr>(e)) {
3268 return IIK_nonscalar;
3269
3270 // Otherwise, it needs to be a null pointer constant.
3271 } else {
3272 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3273 ? IIK_okay : IIK_nonlocal);
3274 }
3275
3276 return IIK_nonlocal;
3277}
3278
3279/// Check whether the given expression is a valid operand for an
3280/// indirect copy/restore.
3281static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3282 assert(src->isRValue());
3283
John McCall63f84442011-06-27 23:59:58 +00003284 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003285 if (iik == IIK_okay) return;
3286
3287 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3288 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3289 << src->getSourceRange();
3290}
3291
Douglas Gregore2f943b2011-02-22 18:29:51 +00003292/// \brief Determine whether we have compatible array types for the
3293/// purposes of GNU by-copy array initialization.
3294static bool hasCompatibleArrayTypes(ASTContext &Context,
3295 const ArrayType *Dest,
3296 const ArrayType *Source) {
3297 // If the source and destination array types are equivalent, we're
3298 // done.
3299 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3300 return true;
3301
3302 // Make sure that the element types are the same.
3303 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3304 return false;
3305
3306 // The only mismatch we allow is when the destination is an
3307 // incomplete array type and the source is a constant array type.
3308 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3309}
3310
John McCall31168b02011-06-15 23:02:42 +00003311static bool tryObjCWritebackConversion(Sema &S,
3312 InitializationSequence &Sequence,
3313 const InitializedEntity &Entity,
3314 Expr *Initializer) {
3315 bool ArrayDecay = false;
3316 QualType ArgType = Initializer->getType();
3317 QualType ArgPointee;
3318 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3319 ArrayDecay = true;
3320 ArgPointee = ArgArrayType->getElementType();
3321 ArgType = S.Context.getPointerType(ArgPointee);
3322 }
3323
3324 // Handle write-back conversion.
3325 QualType ConvertedArgType;
3326 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3327 ConvertedArgType))
3328 return false;
3329
3330 // We should copy unless we're passing to an argument explicitly
3331 // marked 'out'.
3332 bool ShouldCopy = true;
3333 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3334 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3335
3336 // Do we need an lvalue conversion?
3337 if (ArrayDecay || Initializer->isGLValue()) {
3338 ImplicitConversionSequence ICS;
3339 ICS.setStandard();
3340 ICS.Standard.setAsIdentityConversion();
3341
3342 QualType ResultType;
3343 if (ArrayDecay) {
3344 ICS.Standard.First = ICK_Array_To_Pointer;
3345 ResultType = S.Context.getPointerType(ArgPointee);
3346 } else {
3347 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3348 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3349 }
3350
3351 Sequence.AddConversionSequenceStep(ICS, ResultType);
3352 }
3353
3354 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3355 return true;
3356}
3357
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003358InitializationSequence::InitializationSequence(Sema &S,
3359 const InitializedEntity &Entity,
3360 const InitializationKind &Kind,
3361 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003362 unsigned NumArgs)
3363 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003364 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003366 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367 // The semantics of initializers are as follows. The destination type is
3368 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003369 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003370 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003371 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003372 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003373
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003374 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003375 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3376 SequenceKind = DependentSequence;
3377 return;
3378 }
3379
Sebastian Redld201edf2011-06-05 13:59:11 +00003380 // Almost everything is a normal sequence.
3381 setSequenceKind(NormalSequence);
3382
John McCalled75c092010-12-07 22:54:16 +00003383 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003384 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3385 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3386 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003387 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003388 return;
3389 }
3390 Args[I] = Result.take();
3391 }
John McCalled75c092010-12-07 22:54:16 +00003392
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003393 QualType SourceType;
3394 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003395 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003396 Initializer = Args[0];
3397 if (!isa<InitListExpr>(Initializer))
3398 SourceType = Initializer->getType();
3399 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400
3401 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003402 // list-initialized (8.5.4).
3403 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003404 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003405 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003408 // - If the destination type is a reference type, see 8.5.3.
3409 if (DestType->isReferenceType()) {
3410 // C++0x [dcl.init.ref]p1:
3411 // A variable declared to be a T& or T&&, that is, "reference to type T"
3412 // (8.3.2), shall be initialized by an object, or function, of type T or
3413 // by an object that can be converted into a T.
3414 // (Therefore, multiple arguments are not permitted.)
3415 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003416 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003417 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003418 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003419 return;
3420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003422 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003423 if (Kind.getKind() == InitializationKind::IK_Value ||
3424 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003425 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003426 return;
3427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428
Douglas Gregor85dabae2009-12-16 01:38:02 +00003429 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003430 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003431 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003432 return;
3433 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003434
John McCall66884dd2011-02-21 07:22:22 +00003435 // - If the destination type is an array of characters, an array of
3436 // char16_t, an array of char32_t, or an array of wchar_t, and the
3437 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003439 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003440 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3441 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003442 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003443 return;
3444 }
3445
Douglas Gregore2f943b2011-02-22 18:29:51 +00003446 // Note: as an GNU C extension, we allow initialization of an
3447 // array from a compound literal that creates an array of the same
3448 // type, so long as the initializer has no side effects.
3449 if (!S.getLangOptions().CPlusPlus && Initializer &&
3450 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3451 Initializer->getType()->isArrayType()) {
3452 const ArrayType *SourceAT
3453 = Context.getAsArrayType(Initializer->getType());
3454 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003455 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003456 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003457 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003458 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003459 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003460 }
3461 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003462 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003463 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003464 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003466 return;
3467 }
Eli Friedman78275202009-12-19 08:11:05 +00003468
John McCall31168b02011-06-15 23:02:42 +00003469 // Determine whether we should consider writeback conversions for
3470 // Objective-C ARC.
3471 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3472 Entity.getKind() == InitializedEntity::EK_Parameter;
3473
3474 // We're at the end of the line for C: it's either a write-back conversion
3475 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003476 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003477 // If allowed, check whether this is an Objective-C writeback conversion.
3478 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003479 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003480 return;
3481 }
3482
3483 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003484 AddCAssignmentStep(DestType);
3485 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003486 return;
3487 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488
John McCall31168b02011-06-15 23:02:42 +00003489 assert(S.getLangOptions().CPlusPlus);
3490
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003491 // - If the destination type is a (possibly cv-qualified) class type:
3492 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493 // - If the initialization is direct-initialization, or if it is
3494 // copy-initialization where the cv-unqualified version of the
3495 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003496 // class of the destination, constructors are considered. [...]
3497 if (Kind.getKind() == InitializationKind::IK_Direct ||
3498 (Kind.getKind() == InitializationKind::IK_Copy &&
3499 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3500 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003502 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003504 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003506 // used) to a derived class thereof are enumerated as described in
3507 // 13.3.1.4, and the best one is chosen through overload resolution
3508 // (13.3).
3509 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003510 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003511 return;
3512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513
Douglas Gregor85dabae2009-12-16 01:38:02 +00003514 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003515 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003516 return;
3517 }
3518 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519
3520 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003521 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003522 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003523 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3524 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003525 return;
3526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003527
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003528 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003529 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003530 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003533
3534 ImplicitConversionSequence ICS
3535 = S.TryImplicitConversion(Initializer, Entity.getType(),
3536 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003537 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003538 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003539 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3540 allowObjCWritebackConversion);
3541
3542 if (ICS.isStandard() &&
3543 ICS.Standard.Second == ICK_Writeback_Conversion) {
3544 // Objective-C ARC writeback conversion.
3545
3546 // We should copy unless we're passing to an argument explicitly
3547 // marked 'out'.
3548 bool ShouldCopy = true;
3549 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3550 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3551
3552 // If there was an lvalue adjustment, add it as a separate conversion.
3553 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3554 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3555 ImplicitConversionSequence LvalueICS;
3556 LvalueICS.setStandard();
3557 LvalueICS.Standard.setAsIdentityConversion();
3558 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3559 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003560 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003561 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003562
3563 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003564 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003565 DeclAccessPair dap;
3566 if (Initializer->getType() == Context.OverloadTy &&
3567 !S.ResolveAddressOfOverloadedFunction(Initializer
3568 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003569 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003570 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003571 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003572 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003573 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003574
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003575 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003576 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003577}
3578
3579InitializationSequence::~InitializationSequence() {
3580 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3581 StepEnd = Steps.end();
3582 Step != StepEnd; ++Step)
3583 Step->Destroy();
3584}
3585
3586//===----------------------------------------------------------------------===//
3587// Perform initialization
3588//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003590getAssignmentAction(const InitializedEntity &Entity) {
3591 switch(Entity.getKind()) {
3592 case InitializedEntity::EK_Variable:
3593 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003594 case InitializedEntity::EK_Exception:
3595 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003596 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003597 return Sema::AA_Initializing;
3598
3599 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003601 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3602 return Sema::AA_Sending;
3603
Douglas Gregore1314a62009-12-18 05:02:21 +00003604 return Sema::AA_Passing;
3605
3606 case InitializedEntity::EK_Result:
3607 return Sema::AA_Returning;
3608
Douglas Gregore1314a62009-12-18 05:02:21 +00003609 case InitializedEntity::EK_Temporary:
3610 // FIXME: Can we tell apart casting vs. converting?
3611 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612
Douglas Gregore1314a62009-12-18 05:02:21 +00003613 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003614 case InitializedEntity::EK_ArrayElement:
3615 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003616 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003617 return Sema::AA_Initializing;
3618 }
3619
3620 return Sema::AA_Converting;
3621}
3622
Douglas Gregor95562572010-04-24 23:45:46 +00003623/// \brief Whether we should binding a created object as a temporary when
3624/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003625static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003626 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003627 case InitializedEntity::EK_ArrayElement:
3628 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003629 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003630 case InitializedEntity::EK_New:
3631 case InitializedEntity::EK_Variable:
3632 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003633 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003634 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003635 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003636 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003637 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638
Douglas Gregore1314a62009-12-18 05:02:21 +00003639 case InitializedEntity::EK_Parameter:
3640 case InitializedEntity::EK_Temporary:
3641 return true;
3642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003643
Douglas Gregore1314a62009-12-18 05:02:21 +00003644 llvm_unreachable("missed an InitializedEntity kind?");
3645}
3646
Douglas Gregor95562572010-04-24 23:45:46 +00003647/// \brief Whether the given entity, when initialized with an object
3648/// created for that initialization, requires destruction.
3649static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3650 switch (Entity.getKind()) {
3651 case InitializedEntity::EK_Member:
3652 case InitializedEntity::EK_Result:
3653 case InitializedEntity::EK_New:
3654 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003655 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00003656 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003657 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003658 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659
Douglas Gregor95562572010-04-24 23:45:46 +00003660 case InitializedEntity::EK_Variable:
3661 case InitializedEntity::EK_Parameter:
3662 case InitializedEntity::EK_Temporary:
3663 case InitializedEntity::EK_ArrayElement:
3664 case InitializedEntity::EK_Exception:
3665 return true;
3666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
3668 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003669}
3670
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003671/// \brief Make a (potentially elidable) temporary copy of the object
3672/// provided by the given initializer by calling the appropriate copy
3673/// constructor.
3674///
3675/// \param S The Sema object used for type-checking.
3676///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003677/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003678/// the type of the initializer expression or a superclass thereof.
3679///
3680/// \param Enter The entity being initialized.
3681///
3682/// \param CurInit The initializer expression.
3683///
3684/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3685/// is permitted in C++03 (but not C++0x) when binding a reference to
3686/// an rvalue.
3687///
3688/// \returns An expression that copies the initializer expression into
3689/// a temporary object, or an error expression if a copy could not be
3690/// created.
John McCalldadc5752010-08-24 06:29:42 +00003691static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003692 QualType T,
3693 const InitializedEntity &Entity,
3694 ExprResult CurInit,
3695 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003696 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003697 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003699 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003700 Class = cast<CXXRecordDecl>(Record->getDecl());
3701 if (!Class)
3702 return move(CurInit);
3703
Douglas Gregor5d369002011-01-21 18:05:27 +00003704 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003705 // When certain criteria are met, an implementation is allowed to
3706 // omit the copy/move construction of a class object, even if the
3707 // copy/move constructor and/or destructor for the object have
3708 // side effects. [...]
3709 // - when a temporary class object that has not been bound to a
3710 // reference (12.2) would be copied/moved to a class object
3711 // with the same cv-unqualified type, the copy/move operation
3712 // can be omitted by constructing the temporary object
3713 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003715 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003716 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003718 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003719 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003720 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003721 switch (Entity.getKind()) {
3722 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003723 Loc = Entity.getReturnLoc();
3724 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725
Douglas Gregore1314a62009-12-18 05:02:21 +00003726 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003727 Loc = Entity.getThrowLoc();
3728 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729
Douglas Gregore1314a62009-12-18 05:02:21 +00003730 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003731 Loc = Entity.getDecl()->getLocation();
3732 break;
3733
Anders Carlsson0bd52402010-01-24 00:19:41 +00003734 case InitializedEntity::EK_ArrayElement:
3735 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003736 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003737 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003738 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003739 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003740 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003741 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003742 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003743 Loc = CurInitExpr->getLocStart();
3744 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003745 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003746
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003748 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3749 return move(CurInit);
3750
Douglas Gregorf282a762011-01-21 19:38:21 +00003751 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003752 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003753 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003754 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003755 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003756 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003757 // C++0x [dcl.init]p16, second bullet to class types, this
3758 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003759 CXXConstructorDecl *Constructor = 0;
3760
3761 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003762 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003763 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003764 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003765 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003766 continue;
3767
3768 DeclAccessPair FoundDecl
3769 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3770 S.AddOverloadCandidate(Constructor, FoundDecl,
3771 &CurInitExpr, 1, CandidateSet);
3772 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003774
3775 // Handle constructor templates.
3776 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3777 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003778 continue;
John McCalla0296f72010-03-19 07:35:19 +00003779
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003780 Constructor = cast<CXXConstructorDecl>(
3781 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003782 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003783 continue;
3784
3785 // FIXME: Do we need to limit this to copy-constructor-like
3786 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003787 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003788 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3789 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3790 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003792
Douglas Gregore1314a62009-12-18 05:02:21 +00003793 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003794 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003795 case OR_Success:
3796 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797
Douglas Gregore1314a62009-12-18 05:02:21 +00003798 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003799 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3800 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3801 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003802 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003803 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003804 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003805 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003806 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003807 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808
Douglas Gregore1314a62009-12-18 05:02:21 +00003809 case OR_Ambiguous:
3810 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003811 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003812 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003813 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003814 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815
Douglas Gregore1314a62009-12-18 05:02:21 +00003816 case OR_Deleted:
3817 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003818 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003819 << CurInitExpr->getSourceRange();
3820 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00003821 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003822 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003823 }
3824
Douglas Gregor5ab11652010-04-17 22:01:05 +00003825 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003826 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003827 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003828
Anders Carlssona01874b2010-04-21 18:47:17 +00003829 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003830 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003831
3832 if (IsExtraneousCopy) {
3833 // If this is a totally extraneous copy for C++03 reference
3834 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003835 // expression. We don't generate an (elided) copy operation here
3836 // because doing so would require us to pass down a flag to avoid
3837 // infinite recursion, where each step adds another extraneous,
3838 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003839
Douglas Gregor30b52772010-04-18 07:57:34 +00003840 // Instantiate the default arguments of any extra parameters in
3841 // the selected copy constructor, as if we were going to create a
3842 // proper call to the copy constructor.
3843 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3844 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3845 if (S.RequireCompleteType(Loc, Parm->getType(),
3846 S.PDiag(diag::err_call_incomplete_argument)))
3847 break;
3848
3849 // Build the default argument expression; we don't actually care
3850 // if this succeeds or not, because this routine will complain
3851 // if there was a problem.
3852 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3853 }
3854
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003855 return S.Owned(CurInitExpr);
3856 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003857
Chandler Carruth30141632011-02-25 19:41:05 +00003858 S.MarkDeclarationReferenced(Loc, Constructor);
3859
Douglas Gregor5ab11652010-04-17 22:01:05 +00003860 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003861 // constructor call (we might have derived-to-base conversions, or
3862 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003863 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003864 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003865 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003866
Douglas Gregord0ace022010-04-25 00:55:24 +00003867 // Actually perform the constructor call.
3868 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003869 move_arg(ConstructorArgs),
3870 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003871 CXXConstructExpr::CK_Complete,
3872 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873
Douglas Gregord0ace022010-04-25 00:55:24 +00003874 // If we're supposed to bind temporaries, do so.
3875 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3876 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3877 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003878}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003879
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003880void InitializationSequence::PrintInitLocationNote(Sema &S,
3881 const InitializedEntity &Entity) {
3882 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3883 if (Entity.getDecl()->getLocation().isInvalid())
3884 return;
3885
3886 if (Entity.getDecl()->getDeclName())
3887 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3888 << Entity.getDecl()->getDeclName();
3889 else
3890 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3891 }
3892}
3893
Sebastian Redl112aa822011-07-14 19:07:55 +00003894static bool isReferenceBinding(const InitializationSequence::Step &s) {
3895 return s.Kind == InitializationSequence::SK_BindReference ||
3896 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
3897}
3898
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003899ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900InitializationSequence::Perform(Sema &S,
3901 const InitializedEntity &Entity,
3902 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003903 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003904 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003905 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003906 unsigned NumArgs = Args.size();
3907 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003908 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910
Sebastian Redld201edf2011-06-05 13:59:11 +00003911 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003912 // If the declaration is a non-dependent, incomplete array type
3913 // that has an initializer, then its type will be completed once
3914 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003915 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003916 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003917 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003918 if (const IncompleteArrayType *ArrayT
3919 = S.Context.getAsIncompleteArrayType(DeclType)) {
3920 // FIXME: We don't currently have the ability to accurately
3921 // compute the length of an initializer list without
3922 // performing full type-checking of the initializer list
3923 // (since we have to determine where braces are implicitly
3924 // introduced and such). So, we fall back to making the array
3925 // type a dependently-sized array type with no specified
3926 // bound.
3927 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3928 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003929
Douglas Gregor51e77d52009-12-10 17:56:55 +00003930 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003931 if (DeclaratorDecl *DD = Entity.getDecl()) {
3932 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3933 TypeLoc TL = TInfo->getTypeLoc();
3934 if (IncompleteArrayTypeLoc *ArrayLoc
3935 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3936 Brackets = ArrayLoc->getBracketsRange();
3937 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003938 }
3939
3940 *ResultType
3941 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3942 /*NumElts=*/0,
3943 ArrayT->getSizeModifier(),
3944 ArrayT->getIndexTypeCVRQualifiers(),
3945 Brackets);
3946 }
3947
3948 }
3949 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00003950 assert(Kind.getKind() == InitializationKind::IK_Copy ||
3951 Kind.isExplicitCast());
3952 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003953 }
3954
Sebastian Redld201edf2011-06-05 13:59:11 +00003955 // No steps means no initialization.
3956 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00003957 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958
Douglas Gregor1b303932009-12-22 15:35:07 +00003959 QualType DestType = Entity.getType().getNonReferenceType();
3960 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003961 // the same as Entity.getDecl()->getType() in cases involving type merging,
3962 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003963 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003964 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003965 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003966
John McCalldadc5752010-08-24 06:29:42 +00003967 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003969 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00003970 // grab the only argument out the Args and place it into the "current"
3971 // initializer.
3972 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003973 case SK_ResolveAddressOfOverloadedFunction:
3974 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003975 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003976 case SK_CastDerivedToBaseLValue:
3977 case SK_BindReference:
3978 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003979 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003980 case SK_UserConversion:
3981 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003982 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003983 case SK_QualificationConversionRValue:
3984 case SK_ConversionSequence:
3985 case SK_ListInitialization:
3986 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003987 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003988 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00003989 case SK_ArrayInit:
3990 case SK_PassByIndirectCopyRestore:
3991 case SK_PassByIndirectRestore:
3992 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00003993 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00003994 CurInit = Args.get()[0];
3995 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003996
3997 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00003998 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3999 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4000 if (CurInit.isInvalid())
4001 return ExprError();
4002 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004003 break;
John McCall34376a62010-12-04 03:47:34 +00004004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004005
Douglas Gregore1314a62009-12-18 05:02:21 +00004006 case SK_ConstructorInitialization:
4007 case SK_ZeroInitialization:
4008 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010
4011 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004012 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004013 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004014 for (step_iterator Step = step_begin(), StepEnd = step_end();
4015 Step != StepEnd; ++Step) {
4016 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004017 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018
John Wiegley01296292011-04-08 18:41:53 +00004019 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004021 switch (Step->Kind) {
4022 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004024 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004025 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004026 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004027 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004028 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004029 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004030 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004032 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004033 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004034 case SK_CastDerivedToBaseLValue: {
4035 // We have a derived-to-base cast that produces either an rvalue or an
4036 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004037
John McCallcf142162010-08-07 06:22:56 +00004038 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004039
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004040 // Casts to inaccessible base classes are allowed with C-style casts.
4041 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4042 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004043 CurInit.get()->getLocStart(),
4044 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004045 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004046 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047
Douglas Gregor88d292c2010-05-13 16:44:06 +00004048 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4049 QualType T = SourceType;
4050 if (const PointerType *Pointer = T->getAs<PointerType>())
4051 T = Pointer->getPointeeType();
4052 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004053 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004054 cast<CXXRecordDecl>(RecordTy->getDecl()));
4055 }
4056
John McCall2536c6d2010-08-25 10:28:54 +00004057 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004058 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004059 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004060 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004061 VK_XValue :
4062 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004063 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4064 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004065 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004066 CurInit.get(),
4067 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004068 break;
4069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004070
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004071 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004072 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004073 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4074 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004075 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004076 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004077 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004078 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004079 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004080 }
Anders Carlssona91be642010-01-29 02:47:33 +00004081
John Wiegley01296292011-04-08 18:41:53 +00004082 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004083 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004084 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4085 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004086 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004087 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004088 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004091 // Reference binding does not have any corresponding ASTs.
4092
4093 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004094 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004095 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004096
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004097 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004098
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004099 case SK_BindReferenceToTemporary:
4100 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004101 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004102 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004103
Douglas Gregorfe314812011-06-21 17:03:29 +00004104 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004105 CurInit = new (S.Context) MaterializeTemporaryExpr(
4106 Entity.getType().getNonReferenceType(),
4107 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004108 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004109
4110 // If we're binding to an Objective-C object that has lifetime, we
4111 // need cleanups.
4112 if (S.getLangOptions().ObjCAutoRefCount &&
4113 CurInit.get()->getType()->isObjCLifetimeType())
4114 S.ExprNeedsCleanups = true;
4115
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004116 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004117
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004118 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004120 /*IsExtraneousCopy=*/true);
4121 break;
4122
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004123 case SK_UserConversion: {
4124 // We have a user-defined conversion that invokes either a constructor
4125 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004126 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004127 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004128 FunctionDecl *Fn = Step->Function.Function;
4129 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004130 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00004131 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00004132 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004133 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004134 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004135 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004136 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004137
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004138 // Determine the arguments required to actually perform the constructor
4139 // call.
John Wiegley01296292011-04-08 18:41:53 +00004140 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004141 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004142 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004143 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004144 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004146 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004148 move_arg(ConstructorArgs),
4149 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004150 CXXConstructExpr::CK_Complete,
4151 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004152 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004153 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004154
Anders Carlssona01874b2010-04-21 18:47:17 +00004155 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004156 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004157 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
John McCalle3027922010-08-25 11:45:40 +00004159 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004160 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4161 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4162 S.IsDerivedFrom(SourceType, Class))
4163 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004164
Douglas Gregor95562572010-04-24 23:45:46 +00004165 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004166 } else {
4167 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004168 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00004169 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00004170 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004171 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004172 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173
4174 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004175 // derived-to-base conversion? I believe the answer is "no", because
4176 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004177 ExprResult CurInitExprRes =
4178 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4179 FoundFn, Conversion);
4180 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004181 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004182 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004184 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004185 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004186 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004187 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
John McCalle3027922010-08-25 11:45:40 +00004189 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190
Douglas Gregor95562572010-04-24 23:45:46 +00004191 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193
Sebastian Redl112aa822011-07-14 19:07:55 +00004194 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004195 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004196 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004197 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004198 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004199 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004201 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004202 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004203 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004204 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4205 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004206 }
4207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004209 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00004210 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004211 CurInit.get()->getType(),
4212 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00004213 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004215 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004216 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4217 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004218
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004219 break;
4220 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004221
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004222 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004223 case SK_QualificationConversionXValue:
4224 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004225 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004226 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004227 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004228 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004229 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004230 VK_XValue :
4231 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004232 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004233 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004234 }
4235
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004236 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004237 Sema::CheckedConversionKind CCK
4238 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4239 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4240 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4241 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004242 ExprResult CurInitExprRes =
4243 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004244 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004245 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004246 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004247 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004248 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250
Douglas Gregor51e77d52009-12-10 17:56:55 +00004251 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004252 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004253 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00004254 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00004255 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004256
4257 CurInit.release();
4258 CurInit = S.Owned(InitList);
4259 break;
4260 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004261
4262 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004263 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004264 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004265 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004266
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004267 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004268 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004269 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4270 ? Kind.getEqualLoc()
4271 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004272
4273 if (Kind.getKind() == InitializationKind::IK_Default) {
4274 // Force even a trivial, implicit default constructor to be
4275 // semantically checked. We do this explicitly because we don't build
4276 // the definition for completely trivial constructors.
4277 CXXRecordDecl *ClassDecl = Constructor->getParent();
4278 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004279 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004280 ClassDecl->hasTrivialDefaultConstructor() &&
4281 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004282 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4283 }
4284
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004285 // Determine the arguments required to actually perform the constructor
4286 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004288 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004289 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
4291
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004292 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004293 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004294 (Kind.getKind() == InitializationKind::IK_Direct ||
4295 Kind.getKind() == InitializationKind::IK_Value)) {
4296 // An explicitly-constructed temporary, e.g., X(1, 2).
4297 unsigned NumExprs = ConstructorArgs.size();
4298 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004299 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004300 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301
Douglas Gregor2b88c112010-09-08 00:15:04 +00004302 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4303 if (!TSInfo)
4304 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004306 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4307 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004308 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004310 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004311 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004312 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004313 } else {
4314 CXXConstructExpr::ConstructionKind ConstructKind =
4315 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004317 if (Entity.getKind() == InitializedEntity::EK_Base) {
4318 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004320 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004321 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004322 ConstructKind = CXXConstructExpr::CK_Delegating;
4323 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324
Chandler Carruth01718152010-10-25 08:47:36 +00004325 // Only get the parenthesis range if it is a direct construction.
4326 SourceRange parenRange =
4327 Kind.getKind() == InitializationKind::IK_Direct ?
4328 Kind.getParenRange() : SourceRange();
4329
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004330 // If the entity allows NRVO, mark the construction as elidable
4331 // unconditionally.
4332 if (Entity.allowsNRVO())
4333 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4334 Constructor, /*Elidable=*/true,
4335 move_arg(ConstructorArgs),
4336 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004337 ConstructKind,
4338 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004339 else
4340 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004342 move_arg(ConstructorArgs),
4343 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004344 ConstructKind,
4345 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004346 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004347 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004348 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004349
4350 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004351 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004352 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004353 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004355 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004356 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004358 break;
4359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004361 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004362 step_iterator NextStep = Step;
4363 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004365 NextStep->Kind == SK_ConstructorInitialization) {
4366 // The need for zero-initialization is recorded directly into
4367 // the call to the object's constructor within the next step.
4368 ConstructorInitRequiresZeroInit = true;
4369 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4370 S.getLangOptions().CPlusPlus &&
4371 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004372 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4373 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004375 Kind.getRange().getBegin());
4376
4377 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4378 TSInfo->getType().getNonLValueExprType(S.Context),
4379 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004380 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004381 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004382 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004383 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004384 break;
4385 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004386
4387 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004388 QualType SourceType = CurInit.get()->getType();
4389 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004390 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004391 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4392 if (Result.isInvalid())
4393 return ExprError();
4394 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004395
4396 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004397 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004398 if (ConvTy != Sema::Compatible &&
4399 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004400 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004401 == Sema::Compatible)
4402 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004403 if (CurInitExprRes.isInvalid())
4404 return ExprError();
4405 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004406
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004407 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004408 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4409 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004410 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004411 getAssignmentAction(Entity),
4412 &Complained)) {
4413 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004414 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004415 } else if (Complained)
4416 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004417 break;
4418 }
Eli Friedman78275202009-12-19 08:11:05 +00004419
4420 case SK_StringInit: {
4421 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004422 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004423 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004424 break;
4425 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004426
4427 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004428 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004429 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004430 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004431 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004432
4433 case SK_ArrayInit:
4434 // Okay: we checked everything before creating this step. Note that
4435 // this is a GNU extension.
4436 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004437 << Step->Type << CurInit.get()->getType()
4438 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004439
4440 // If the destination type is an incomplete array type, update the
4441 // type accordingly.
4442 if (ResultType) {
4443 if (const IncompleteArrayType *IncompleteDest
4444 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4445 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004446 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004447 *ResultType = S.Context.getConstantArrayType(
4448 IncompleteDest->getElementType(),
4449 ConstantSource->getSize(),
4450 ArrayType::Normal, 0);
4451 }
4452 }
4453 }
John McCall31168b02011-06-15 23:02:42 +00004454 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004455
John McCall31168b02011-06-15 23:02:42 +00004456 case SK_PassByIndirectCopyRestore:
4457 case SK_PassByIndirectRestore:
4458 checkIndirectCopyRestoreSource(S, CurInit.get());
4459 CurInit = S.Owned(new (S.Context)
4460 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4461 Step->Kind == SK_PassByIndirectCopyRestore));
4462 break;
4463
4464 case SK_ProduceObjCObject:
4465 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4466 CK_ObjCProduceObject,
4467 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004468 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004469 }
4470 }
John McCall1f425642010-11-11 03:21:53 +00004471
4472 // Diagnose non-fatal problems with the completed initialization.
4473 if (Entity.getKind() == InitializedEntity::EK_Member &&
4474 cast<FieldDecl>(Entity.getDecl())->isBitField())
4475 S.CheckBitFieldInitialization(Kind.getLocation(),
4476 cast<FieldDecl>(Entity.getDecl()),
4477 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004479 return move(CurInit);
4480}
4481
4482//===----------------------------------------------------------------------===//
4483// Diagnose initialization failures
4484//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004486 const InitializedEntity &Entity,
4487 const InitializationKind &Kind,
4488 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004489 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004490 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491
Douglas Gregor1b303932009-12-22 15:35:07 +00004492 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004493 switch (Failure) {
4494 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004495 // FIXME: Customize for the initialized entity?
4496 if (NumArgs == 0)
4497 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4498 << DestType.getNonReferenceType();
4499 else // FIXME: diagnostic below could be better!
4500 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4501 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004502 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004504 case FK_ArrayNeedsInitList:
4505 case FK_ArrayNeedsInitListOrStringLiteral:
4506 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4507 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4508 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509
Douglas Gregore2f943b2011-02-22 18:29:51 +00004510 case FK_ArrayTypeMismatch:
4511 case FK_NonConstantArrayInit:
4512 S.Diag(Kind.getLocation(),
4513 (Failure == FK_ArrayTypeMismatch
4514 ? diag::err_array_init_different_type
4515 : diag::err_array_init_non_constant_array))
4516 << DestType.getNonReferenceType()
4517 << Args[0]->getType()
4518 << Args[0]->getSourceRange();
4519 break;
4520
John McCall16df1e52010-03-30 21:47:33 +00004521 case FK_AddressOfOverloadFailed: {
4522 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004524 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004525 true,
4526 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004527 break;
John McCall16df1e52010-03-30 21:47:33 +00004528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004529
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004530 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004531 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004532 switch (FailedOverloadResult) {
4533 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004534 if (Failure == FK_UserConversionOverloadFailed)
4535 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4536 << Args[0]->getType() << DestType
4537 << Args[0]->getSourceRange();
4538 else
4539 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4540 << DestType << Args[0]->getType()
4541 << Args[0]->getSourceRange();
4542
John McCall5c32be02010-08-24 20:38:10 +00004543 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004544 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004546 case OR_No_Viable_Function:
4547 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4548 << Args[0]->getType() << DestType.getNonReferenceType()
4549 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004550 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004551 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004553 case OR_Deleted: {
4554 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4555 << Args[0]->getType() << DestType.getNonReferenceType()
4556 << Args[0]->getSourceRange();
4557 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004558 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004559 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4560 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004561 if (Ovl == OR_Deleted) {
4562 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004563 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004564 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004565 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004566 }
4567 break;
4568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004569
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004570 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004571 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004572 break;
4573 }
4574 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004576 case FK_NonConstLValueReferenceBindingToTemporary:
4577 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004579 Failure == FK_NonConstLValueReferenceBindingToTemporary
4580 ? diag::err_lvalue_reference_bind_to_temporary
4581 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004582 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004583 << DestType.getNonReferenceType()
4584 << Args[0]->getType()
4585 << Args[0]->getSourceRange();
4586 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004588 case FK_RValueReferenceBindingToLValue:
4589 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004590 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004591 << Args[0]->getSourceRange();
4592 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004594 case FK_ReferenceInitDropsQualifiers:
4595 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4596 << DestType.getNonReferenceType()
4597 << Args[0]->getType()
4598 << Args[0]->getSourceRange();
4599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004601 case FK_ReferenceInitFailed:
4602 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4603 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004604 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004605 << Args[0]->getType()
4606 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004607 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4608 Args[0]->getType()->isObjCObjectPointerType())
4609 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004610 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611
Douglas Gregorb491ed32011-02-19 21:32:49 +00004612 case FK_ConversionFailed: {
4613 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004614 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4615 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004616 << DestType
John McCall086a4642010-11-24 05:12:34 +00004617 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004618 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004619 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004620 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4621 Args[0]->getType()->isObjCObjectPointerType())
4622 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004623 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004624 }
John Wiegley01296292011-04-08 18:41:53 +00004625
4626 case FK_ConversionFromPropertyFailed:
4627 // No-op. This error has already been reported.
4628 break;
4629
Douglas Gregor51e77d52009-12-10 17:56:55 +00004630 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004631 SourceRange R;
4632
4633 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004634 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004635 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004636 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004637 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004638
Douglas Gregor8ec51732010-09-08 21:40:08 +00004639 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4640 if (Kind.isCStyleOrFunctionalCast())
4641 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4642 << R;
4643 else
4644 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4645 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004646 break;
4647 }
4648
4649 case FK_ReferenceBindingToInitList:
4650 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4651 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4652 break;
4653
4654 case FK_InitListBadDestinationType:
4655 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4656 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004659 case FK_ConstructorOverloadFailed: {
4660 SourceRange ArgsRange;
4661 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004663 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004665 // FIXME: Using "DestType" for the entity we're printing is probably
4666 // bad.
4667 switch (FailedOverloadResult) {
4668 case OR_Ambiguous:
4669 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4670 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004671 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4672 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004673 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004675 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004676 if (Kind.getKind() == InitializationKind::IK_Default &&
4677 (Entity.getKind() == InitializedEntity::EK_Base ||
4678 Entity.getKind() == InitializedEntity::EK_Member) &&
4679 isa<CXXConstructorDecl>(S.CurContext)) {
4680 // This is implicit default initialization of a member or
4681 // base within a constructor. If no viable function was
4682 // found, notify the user that she needs to explicitly
4683 // initialize this base/member.
4684 CXXConstructorDecl *Constructor
4685 = cast<CXXConstructorDecl>(S.CurContext);
4686 if (Entity.getKind() == InitializedEntity::EK_Base) {
4687 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4688 << Constructor->isImplicit()
4689 << S.Context.getTypeDeclType(Constructor->getParent())
4690 << /*base=*/0
4691 << Entity.getType();
4692
4693 RecordDecl *BaseDecl
4694 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4695 ->getDecl();
4696 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4697 << S.Context.getTagDeclType(BaseDecl);
4698 } else {
4699 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4700 << Constructor->isImplicit()
4701 << S.Context.getTypeDeclType(Constructor->getParent())
4702 << /*member=*/1
4703 << Entity.getName();
4704 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4705
4706 if (const RecordType *Record
4707 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004709 diag::note_previous_decl)
4710 << S.Context.getTagDeclType(Record->getDecl());
4711 }
4712 break;
4713 }
4714
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004715 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4716 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004717 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004718 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004720 case OR_Deleted: {
4721 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4722 << true << DestType << ArgsRange;
4723 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004724 OverloadingResult Ovl
4725 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004726 if (Ovl == OR_Deleted) {
4727 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004728 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004729 } else {
4730 llvm_unreachable("Inconsistent overload resolution?");
4731 }
4732 break;
4733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004735 case OR_Success:
4736 llvm_unreachable("Conversion did not fail!");
4737 break;
4738 }
4739 break;
4740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741
Douglas Gregor85dabae2009-12-16 01:38:02 +00004742 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004743 if (Entity.getKind() == InitializedEntity::EK_Member &&
4744 isa<CXXConstructorDecl>(S.CurContext)) {
4745 // This is implicit default-initialization of a const member in
4746 // a constructor. Complain that it needs to be explicitly
4747 // initialized.
4748 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4749 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4750 << Constructor->isImplicit()
4751 << S.Context.getTypeDeclType(Constructor->getParent())
4752 << /*const=*/1
4753 << Entity.getName();
4754 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4755 << Entity.getName();
4756 } else {
4757 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4758 << DestType << (bool)DestType->getAs<RecordType>();
4759 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004762 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004764 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004766 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004768 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004769 return true;
4770}
Douglas Gregore1314a62009-12-18 05:02:21 +00004771
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004772void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4773 switch (SequenceKind) {
4774 case FailedSequence: {
4775 OS << "Failed sequence: ";
4776 switch (Failure) {
4777 case FK_TooManyInitsForReference:
4778 OS << "too many initializers for reference";
4779 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004780
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004781 case FK_ArrayNeedsInitList:
4782 OS << "array requires initializer list";
4783 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004785 case FK_ArrayNeedsInitListOrStringLiteral:
4786 OS << "array requires initializer list or string literal";
4787 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004788
Douglas Gregore2f943b2011-02-22 18:29:51 +00004789 case FK_ArrayTypeMismatch:
4790 OS << "array type mismatch";
4791 break;
4792
4793 case FK_NonConstantArrayInit:
4794 OS << "non-constant array initializer";
4795 break;
4796
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004797 case FK_AddressOfOverloadFailed:
4798 OS << "address of overloaded function failed";
4799 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004801 case FK_ReferenceInitOverloadFailed:
4802 OS << "overload resolution for reference initialization failed";
4803 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004804
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004805 case FK_NonConstLValueReferenceBindingToTemporary:
4806 OS << "non-const lvalue reference bound to temporary";
4807 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004809 case FK_NonConstLValueReferenceBindingToUnrelated:
4810 OS << "non-const lvalue reference bound to unrelated type";
4811 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004812
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004813 case FK_RValueReferenceBindingToLValue:
4814 OS << "rvalue reference bound to an lvalue";
4815 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004816
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004817 case FK_ReferenceInitDropsQualifiers:
4818 OS << "reference initialization drops qualifiers";
4819 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004821 case FK_ReferenceInitFailed:
4822 OS << "reference initialization failed";
4823 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004825 case FK_ConversionFailed:
4826 OS << "conversion failed";
4827 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828
John Wiegley01296292011-04-08 18:41:53 +00004829 case FK_ConversionFromPropertyFailed:
4830 OS << "conversion from property failed";
4831 break;
4832
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004833 case FK_TooManyInitsForScalar:
4834 OS << "too many initializers for scalar";
4835 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004837 case FK_ReferenceBindingToInitList:
4838 OS << "referencing binding to initializer list";
4839 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004840
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004841 case FK_InitListBadDestinationType:
4842 OS << "initializer list for non-aggregate, non-scalar type";
4843 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004845 case FK_UserConversionOverloadFailed:
4846 OS << "overloading failed for user-defined conversion";
4847 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004849 case FK_ConstructorOverloadFailed:
4850 OS << "constructor overloading failed";
4851 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004853 case FK_DefaultInitOfConst:
4854 OS << "default initialization of a const variable";
4855 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004857 case FK_Incomplete:
4858 OS << "initialization of incomplete type";
4859 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004860 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004861 OS << '\n';
4862 return;
4863 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004864
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004865 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00004866 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004867 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868
Sebastian Redld201edf2011-06-05 13:59:11 +00004869 case NormalSequence:
4870 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004871 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004874 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4875 if (S != step_begin()) {
4876 OS << " -> ";
4877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004878
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004879 switch (S->Kind) {
4880 case SK_ResolveAddressOfOverloadedFunction:
4881 OS << "resolve address of overloaded function";
4882 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004884 case SK_CastDerivedToBaseRValue:
4885 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4886 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004888 case SK_CastDerivedToBaseXValue:
4889 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4890 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004892 case SK_CastDerivedToBaseLValue:
4893 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4894 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004896 case SK_BindReference:
4897 OS << "bind reference to lvalue";
4898 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004899
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004900 case SK_BindReferenceToTemporary:
4901 OS << "bind reference to a temporary";
4902 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004904 case SK_ExtraneousCopyToTemporary:
4905 OS << "extraneous C++03 copy to temporary";
4906 break;
4907
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004908 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004909 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004910 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004911
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004912 case SK_QualificationConversionRValue:
4913 OS << "qualification conversion (rvalue)";
4914
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004915 case SK_QualificationConversionXValue:
4916 OS << "qualification conversion (xvalue)";
4917
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004918 case SK_QualificationConversionLValue:
4919 OS << "qualification conversion (lvalue)";
4920 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004921
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004922 case SK_ConversionSequence:
4923 OS << "implicit conversion sequence (";
4924 S->ICS->DebugPrint(); // FIXME: use OS
4925 OS << ")";
4926 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004928 case SK_ListInitialization:
4929 OS << "list initialization";
4930 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004932 case SK_ConstructorInitialization:
4933 OS << "constructor initialization";
4934 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004936 case SK_ZeroInitialization:
4937 OS << "zero initialization";
4938 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004940 case SK_CAssignment:
4941 OS << "C assignment";
4942 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004943
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004944 case SK_StringInit:
4945 OS << "string initialization";
4946 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004947
4948 case SK_ObjCObjectConversion:
4949 OS << "Objective-C object conversion";
4950 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004951
4952 case SK_ArrayInit:
4953 OS << "array initialization";
4954 break;
John McCall31168b02011-06-15 23:02:42 +00004955
4956 case SK_PassByIndirectCopyRestore:
4957 OS << "pass by indirect copy and restore";
4958 break;
4959
4960 case SK_PassByIndirectRestore:
4961 OS << "pass by indirect restore";
4962 break;
4963
4964 case SK_ProduceObjCObject:
4965 OS << "Objective-C object retension";
4966 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004967 }
4968 }
4969}
4970
4971void InitializationSequence::dump() const {
4972 dump(llvm::errs());
4973}
4974
Douglas Gregore1314a62009-12-18 05:02:21 +00004975//===----------------------------------------------------------------------===//
4976// Initialization helper functions
4977//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00004978bool
4979Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
4980 ExprResult Init) {
4981 if (Init.isInvalid())
4982 return false;
4983
4984 Expr *InitE = Init.get();
4985 assert(InitE && "No initialization expression");
4986
4987 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
4988 SourceLocation());
4989 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004990 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00004991}
4992
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004993ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004994Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4995 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004996 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004997 if (Init.isInvalid())
4998 return ExprError();
4999
John McCall1f425642010-11-11 03:21:53 +00005000 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005001 assert(InitE && "No initialization expression?");
5002
5003 if (EqualLoc.isInvalid())
5004 EqualLoc = InitE->getLocStart();
5005
5006 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5007 EqualLoc);
5008 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5009 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00005010 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005011}