blob: 58565af9cee4745cd7c098524f7fde3f7e824529 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Steve Narofff8ecff22008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
John McCall66884dd2011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattnera9196812009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnera9196812009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000055
Eli Friedman42a84652009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000062 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner0cb78032009-02-24 22:27:37 +000064 return 0;
65}
66
John McCall66884dd2011-02-21 07:22:22 +000067static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
68 const ArrayType *arrayType = Context.getAsArrayType(declType);
69 if (!arrayType) return 0;
70
71 return IsStringInit(init, arrayType, Context);
72}
73
John McCall5decec92011-02-21 07:57:55 +000074static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
75 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000076 // Get the length of the string as parsed.
77 uint64_t StrLength =
78 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
79
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner0cb78032009-02-24 22:27:37 +000081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000082 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000083 // being initialized to a string literal.
84 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000085 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000086 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000087 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
88 ConstVal,
89 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000090 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000091 }
Mike Stump11289f42009-09-09 15:08:12 +000092
Eli Friedman893abe42009-05-29 18:22:49 +000093 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000094
Eli Friedman554eba92011-04-11 00:23:45 +000095 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +000096 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +000098 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +000099 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
100 // For Pascal strings it's OK to strip off the terminating null character,
101 // so the example below is valid:
102 //
103 // unsigned char a[2] = "\pa";
104 if (SL->isPascal())
105 StrLength--;
106 }
107
Eli Friedman554eba92011-04-11 00:23:45 +0000108 // [dcl.init.string]p2
109 if (StrLength > CAT->getSize().getZExtValue())
110 S.Diag(Str->getSourceRange().getBegin(),
111 diag::err_initializer_string_for_char_array_too_long)
112 << Str->getSourceRange();
113 } else {
114 // C99 6.7.8p14.
115 if (StrLength-1 > CAT->getSize().getZExtValue())
116 S.Diag(Str->getSourceRange().getBegin(),
117 diag::warn_initializer_string_for_char_array_too_long)
118 << Str->getSourceRange();
119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Eli Friedman893abe42009-05-29 18:22:49 +0000121 // Set the type to the actual size that we are initializing. If we have
122 // something like:
123 // char x[1] = "foo";
124 // then this will set the string literal's type to char[1].
125 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000126}
127
Chris Lattner0cb78032009-02-24 22:27:37 +0000128//===----------------------------------------------------------------------===//
129// Semantic checking for initializer lists.
130//===----------------------------------------------------------------------===//
131
Douglas Gregorcde232f2009-01-29 01:05:33 +0000132/// @brief Semantic checking for initializer lists.
133///
134/// The InitListChecker class contains a set of routines that each
135/// handle the initialization of a certain kind of entity, e.g.,
136/// arrays, vectors, struct/union types, scalars, etc. The
137/// InitListChecker itself performs a recursive walk of the subobject
138/// structure of the type to be initialized, while stepping through
139/// the initializer list one element at a time. The IList and Index
140/// parameters to each of the Check* routines contain the active
141/// (syntactic) initializer list and the index into that initializer
142/// list that represents the current initializer. Each routine is
143/// responsible for moving that Index forward as it consumes elements.
144///
145/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000146/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000147/// initializer list and the index into that initializer list where we
148/// are copying initializers as we map them over to the semantic
149/// list. Once we have completed our recursive walk of the subobject
150/// structure, we will have constructed a full semantic initializer
151/// list.
152///
153/// C99 designators cause changes in the initializer list traversal,
154/// because they make the initialization "jump" into a specific
155/// subobject and then continue the initialization from that
156/// point. CheckDesignatedInitializer() recursively steps into the
157/// designated subobject and manages backing out the recursion to
158/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000159namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000160class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000161 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000162 bool hadError;
163 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
164 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000165
Anders Carlsson6cabf312010-01-23 23:23:01 +0000166 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000167 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000168 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000169 unsigned &StructuredIndex,
170 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000171 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000172 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000173 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000174 unsigned &StructuredIndex,
175 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000178 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000179 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000180 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000181 unsigned &StructuredIndex,
182 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000183 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000185 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000186 InitListExpr *StructuredList,
187 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckReferenceType(const InitializedEntity &Entity,
194 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000195 unsigned &Index,
196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000198 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000202 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000203 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000204 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000209 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000210 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000211 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000212 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000216 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
227 QualType CurrentObjectType,
228 InitListExpr *StructuredList,
229 unsigned StructuredIndex,
230 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000236
Douglas Gregor2bb07652009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000245 bool HadError() { return hadError; }
246
247 // @brief Retrieves the fully-structured initializer list used for
248 // semantic analysis and code generation.
249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
250};
Chris Lattner9ececce2009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000252
Douglas Gregor2bb07652009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000260 = InitializedEntity::InitializeMember(Field, &ParentEntity);
261 if (Init >= NumInits || !ILE->getInit(Init)) {
262 // FIXME: We probably don't need to handle references
263 // specially here, since value-initialization of references is
264 // handled in InitializationSequence.
265 if (Field->getType()->isReferenceType()) {
266 // C++ [dcl.init.aggr]p9:
267 // If an incomplete or empty initializer-list leaves a
268 // member of reference type uninitialized, the program is
269 // ill-formed.
270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
271 << Field->getType()
272 << ILE->getSyntacticForm()->getSourceRange();
273 SemaRef.Diag(Field->getLocation(),
274 diag::note_uninit_reference_member);
275 hadError = true;
276 return;
277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
Douglas Gregor2bb07652009-12-22 00:05:34 +0000279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
282 if (!InitSeq) {
283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
284 hadError = true;
285 return;
286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
John McCalldadc5752010-08-24 06:29:42 +0000288 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000290 if (MemberInit.isInvalid()) {
291 hadError = true;
292 return;
293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 if (hadError) {
296 // Do nothing
297 } else if (Init < NumInits) {
298 ILE->setInit(Init, MemberInit.takeAs<Expr>());
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
715 // initializing the aggregate member with an ini- tializer from
716 // 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.
772 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
773 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
774 StructuredIndex);
775 ++StructuredIndex;
776 } else {
777 // We cannot initialize this element, so let
778 // PerformCopyInitialization produce the appropriate diagnostic.
779 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
780 SemaRef.Owned(expr));
781 hadError = true;
782 ++Index;
783 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000784 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000785}
786
Anders Carlsson6cabf312010-01-23 23:23:01 +0000787void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000788 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000789 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000790 InitListExpr *StructuredList,
791 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000792 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000793 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000794 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000795 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000796 ++Index;
797 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000798 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000799 }
John McCall643169b2010-11-11 00:46:36 +0000800
801 Expr *expr = IList->getInit(Index);
802 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
803 SemaRef.Diag(SubIList->getLocStart(),
804 diag::warn_many_braces_around_scalar_init)
805 << SubIList->getSourceRange();
806
807 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
808 StructuredIndex);
809 return;
810 } else if (isa<DesignatedInitExpr>(expr)) {
811 SemaRef.Diag(expr->getSourceRange().getBegin(),
812 diag::err_designator_for_scalar_init)
813 << DeclType << expr->getSourceRange();
814 hadError = true;
815 ++Index;
816 ++StructuredIndex;
817 return;
818 }
819
820 ExprResult Result =
821 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
822 SemaRef.Owned(expr));
823
824 Expr *ResultExpr = 0;
825
826 if (Result.isInvalid())
827 hadError = true; // types weren't compatible.
828 else {
829 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830
John McCall643169b2010-11-11 00:46:36 +0000831 if (ResultExpr != expr) {
832 // The type was promoted, update initializer list.
833 IList->setInit(Index, ResultExpr);
834 }
835 }
836 if (hadError)
837 ++StructuredIndex;
838 else
839 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
840 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000841}
842
Anders Carlsson6cabf312010-01-23 23:23:01 +0000843void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
844 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000845 unsigned &Index,
846 InitListExpr *StructuredList,
847 unsigned &StructuredIndex) {
848 if (Index < IList->getNumInits()) {
849 Expr *expr = IList->getInit(Index);
850 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000851 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000852 << DeclType << IList->getSourceRange();
853 hadError = true;
854 ++Index;
855 ++StructuredIndex;
856 return;
Mike Stump11289f42009-09-09 15:08:12 +0000857 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000858
John McCalldadc5752010-08-24 06:29:42 +0000859 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000860 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
861 SemaRef.Owned(expr));
862
863 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000864 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000865
866 expr = Result.takeAs<Expr>();
867 IList->setInit(Index, expr);
868
Douglas Gregord14247a2009-01-30 22:09:00 +0000869 if (hadError)
870 ++StructuredIndex;
871 else
872 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
873 ++Index;
874 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000875 // FIXME: It would be wonderful if we could point at the actual member. In
876 // general, it would be useful to pass location information down the stack,
877 // so that we know the location (or decl) of the "current object" being
878 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000879 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000880 diag::err_init_reference_member_uninitialized)
881 << DeclType
882 << IList->getSourceRange();
883 hadError = true;
884 ++Index;
885 ++StructuredIndex;
886 return;
887 }
888}
889
Anders Carlsson6cabf312010-01-23 23:23:01 +0000890void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000891 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000892 unsigned &Index,
893 InitListExpr *StructuredList,
894 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000895 if (Index >= IList->getNumInits())
896 return;
Mike Stump11289f42009-09-09 15:08:12 +0000897
John McCall6a16b2f2010-10-30 00:11:39 +0000898 const VectorType *VT = DeclType->getAs<VectorType>();
899 unsigned maxElements = VT->getNumElements();
900 unsigned numEltsInit = 0;
901 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000902
John McCall6a16b2f2010-10-30 00:11:39 +0000903 if (!SemaRef.getLangOptions().OpenCL) {
904 // If the initializing element is a vector, try to copy-initialize
905 // instead of breaking it apart (which is doomed to failure anyway).
906 Expr *Init = IList->getInit(Index);
907 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
908 ExprResult Result =
909 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
910 SemaRef.Owned(Init));
911
912 Expr *ResultExpr = 0;
913 if (Result.isInvalid())
914 hadError = true; // types weren't compatible.
915 else {
916 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000917
John McCall6a16b2f2010-10-30 00:11:39 +0000918 if (ResultExpr != Init) {
919 // The type was promoted, update initializer list.
920 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000921 }
922 }
John McCall6a16b2f2010-10-30 00:11:39 +0000923 if (hadError)
924 ++StructuredIndex;
925 else
926 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
927 ++Index;
928 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930
John McCall6a16b2f2010-10-30 00:11:39 +0000931 InitializedEntity ElementEntity =
932 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000933
John McCall6a16b2f2010-10-30 00:11:39 +0000934 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
935 // Don't attempt to go past the end of the init list
936 if (Index >= IList->getNumInits())
937 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938
John McCall6a16b2f2010-10-30 00:11:39 +0000939 ElementEntity.setElementIndex(Index);
940 CheckSubElementType(ElementEntity, IList, elementType, Index,
941 StructuredList, StructuredIndex);
942 }
943 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000944 }
John McCall6a16b2f2010-10-30 00:11:39 +0000945
946 InitializedEntity ElementEntity =
947 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000948
John McCall6a16b2f2010-10-30 00:11:39 +0000949 // OpenCL initializers allows vectors to be constructed from vectors.
950 for (unsigned i = 0; i < maxElements; ++i) {
951 // Don't attempt to go past the end of the init list
952 if (Index >= IList->getNumInits())
953 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954
John McCall6a16b2f2010-10-30 00:11:39 +0000955 ElementEntity.setElementIndex(Index);
956
957 QualType IType = IList->getInit(Index)->getType();
958 if (!IType->isVectorType()) {
959 CheckSubElementType(ElementEntity, IList, elementType, Index,
960 StructuredList, StructuredIndex);
961 ++numEltsInit;
962 } else {
963 QualType VecType;
964 const VectorType *IVT = IType->getAs<VectorType>();
965 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000966
John McCall6a16b2f2010-10-30 00:11:39 +0000967 if (IType->isExtVectorType())
968 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
969 else
970 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000971 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000972 CheckSubElementType(ElementEntity, IList, VecType, Index,
973 StructuredList, StructuredIndex);
974 numEltsInit += numIElts;
975 }
976 }
977
978 // OpenCL requires all elements to be initialized.
979 if (numEltsInit != maxElements)
980 if (SemaRef.getLangOptions().OpenCL)
981 SemaRef.Diag(IList->getSourceRange().getBegin(),
982 diag::err_vector_incorrect_num_initializers)
983 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000984}
985
Anders Carlsson6cabf312010-01-23 23:23:01 +0000986void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000987 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000988 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000989 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000990 unsigned &Index,
991 InitListExpr *StructuredList,
992 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000993 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
994
Steve Narofff8ecff22008-05-01 22:18:59 +0000995 // Check for the special-case of initializing an array with a string.
996 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +0000997 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000998 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +0000999 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001000 // We place the string literal directly into the resulting
1001 // initializer list. This is the only place where the structure
1002 // of the structured initializer list doesn't match exactly,
1003 // because doing so would involve allocating one character
1004 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +00001005 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +00001006 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001007 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001008 return;
1009 }
1010 }
John McCall66884dd2011-02-21 07:22:22 +00001011 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001012 // Check for VLAs; in standard C it would be possible to check this
1013 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1014 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001015 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001016 diag::err_variable_object_no_init)
1017 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001018 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001019 ++Index;
1020 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001021 return;
1022 }
1023
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001024 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001025 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1026 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001027 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001028 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001029 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001030 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001031 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001032 maxElementsKnown = true;
1033 }
1034
John McCall66884dd2011-02-21 07:22:22 +00001035 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001036 while (Index < IList->getNumInits()) {
1037 Expr *Init = IList->getInit(Index);
1038 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001039 // If we're not the subobject that matches up with the '{' for
1040 // the designator, we shouldn't be handling the
1041 // designator. Return immediately.
1042 if (!SubobjectIsDesignatorContext)
1043 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001044
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001045 // Handle this designated initializer. elementIndex will be
1046 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001047 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001048 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001049 StructuredList, StructuredIndex, true,
1050 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001051 hadError = true;
1052 continue;
1053 }
1054
Douglas Gregor033d1252009-01-23 16:54:12 +00001055 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001056 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001057 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001058 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001059 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001060
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001061 // If the array is of incomplete type, keep track of the number of
1062 // elements in the initializer.
1063 if (!maxElementsKnown && elementIndex > maxElements)
1064 maxElements = elementIndex;
1065
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001066 continue;
1067 }
1068
1069 // If we know the maximum number of elements, and we've already
1070 // hit it, stop consuming elements in the initializer list.
1071 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001072 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001073
Anders Carlsson6cabf312010-01-23 23:23:01 +00001074 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001075 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001076 Entity);
1077 // Check this element.
1078 CheckSubElementType(ElementEntity, IList, elementType, Index,
1079 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001080 ++elementIndex;
1081
1082 // If the array is of incomplete type, keep track of the number of
1083 // elements in the initializer.
1084 if (!maxElementsKnown && elementIndex > maxElements)
1085 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001086 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001087 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001088 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001089 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001090 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001091 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001092 // Sizing an array implicitly to zero is not allowed by ISO C,
1093 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001094 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001095 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001096 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001097
Mike Stump11289f42009-09-09 15:08:12 +00001098 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001099 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001100 }
1101}
1102
Anders Carlsson6cabf312010-01-23 23:23:01 +00001103void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001104 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001105 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001106 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001107 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001108 unsigned &Index,
1109 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001110 unsigned &StructuredIndex,
1111 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001112 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001113
Eli Friedman23a9e312008-05-19 19:16:24 +00001114 // If the record is invalid, some of it's members are invalid. To avoid
1115 // confusion, we forgo checking the intializer for the entire record.
1116 if (structDecl->isInvalidDecl()) {
1117 hadError = true;
1118 return;
Mike Stump11289f42009-09-09 15:08:12 +00001119 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001120
1121 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1122 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001123 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001124 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001125 Field != FieldEnd; ++Field) {
1126 if (Field->getDeclName()) {
1127 StructuredList->setInitializedFieldInUnion(*Field);
1128 break;
1129 }
1130 }
1131 return;
1132 }
1133
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001134 // If structDecl is a forward declaration, this loop won't do
1135 // anything except look at designated initializers; That's okay,
1136 // because an error should get printed out elsewhere. It might be
1137 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001138 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001139 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001140 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001141 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001142 while (Index < IList->getNumInits()) {
1143 Expr *Init = IList->getInit(Index);
1144
1145 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001146 // If we're not the subobject that matches up with the '{' for
1147 // the designator, we shouldn't be handling the
1148 // designator. Return immediately.
1149 if (!SubobjectIsDesignatorContext)
1150 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001151
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001152 // Handle this designated initializer. Field will be updated to
1153 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001154 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001155 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001156 StructuredList, StructuredIndex,
1157 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001158 hadError = true;
1159
Douglas Gregora9add4e2009-02-12 19:00:39 +00001160 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001161
1162 // Disable check for missing fields when designators are used.
1163 // This matches gcc behaviour.
1164 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001165 continue;
1166 }
1167
1168 if (Field == FieldEnd) {
1169 // We've run out of fields. We're done.
1170 break;
1171 }
1172
Douglas Gregora9add4e2009-02-12 19:00:39 +00001173 // We've already initialized a member of a union. We're done.
1174 if (InitializedSomething && DeclType->isUnionType())
1175 break;
1176
Douglas Gregor91f84212008-12-11 16:49:14 +00001177 // If we've hit the flexible array member at the end, we're done.
1178 if (Field->getType()->isIncompleteArrayType())
1179 break;
1180
Douglas Gregor51695702009-01-29 16:53:55 +00001181 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001182 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001183 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001184 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001185 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001186
Douglas Gregora82064c2011-06-29 21:51:31 +00001187 // Make sure we can use this declaration.
1188 if (SemaRef.DiagnoseUseOfDecl(*Field,
1189 IList->getInit(Index)->getLocStart())) {
1190 ++Index;
1191 ++Field;
1192 hadError = true;
1193 continue;
1194 }
1195
Anders Carlsson6cabf312010-01-23 23:23:01 +00001196 InitializedEntity MemberEntity =
1197 InitializedEntity::InitializeMember(*Field, &Entity);
1198 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1199 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001200 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001201
1202 if (DeclType->isUnionType()) {
1203 // Initialize the first field within the union.
1204 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001205 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001206
1207 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001208 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001209
John McCalle40b58e2010-03-11 19:32:38 +00001210 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001212 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1213 // It is possible we have one or more unnamed bitfields remaining.
1214 // Find first (if any) named field and emit warning.
1215 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1216 it != end; ++it) {
1217 if (!it->isUnnamedBitfield()) {
1218 SemaRef.Diag(IList->getSourceRange().getEnd(),
1219 diag::warn_missing_field_initializers) << it->getName();
1220 break;
1221 }
1222 }
1223 }
1224
Mike Stump11289f42009-09-09 15:08:12 +00001225 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001226 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001227 return;
1228
1229 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001230 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001231 (!isa<InitListExpr>(IList->getInit(Index)) ||
1232 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001233 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001234 diag::err_flexible_array_init_nonempty)
1235 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001236 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001237 << *Field;
1238 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001239 ++Index;
1240 return;
1241 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001242 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001243 diag::ext_flexible_array_init)
1244 << IList->getInit(Index)->getSourceRange().getBegin();
1245 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1246 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001247 }
1248
Anders Carlsson6cabf312010-01-23 23:23:01 +00001249 InitializedEntity MemberEntity =
1250 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251
Anders Carlsson6cabf312010-01-23 23:23:01 +00001252 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001254 StructuredList, StructuredIndex);
1255 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001256 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001257 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001258}
Steve Narofff8ecff22008-05-01 22:18:59 +00001259
Douglas Gregord5846a12009-04-15 06:41:24 +00001260/// \brief Expand a field designator that refers to a member of an
1261/// anonymous struct or union into a series of field designators that
1262/// refers to the field within the appropriate subobject.
1263///
Douglas Gregord5846a12009-04-15 06:41:24 +00001264static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001265 DesignatedInitExpr *DIE,
1266 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001267 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001268 typedef DesignatedInitExpr::Designator Designator;
1269
Douglas Gregord5846a12009-04-15 06:41:24 +00001270 // Build the replacement designators.
1271 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001272 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1273 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1274 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001275 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001276 DIE->getDesignator(DesigIdx)->getDotLoc(),
1277 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1278 else
1279 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1280 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001281 assert(isa<FieldDecl>(*PI));
1282 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001283 }
1284
1285 // Expand the current designator into the set of replacement
1286 // designators, so we have a full subobject path down to where the
1287 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001288 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001289 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001290}
Mike Stump11289f42009-09-09 15:08:12 +00001291
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001293/// corresponds to FieldName.
1294static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1295 IdentifierInfo *FieldName) {
1296 assert(AnonField->isAnonymousStructOrUnion());
1297 Decl *NextDecl = AnonField->getNextDeclInContext();
1298 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1299 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1300 return IF;
1301 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001302 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001303 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001304}
1305
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001306/// @brief Check the well-formedness of a C99 designated initializer.
1307///
1308/// Determines whether the designated initializer @p DIE, which
1309/// resides at the given @p Index within the initializer list @p
1310/// IList, is well-formed for a current object of type @p DeclType
1311/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001312/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001313/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001314///
1315/// @param IList The initializer list in which this designated
1316/// initializer occurs.
1317///
Douglas Gregora5324162009-04-15 04:56:10 +00001318/// @param DIE The designated initializer expression.
1319///
1320/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001321///
1322/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1323/// into which the designation in @p DIE should refer.
1324///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001325/// @param NextField If non-NULL and the first designator in @p DIE is
1326/// a field, this will be set to the field declaration corresponding
1327/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001328///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001329/// @param NextElementIndex If non-NULL and the first designator in @p
1330/// DIE is an array designator or GNU array-range designator, this
1331/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001332///
1333/// @param Index Index into @p IList where the designated initializer
1334/// @p DIE occurs.
1335///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001336/// @param StructuredList The initializer list expression that
1337/// describes all of the subobject initializers in the order they'll
1338/// actually be initialized.
1339///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001340/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001341bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001342InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001343 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001344 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001345 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001346 QualType &CurrentObjectType,
1347 RecordDecl::field_iterator *NextField,
1348 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001349 unsigned &Index,
1350 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001351 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001352 bool FinishSubobjectInit,
1353 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001354 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001355 // Check the actual initialization for the designated object type.
1356 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001357
1358 // Temporarily remove the designator expression from the
1359 // initializer list that the child calls see, so that we don't try
1360 // to re-process the designator.
1361 unsigned OldIndex = Index;
1362 IList->setInit(OldIndex, DIE->getInit());
1363
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001364 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001365 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001366
1367 // Restore the designated initializer expression in the syntactic
1368 // form of the initializer list.
1369 if (IList->getInit(OldIndex) != DIE->getInit())
1370 DIE->setInit(IList->getInit(OldIndex));
1371 IList->setInit(OldIndex, DIE);
1372
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001373 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001374 }
1375
Douglas Gregora5324162009-04-15 04:56:10 +00001376 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001377 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001378 "Need a non-designated initializer list to start from");
1379
Douglas Gregora5324162009-04-15 04:56:10 +00001380 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001381 // Determine the structural initializer list that corresponds to the
1382 // current subobject.
1383 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001384 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001385 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001386 SourceRange(D->getStartLocation(),
1387 DIE->getSourceRange().getEnd()));
1388 assert(StructuredList && "Expected a structured initializer list");
1389
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001390 if (D->isFieldDesignator()) {
1391 // C99 6.7.8p7:
1392 //
1393 // If a designator has the form
1394 //
1395 // . identifier
1396 //
1397 // then the current object (defined below) shall have
1398 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001399 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001400 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001401 if (!RT) {
1402 SourceLocation Loc = D->getDotLoc();
1403 if (Loc.isInvalid())
1404 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001405 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1406 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001407 ++Index;
1408 return true;
1409 }
1410
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001411 // Note: we perform a linear search of the fields here, despite
1412 // the fact that we have a faster lookup method, because we always
1413 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001414 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001415 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001416 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001417 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001418 Field = RT->getDecl()->field_begin(),
1419 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001420 for (; Field != FieldEnd; ++Field) {
1421 if (Field->isUnnamedBitfield())
1422 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001424 // If we find a field representing an anonymous field, look in the
1425 // IndirectFieldDecl that follow for the designated initializer.
1426 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1427 if (IndirectFieldDecl *IF =
1428 FindIndirectFieldDesignator(*Field, FieldName)) {
1429 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1430 D = DIE->getDesignator(DesigIdx);
1431 break;
1432 }
1433 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001434 if (KnownField && KnownField == *Field)
1435 break;
1436 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001437 break;
1438
1439 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001440 }
1441
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001442 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001443 // There was no normal field in the struct with the designated
1444 // name. Perform another lookup for this name, which may find
1445 // something that we can't designate (e.g., a member function),
1446 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001447 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001448 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001449 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001450 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001451 // Name lookup didn't find anything. Determine whether this
1452 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001453 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001454 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001455 TypoCorrection Corrected = SemaRef.CorrectTypo(
1456 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1457 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1458 RT->getDecl(), false, Sema::CTC_NoKeywords);
1459 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001460 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001461 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001462 std::string CorrectedStr(
1463 Corrected.getAsString(SemaRef.getLangOptions()));
1464 std::string CorrectedQuotedStr(
1465 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001467 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001468 << FieldName << CurrentObjectType << CorrectedQuotedStr
1469 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001471 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001472 } else {
1473 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1474 << FieldName << CurrentObjectType;
1475 ++Index;
1476 return true;
1477 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001479
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001480 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001481 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001482 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001483 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001484 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001485 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001486 ++Index;
1487 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001488 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001489
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001490 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001491 // The replacement field comes from typo correction; find it
1492 // in the list of fields.
1493 FieldIndex = 0;
1494 Field = RT->getDecl()->field_begin();
1495 for (; Field != FieldEnd; ++Field) {
1496 if (Field->isUnnamedBitfield())
1497 continue;
1498
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001499 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001500 Field->getIdentifier() == ReplacementField->getIdentifier())
1501 break;
1502
1503 ++FieldIndex;
1504 }
1505 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001506 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001507
1508 // All of the fields of a union are located at the same place in
1509 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001510 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001511 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001512 StructuredList->setInitializedFieldInUnion(*Field);
1513 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001514
Douglas Gregora82064c2011-06-29 21:51:31 +00001515 // Make sure we can use this declaration.
1516 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1517 ++Index;
1518 return true;
1519 }
1520
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001521 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001522 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001523
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001524 // Make sure that our non-designated initializer list has space
1525 // for a subobject corresponding to this field.
1526 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001527 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001528
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001529 // This designator names a flexible array member.
1530 if (Field->getType()->isIncompleteArrayType()) {
1531 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001532 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001533 // We can't designate an object within the flexible array
1534 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001535 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001536 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001537 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001538 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001539 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001540 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001541 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001542 << *Field;
1543 Invalid = true;
1544 }
1545
Chris Lattner001b29c2010-10-10 17:49:49 +00001546 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1547 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001548 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001549 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001550 diag::err_flexible_array_init_needs_braces)
1551 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001552 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001553 << *Field;
1554 Invalid = true;
1555 }
1556
1557 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001558 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001559 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001560 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001561 diag::err_flexible_array_init_nonempty)
1562 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001563 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001564 << *Field;
1565 Invalid = true;
1566 }
1567
1568 if (Invalid) {
1569 ++Index;
1570 return true;
1571 }
1572
1573 // Initialize the array.
1574 bool prevHadError = hadError;
1575 unsigned newStructuredIndex = FieldIndex;
1576 unsigned OldIndex = Index;
1577 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001578
1579 InitializedEntity MemberEntity =
1580 InitializedEntity::InitializeMember(*Field, &Entity);
1581 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001582 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001583
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001584 IList->setInit(OldIndex, DIE);
1585 if (hadError && !prevHadError) {
1586 ++Field;
1587 ++FieldIndex;
1588 if (NextField)
1589 *NextField = Field;
1590 StructuredIndex = FieldIndex;
1591 return true;
1592 }
1593 } else {
1594 // Recurse to check later designated subobjects.
1595 QualType FieldType = (*Field)->getType();
1596 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001598 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001599 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001600 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1601 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001602 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001603 true, false))
1604 return true;
1605 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606
1607 // Find the position of the next field to be initialized in this
1608 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001609 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001610 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001611
1612 // If this the first designator, our caller will continue checking
1613 // the rest of this struct/class/union subobject.
1614 if (IsFirstDesignator) {
1615 if (NextField)
1616 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001617 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001618 return false;
1619 }
1620
Douglas Gregor17bd0942009-01-28 23:36:17 +00001621 if (!FinishSubobjectInit)
1622 return false;
1623
Douglas Gregord5846a12009-04-15 06:41:24 +00001624 // We've already initialized something in the union; we're done.
1625 if (RT->getDecl()->isUnion())
1626 return hadError;
1627
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001628 // Check the remaining fields within this class/struct/union subobject.
1629 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001630
Anders Carlsson6cabf312010-01-23 23:23:01 +00001631 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001632 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001633 return hadError && !prevHadError;
1634 }
1635
1636 // C99 6.7.8p6:
1637 //
1638 // If a designator has the form
1639 //
1640 // [ constant-expression ]
1641 //
1642 // then the current object (defined below) shall have array
1643 // type and the expression shall be an integer constant
1644 // expression. If the array is of unknown size, any
1645 // nonnegative value is valid.
1646 //
1647 // Additionally, cope with the GNU extension that permits
1648 // designators of the form
1649 //
1650 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001651 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001652 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001653 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001654 << CurrentObjectType;
1655 ++Index;
1656 return true;
1657 }
1658
1659 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001660 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1661 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001662 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001663 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001664 DesignatedEndIndex = DesignatedStartIndex;
1665 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001666 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001667
Mike Stump11289f42009-09-09 15:08:12 +00001668 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001669 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001670 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001671 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001672 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001673
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001674 // Codegen can't handle evaluating array range designators that have side
1675 // effects, because we replicate the AST value for each initialized element.
1676 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1677 // elements with something that has a side effect, so codegen can emit an
1678 // "error unsupported" error instead of miscompiling the app.
1679 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1680 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001681 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001682 }
1683
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001684 if (isa<ConstantArrayType>(AT)) {
1685 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001686 DesignatedStartIndex
1687 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001688 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001689 DesignatedEndIndex
1690 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001691 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1692 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001693 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001694 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001695 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001696 << IndexExpr->getSourceRange();
1697 ++Index;
1698 return true;
1699 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001700 } else {
1701 // Make sure the bit-widths and signedness match.
1702 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001703 DesignatedEndIndex
1704 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001705 else if (DesignatedStartIndex.getBitWidth() <
1706 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001707 DesignatedStartIndex
1708 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001709 DesignatedStartIndex.setIsUnsigned(true);
1710 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001713 // Make sure that our non-designated initializer list has space
1714 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001715 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001716 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001717 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001718
Douglas Gregor17bd0942009-01-28 23:36:17 +00001719 // Repeatedly perform subobject initializations in the range
1720 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001721
Douglas Gregor17bd0942009-01-28 23:36:17 +00001722 // Move to the next designator
1723 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1724 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001726 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001727 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001728
Douglas Gregor17bd0942009-01-28 23:36:17 +00001729 while (DesignatedStartIndex <= DesignatedEndIndex) {
1730 // Recurse to check later designated subobjects.
1731 QualType ElementType = AT->getElementType();
1732 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001734 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1736 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001737 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001738 (DesignatedStartIndex == DesignatedEndIndex),
1739 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001740 return true;
1741
1742 // Move to the next index in the array that we'll be initializing.
1743 ++DesignatedStartIndex;
1744 ElementIndex = DesignatedStartIndex.getZExtValue();
1745 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001746
1747 // If this the first designator, our caller will continue checking
1748 // the rest of this array subobject.
1749 if (IsFirstDesignator) {
1750 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001751 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001752 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001753 return false;
1754 }
Mike Stump11289f42009-09-09 15:08:12 +00001755
Douglas Gregor17bd0942009-01-28 23:36:17 +00001756 if (!FinishSubobjectInit)
1757 return false;
1758
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001759 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001760 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001762 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001763 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001764 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001765}
1766
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001767// Get the structured initializer list for a subobject of type
1768// @p CurrentObjectType.
1769InitListExpr *
1770InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1771 QualType CurrentObjectType,
1772 InitListExpr *StructuredList,
1773 unsigned StructuredIndex,
1774 SourceRange InitRange) {
1775 Expr *ExistingInit = 0;
1776 if (!StructuredList)
1777 ExistingInit = SyntacticToSemantic[IList];
1778 else if (StructuredIndex < StructuredList->getNumInits())
1779 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001780
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001781 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1782 return Result;
1783
1784 if (ExistingInit) {
1785 // We are creating an initializer list that initializes the
1786 // subobjects of the current object, but there was already an
1787 // initialization that completely initialized the current
1788 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001789 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001790 // struct X { int a, b; };
1791 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001792 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001793 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1794 // designated initializer re-initializes the whole
1795 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001796 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001797 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001798 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001799 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001800 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001801 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001802 << ExistingInit->getSourceRange();
1803 }
1804
Mike Stump11289f42009-09-09 15:08:12 +00001805 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001806 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1807 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001808 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001809
Douglas Gregora8a089b2010-07-13 18:40:04 +00001810 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001811
Douglas Gregor6d00c992009-03-20 23:58:33 +00001812 // Pre-allocate storage for the structured initializer list.
1813 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001814 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001815 bool GotNumInits = false;
1816 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001817 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001818 GotNumInits = true;
1819 } else if (Index < IList->getNumInits()) {
1820 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001821 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001822 GotNumInits = true;
1823 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00001824 }
1825
Mike Stump11289f42009-09-09 15:08:12 +00001826 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001827 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1828 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1829 NumElements = CAType->getSize().getZExtValue();
1830 // Simple heuristic so that we don't allocate a very large
1831 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001832 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001833 NumElements = 0;
1834 }
John McCall9dd450b2009-09-21 23:43:11 +00001835 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001836 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001837 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001838 RecordDecl *RDecl = RType->getDecl();
1839 if (RDecl->isUnion())
1840 NumElements = 1;
1841 else
Mike Stump11289f42009-09-09 15:08:12 +00001842 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001843 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001844 }
1845
Douglas Gregor221c9a52009-03-21 18:13:52 +00001846 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001847 NumElements = IList->getNumInits();
1848
Ted Kremenekac034612010-04-13 23:39:13 +00001849 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001850
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001851 // Link this new initializer list into the structured initializer
1852 // lists.
1853 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001854 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001855 else {
1856 Result->setSyntacticForm(IList);
1857 SyntacticToSemantic[IList] = Result;
1858 }
1859
1860 return Result;
1861}
1862
1863/// Update the initializer at index @p StructuredIndex within the
1864/// structured initializer list to the value @p expr.
1865void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1866 unsigned &StructuredIndex,
1867 Expr *expr) {
1868 // No structured initializer list to update
1869 if (!StructuredList)
1870 return;
1871
Ted Kremenekac034612010-04-13 23:39:13 +00001872 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1873 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001874 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001875 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001876 diag::warn_initializer_overrides)
1877 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001878 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001879 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001880 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001881 << PrevInit->getSourceRange();
1882 }
Mike Stump11289f42009-09-09 15:08:12 +00001883
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001884 ++StructuredIndex;
1885}
1886
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001887/// Check that the given Index expression is a valid array designator
1888/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001889/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001890/// and produces a reasonable diagnostic if there is a
1891/// failure. Returns true if there was an error, false otherwise. If
1892/// everything went okay, Value will receive the value of the constant
1893/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001894static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001895CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001896 SourceLocation Loc = Index->getSourceRange().getBegin();
1897
1898 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001899 if (S.VerifyIntegerConstantExpression(Index, &Value))
1900 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001901
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001902 if (Value.isSigned() && Value.isNegative())
1903 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001904 << Value.toString(10) << Index->getSourceRange();
1905
Douglas Gregor51650d32009-01-23 21:04:18 +00001906 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001907 return false;
1908}
1909
John McCalldadc5752010-08-24 06:29:42 +00001910ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001911 SourceLocation Loc,
1912 bool GNUSyntax,
1913 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001914 typedef DesignatedInitExpr::Designator ASTDesignator;
1915
1916 bool Invalid = false;
1917 llvm::SmallVector<ASTDesignator, 32> Designators;
1918 llvm::SmallVector<Expr *, 32> InitExpressions;
1919
1920 // Build designators and check array designator expressions.
1921 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1922 const Designator &D = Desig.getDesignator(Idx);
1923 switch (D.getKind()) {
1924 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001925 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001926 D.getFieldLoc()));
1927 break;
1928
1929 case Designator::ArrayDesignator: {
1930 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1931 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001932 if (!Index->isTypeDependent() &&
1933 !Index->isValueDependent() &&
1934 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001935 Invalid = true;
1936 else {
1937 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001938 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001939 D.getRBracketLoc()));
1940 InitExpressions.push_back(Index);
1941 }
1942 break;
1943 }
1944
1945 case Designator::ArrayRangeDesignator: {
1946 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1947 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1948 llvm::APSInt StartValue;
1949 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001950 bool StartDependent = StartIndex->isTypeDependent() ||
1951 StartIndex->isValueDependent();
1952 bool EndDependent = EndIndex->isTypeDependent() ||
1953 EndIndex->isValueDependent();
1954 if ((!StartDependent &&
1955 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1956 (!EndDependent &&
1957 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001958 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001959 else {
1960 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001961 if (StartDependent || EndDependent) {
1962 // Nothing to compute.
1963 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001964 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001965 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001966 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001967
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001968 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001969 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001970 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001971 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1972 Invalid = true;
1973 } else {
1974 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001975 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001976 D.getEllipsisLoc(),
1977 D.getRBracketLoc()));
1978 InitExpressions.push_back(StartIndex);
1979 InitExpressions.push_back(EndIndex);
1980 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001981 }
1982 break;
1983 }
1984 }
1985 }
1986
1987 if (Invalid || Init.isInvalid())
1988 return ExprError();
1989
1990 // Clear out the expressions within the designation.
1991 Desig.ClearExprs(*this);
1992
1993 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001994 = DesignatedInitExpr::Create(Context,
1995 Designators.data(), Designators.size(),
1996 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001997 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998
Douglas Gregorc124e592011-01-16 16:13:16 +00001999 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002000 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2001 << DIE->getSourceRange();
2002 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002003 Diag(DIE->getLocStart(), diag::ext_designated_init)
2004 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002005
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002006 return Owned(DIE);
2007}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002008
Douglas Gregor723796a2009-12-16 06:35:08 +00002009bool Sema::CheckInitList(const InitializedEntity &Entity,
2010 InitListExpr *&InitList, QualType &DeclType) {
2011 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00002012 if (!CheckInitList.HadError())
2013 InitList = CheckInitList.getFullyStructuredList();
2014
2015 return CheckInitList.HadError();
2016}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00002017
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002018//===----------------------------------------------------------------------===//
2019// Initialization entity
2020//===----------------------------------------------------------------------===//
2021
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002022InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002023 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002025{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002026 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2027 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002028 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002029 } else {
2030 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002031 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002032 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002033}
2034
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002035InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002036 CXXBaseSpecifier *Base,
2037 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002038{
2039 InitializedEntity Result;
2040 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002041 Result.Base = reinterpret_cast<uintptr_t>(Base);
2042 if (IsInheritedVirtualBase)
2043 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002044
Douglas Gregor1b303932009-12-22 15:35:07 +00002045 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002046 return Result;
2047}
2048
Douglas Gregor85dabae2009-12-16 01:38:02 +00002049DeclarationName InitializedEntity::getName() const {
2050 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002051 case EK_Parameter: {
2052 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2053 return (D ? D->getDeclName() : DeclarationName());
2054 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002055
2056 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002057 case EK_Member:
2058 return VariableOrMember->getDeclName();
2059
2060 case EK_Result:
2061 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002062 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002063 case EK_Temporary:
2064 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002065 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002066 case EK_ArrayElement:
2067 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002068 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002069 return DeclarationName();
2070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071
Douglas Gregor85dabae2009-12-16 01:38:02 +00002072 // Silence GCC warning
2073 return DeclarationName();
2074}
2075
Douglas Gregora4b592a2009-12-19 03:01:41 +00002076DeclaratorDecl *InitializedEntity::getDecl() const {
2077 switch (getKind()) {
2078 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002079 case EK_Member:
2080 return VariableOrMember;
2081
John McCall31168b02011-06-15 23:02:42 +00002082 case EK_Parameter:
2083 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2084
Douglas Gregora4b592a2009-12-19 03:01:41 +00002085 case EK_Result:
2086 case EK_Exception:
2087 case EK_New:
2088 case EK_Temporary:
2089 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002090 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002091 case EK_ArrayElement:
2092 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002093 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002094 return 0;
2095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002096
Douglas Gregora4b592a2009-12-19 03:01:41 +00002097 // Silence GCC warning
2098 return 0;
2099}
2100
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002101bool InitializedEntity::allowsNRVO() const {
2102 switch (getKind()) {
2103 case EK_Result:
2104 case EK_Exception:
2105 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002106
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002107 case EK_Variable:
2108 case EK_Parameter:
2109 case EK_Member:
2110 case EK_New:
2111 case EK_Temporary:
2112 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002113 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002114 case EK_ArrayElement:
2115 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002116 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002117 break;
2118 }
2119
2120 return false;
2121}
2122
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002123//===----------------------------------------------------------------------===//
2124// Initialization sequence
2125//===----------------------------------------------------------------------===//
2126
2127void InitializationSequence::Step::Destroy() {
2128 switch (Kind) {
2129 case SK_ResolveAddressOfOverloadedFunction:
2130 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002131 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002132 case SK_CastDerivedToBaseLValue:
2133 case SK_BindReference:
2134 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002135 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002136 case SK_UserConversion:
2137 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002138 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002139 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002140 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002141 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002142 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002143 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002144 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002145 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002146 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002147 case SK_PassByIndirectCopyRestore:
2148 case SK_PassByIndirectRestore:
2149 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002150 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002152 case SK_ConversionSequence:
2153 delete ICS;
2154 }
2155}
2156
Douglas Gregor838fcc32010-03-26 20:14:36 +00002157bool InitializationSequence::isDirectReferenceBinding() const {
2158 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2159}
2160
2161bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002162 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002163 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
Douglas Gregor838fcc32010-03-26 20:14:36 +00002165 switch (getFailureKind()) {
2166 case FK_TooManyInitsForReference:
2167 case FK_ArrayNeedsInitList:
2168 case FK_ArrayNeedsInitListOrStringLiteral:
2169 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2170 case FK_NonConstLValueReferenceBindingToTemporary:
2171 case FK_NonConstLValueReferenceBindingToUnrelated:
2172 case FK_RValueReferenceBindingToLValue:
2173 case FK_ReferenceInitDropsQualifiers:
2174 case FK_ReferenceInitFailed:
2175 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002176 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002177 case FK_TooManyInitsForScalar:
2178 case FK_ReferenceBindingToInitList:
2179 case FK_InitListBadDestinationType:
2180 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002181 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002182 case FK_ArrayTypeMismatch:
2183 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002184 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002185
Douglas Gregor838fcc32010-03-26 20:14:36 +00002186 case FK_ReferenceInitOverloadFailed:
2187 case FK_UserConversionOverloadFailed:
2188 case FK_ConstructorOverloadFailed:
2189 return FailedOverloadResult == OR_Ambiguous;
2190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002191
Douglas Gregor838fcc32010-03-26 20:14:36 +00002192 return false;
2193}
2194
Douglas Gregorb33eed02010-04-16 22:09:46 +00002195bool InitializationSequence::isConstructorInitialization() const {
2196 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2197}
2198
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002199void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002200 FunctionDecl *Function,
2201 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002202 Step S;
2203 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2204 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002205 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002206 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002207 Steps.push_back(S);
2208}
2209
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002211 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002212 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002213 switch (VK) {
2214 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2215 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2216 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002217 default: llvm_unreachable("No such category");
2218 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002219 S.Type = BaseType;
2220 Steps.push_back(S);
2221}
2222
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002223void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002224 bool BindingTemporary) {
2225 Step S;
2226 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2227 S.Type = T;
2228 Steps.push_back(S);
2229}
2230
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002231void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2232 Step S;
2233 S.Kind = SK_ExtraneousCopyToTemporary;
2234 S.Type = T;
2235 Steps.push_back(S);
2236}
2237
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002238void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002239 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002240 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002241 Step S;
2242 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002243 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002244 S.Function.Function = Function;
2245 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002246 Steps.push_back(S);
2247}
2248
2249void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002250 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002251 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002252 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002253 switch (VK) {
2254 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002255 S.Kind = SK_QualificationConversionRValue;
2256 break;
John McCall2536c6d2010-08-25 10:28:54 +00002257 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002258 S.Kind = SK_QualificationConversionXValue;
2259 break;
John McCall2536c6d2010-08-25 10:28:54 +00002260 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002261 S.Kind = SK_QualificationConversionLValue;
2262 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002263 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002264 S.Type = Ty;
2265 Steps.push_back(S);
2266}
2267
2268void InitializationSequence::AddConversionSequenceStep(
2269 const ImplicitConversionSequence &ICS,
2270 QualType T) {
2271 Step S;
2272 S.Kind = SK_ConversionSequence;
2273 S.Type = T;
2274 S.ICS = new ImplicitConversionSequence(ICS);
2275 Steps.push_back(S);
2276}
2277
Douglas Gregor51e77d52009-12-10 17:56:55 +00002278void InitializationSequence::AddListInitializationStep(QualType T) {
2279 Step S;
2280 S.Kind = SK_ListInitialization;
2281 S.Type = T;
2282 Steps.push_back(S);
2283}
2284
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002285void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002286InitializationSequence::AddConstructorInitializationStep(
2287 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002288 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002289 QualType T) {
2290 Step S;
2291 S.Kind = SK_ConstructorInitialization;
2292 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002293 S.Function.Function = Constructor;
2294 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002295 Steps.push_back(S);
2296}
2297
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002298void InitializationSequence::AddZeroInitializationStep(QualType T) {
2299 Step S;
2300 S.Kind = SK_ZeroInitialization;
2301 S.Type = T;
2302 Steps.push_back(S);
2303}
2304
Douglas Gregore1314a62009-12-18 05:02:21 +00002305void InitializationSequence::AddCAssignmentStep(QualType T) {
2306 Step S;
2307 S.Kind = SK_CAssignment;
2308 S.Type = T;
2309 Steps.push_back(S);
2310}
2311
Eli Friedman78275202009-12-19 08:11:05 +00002312void InitializationSequence::AddStringInitStep(QualType T) {
2313 Step S;
2314 S.Kind = SK_StringInit;
2315 S.Type = T;
2316 Steps.push_back(S);
2317}
2318
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002319void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2320 Step S;
2321 S.Kind = SK_ObjCObjectConversion;
2322 S.Type = T;
2323 Steps.push_back(S);
2324}
2325
Douglas Gregore2f943b2011-02-22 18:29:51 +00002326void InitializationSequence::AddArrayInitStep(QualType T) {
2327 Step S;
2328 S.Kind = SK_ArrayInit;
2329 S.Type = T;
2330 Steps.push_back(S);
2331}
2332
John McCall31168b02011-06-15 23:02:42 +00002333void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2334 bool shouldCopy) {
2335 Step s;
2336 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2337 : SK_PassByIndirectRestore);
2338 s.Type = type;
2339 Steps.push_back(s);
2340}
2341
2342void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2343 Step S;
2344 S.Kind = SK_ProduceObjCObject;
2345 S.Type = T;
2346 Steps.push_back(S);
2347}
2348
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002349void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002350 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002351 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002352 this->Failure = Failure;
2353 this->FailedOverloadResult = Result;
2354}
2355
2356//===----------------------------------------------------------------------===//
2357// Attempt initialization
2358//===----------------------------------------------------------------------===//
2359
John McCall31168b02011-06-15 23:02:42 +00002360static void MaybeProduceObjCObject(Sema &S,
2361 InitializationSequence &Sequence,
2362 const InitializedEntity &Entity) {
2363 if (!S.getLangOptions().ObjCAutoRefCount) return;
2364
2365 /// When initializing a parameter, produce the value if it's marked
2366 /// __attribute__((ns_consumed)).
2367 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2368 if (!Entity.isParameterConsumed())
2369 return;
2370
2371 assert(Entity.getType()->isObjCRetainableType() &&
2372 "consuming an object of unretainable type?");
2373 Sequence.AddProduceObjCObjectStep(Entity.getType());
2374
2375 /// When initializing a return value, if the return type is a
2376 /// retainable type, then returns need to immediately retain the
2377 /// object. If an autorelease is required, it will be done at the
2378 /// last instant.
2379 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2380 if (!Entity.getType()->isObjCRetainableType())
2381 return;
2382
2383 Sequence.AddProduceObjCObjectStep(Entity.getType());
2384 }
2385}
2386
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387/// \brief Attempt list initialization (C++0x [dcl.init.list])
2388static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002389 const InitializedEntity &Entity,
2390 const InitializationKind &Kind,
2391 InitListExpr *InitList,
2392 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002393 // FIXME: We only perform rudimentary checking of list
2394 // initializations at this point, then assume that any list
2395 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002396 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002397 // do all of the necessary checking. C++0x initializer lists will
2398 // force us to perform more checking here.
Douglas Gregor51e77d52009-12-10 17:56:55 +00002399
Douglas Gregor1b303932009-12-22 15:35:07 +00002400 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002401
2402 // C++ [dcl.init]p13:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002403 // If T is a scalar type, then a declaration of the form
Douglas Gregor51e77d52009-12-10 17:56:55 +00002404 //
2405 // T x = { a };
2406 //
2407 // is equivalent to
2408 //
2409 // T x = a;
2410 if (DestType->isScalarType()) {
2411 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2412 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2413 return;
2414 }
2415
2416 // Assume scalar initialization from a single value works.
2417 } else if (DestType->isAggregateType()) {
2418 // Assume aggregate initialization works.
2419 } else if (DestType->isVectorType()) {
2420 // Assume vector initialization works.
2421 } else if (DestType->isReferenceType()) {
2422 // FIXME: C++0x defines behavior for this.
2423 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2424 return;
2425 } else if (DestType->isRecordType()) {
2426 // FIXME: C++0x defines behavior for this
2427 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2428 }
2429
2430 // Add a general "list initialization" step.
2431 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002432}
2433
2434/// \brief Try a reference initialization that involves calling a conversion
2435/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002436static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2437 const InitializedEntity &Entity,
2438 const InitializationKind &Kind,
2439 Expr *Initializer,
2440 bool AllowRValues,
2441 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002442 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002443 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2444 QualType T1 = cv1T1.getUnqualifiedType();
2445 QualType cv2T2 = Initializer->getType();
2446 QualType T2 = cv2T2.getUnqualifiedType();
2447
2448 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002449 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002450 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002452 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002453 ObjCConversion,
2454 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002455 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002456 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002457 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002458 (void)ObjCLifetimeConversion;
2459
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002460 // Build the candidate set directly in the initialization sequence
2461 // structure, so that it will persist if we fail.
2462 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2463 CandidateSet.clear();
2464
2465 // Determine whether we are allowed to call explicit constructors or
2466 // explicit conversion operators.
2467 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002469 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002470 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2471 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002472 // The type we're converting to is a class type. Enumerate its constructors
2473 // to see if there is a suitable conversion.
2474 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002475
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002476 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002477 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002478 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002479 NamedDecl *D = *Con;
2480 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2481
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002482 // Find the constructor (which may be a template).
2483 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002484 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002485 if (ConstructorTmpl)
2486 Constructor = cast<CXXConstructorDecl>(
2487 ConstructorTmpl->getTemplatedDecl());
2488 else
John McCalla0296f72010-03-19 07:35:19 +00002489 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002490
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002491 if (!Constructor->isInvalidDecl() &&
2492 Constructor->isConvertingConstructor(AllowExplicit)) {
2493 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002494 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002495 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002496 &Initializer, 1, CandidateSet,
2497 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002498 else
John McCalla0296f72010-03-19 07:35:19 +00002499 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002500 &Initializer, 1, CandidateSet,
2501 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002503 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002504 }
John McCall3696dcb2010-08-17 07:23:57 +00002505 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2506 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002507
Douglas Gregor496e8b342010-05-07 19:42:26 +00002508 const RecordType *T2RecordType = 0;
2509 if ((T2RecordType = T2->getAs<RecordType>()) &&
2510 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002511 // The type we're converting from is a class type, enumerate its conversion
2512 // functions.
2513 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2514
John McCallad371252010-01-20 00:46:10 +00002515 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002516 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002517 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2518 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002519 NamedDecl *D = *I;
2520 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2521 if (isa<UsingShadowDecl>(D))
2522 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002523
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002524 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2525 CXXConversionDecl *Conv;
2526 if (ConvTemplate)
2527 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2528 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002529 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002531 // If the conversion function doesn't return a reference type,
2532 // it can't be considered for this conversion unless we're allowed to
2533 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534 // FIXME: Do we need to make sure that we only consider conversion
2535 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002536 // break recursion.
2537 if ((AllowExplicit || !Conv->isExplicit()) &&
2538 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2539 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002540 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002541 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002542 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002543 else
John McCalla0296f72010-03-19 07:35:19 +00002544 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002545 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002546 }
2547 }
2548 }
John McCall3696dcb2010-08-17 07:23:57 +00002549 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2550 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002551
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002552 SourceLocation DeclLoc = Initializer->getLocStart();
2553
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002554 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002555 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002557 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002558 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002559
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002560 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002561
Chandler Carruth30141632011-02-25 19:41:05 +00002562 // This is the overload that will actually be used for the initialization, so
2563 // mark it as used.
2564 S.MarkDeclarationReferenced(DeclLoc, Function);
2565
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002566 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002567 if (isa<CXXConversionDecl>(Function))
2568 T2 = Function->getResultType();
2569 else
2570 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002571
2572 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002573 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002574 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002575
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002577 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002578 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002579 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002580 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002581 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002582 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002583
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002584 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002585 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002586 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002587 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002588 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002589 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002590 NewDerivedToBase, NewObjCConversion,
2591 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002592 if (NewRefRelationship == Sema::Ref_Incompatible) {
2593 // If the type we've converted to is not reference-related to the
2594 // type we're looking for, then there is another conversion step
2595 // we need to perform to produce a temporary of the right type
2596 // that we'll be binding to.
2597 ImplicitConversionSequence ICS;
2598 ICS.setStandard();
2599 ICS.Standard = Best->FinalConversion;
2600 T2 = ICS.Standard.getToType(2);
2601 Sequence.AddConversionSequenceStep(ICS, T2);
2602 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002603 Sequence.AddDerivedToBaseCastStep(
2604 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002605 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002606 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002607 else if (NewObjCConversion)
2608 Sequence.AddObjCObjectConversionStep(
2609 S.Context.getQualifiedType(T1,
2610 T2.getNonReferenceType().getQualifiers()));
2611
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002612 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002613 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002614
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002615 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2616 return OR_Success;
2617}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618
2619/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2620static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002621 const InitializedEntity &Entity,
2622 const InitializationKind &Kind,
2623 Expr *Initializer,
2624 InitializationSequence &Sequence) {
2625 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002626
Douglas Gregor1b303932009-12-22 15:35:07 +00002627 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002628 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002629 Qualifiers T1Quals;
2630 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002631 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002632 Qualifiers T2Quals;
2633 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002634 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002635
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002636 // If the initializer is the address of an overloaded function, try
2637 // to resolve the overloaded function. If all goes well, T2 is the
2638 // type of the resulting function.
2639 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002640 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002641 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002642 T1,
2643 false,
2644 Found)) {
2645 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2646 cv2T2 = Fn->getType();
2647 T2 = cv2T2.getUnqualifiedType();
2648 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002649 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2650 return;
2651 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002652 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002653
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002654 // Compute some basic properties of the types and the initializer.
2655 bool isLValueRef = DestType->isLValueReferenceType();
2656 bool isRValueRef = !isLValueRef;
2657 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002658 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002659 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002660 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002661 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002662 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002663 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002664
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002665 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002666 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002667 // "cv2 T2" as follows:
2668 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002669 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002670 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002671 // Note the analogous bullet points for rvlaue refs to functions. Because
2672 // there are no function rvalues in C++, rvalue refs to functions are treated
2673 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002674 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002675 bool T1Function = T1->isFunctionType();
2676 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002678 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002679 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002680 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002681 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 // reference-compatible with "cv2 T2," or
2683 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002684 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002685 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002686 // can occur. However, we do pay attention to whether it is a bit-field
2687 // to decide whether we're actually binding to a temporary created from
2688 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002689 if (DerivedToBase)
2690 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002691 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002692 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002693 else if (ObjCConversion)
2694 Sequence.AddObjCObjectConversionStep(
2695 S.Context.getQualifiedType(T1, T2Quals));
2696
Chandler Carruth04bdce62010-01-12 20:32:25 +00002697 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002698 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002699 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002700 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002701 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002702 return;
2703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002704
2705 // - has a class type (i.e., T2 is a class type), where T1 is not
2706 // reference-related to T2, and can be implicitly converted to an
2707 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2708 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002709 // applicable conversion functions (13.3.1.6) and choosing the best
2710 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002711 // If we have an rvalue ref to function type here, the rhs must be
2712 // an rvalue.
2713 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2714 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002716 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002717 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002718 Sequence);
2719 if (ConvOvlResult == OR_Success)
2720 return;
John McCall0d1da222010-01-12 00:44:57 +00002721 if (ConvOvlResult != OR_No_Viable_Function) {
2722 Sequence.SetOverloadFailure(
2723 InitializationSequence::FK_ReferenceInitOverloadFailed,
2724 ConvOvlResult);
2725 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726 }
2727 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002728
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002729 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002730 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002731 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002732 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002733 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2734 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2735 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002736 Sequence.SetOverloadFailure(
2737 InitializationSequence::FK_ReferenceInitOverloadFailed,
2738 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002739 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002740 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002741 ? (RefRelationship == Sema::Ref_Related
2742 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2743 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2744 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002745
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002746 return;
2747 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002748
Douglas Gregor92e460e2011-01-20 16:44:54 +00002749 // - If the initializer expression
2750 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2751 // "cv1 T1" is reference-compatible with "cv2 T2"
2752 // Note: functions are handled below.
2753 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002754 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002755 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002756 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002757 (InitCategory.isXValue() ||
2758 (InitCategory.isPRValue() && T2->isRecordType()) ||
2759 (InitCategory.isPRValue() && T2->isArrayType()))) {
2760 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2761 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002762 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2763 // compiler the freedom to perform a copy here or bind to the
2764 // object, while C++0x requires that we bind directly to the
2765 // object. Hence, we always bind to the object without making an
2766 // extra copy. However, in C++03 requires that we check for the
2767 // presence of a suitable copy constructor:
2768 //
2769 // The constructor that would be used to make the copy shall
2770 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002771 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002772 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002774
Douglas Gregor92e460e2011-01-20 16:44:54 +00002775 if (DerivedToBase)
2776 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2777 ValueKind);
2778 else if (ObjCConversion)
2779 Sequence.AddObjCObjectConversionStep(
2780 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002781
Douglas Gregor92e460e2011-01-20 16:44:54 +00002782 if (T1Quals != T2Quals)
2783 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002785 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002786 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002787 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002788
2789 // - has a class type (i.e., T2 is a class type), where T1 is not
2790 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002791 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2792 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002793 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002794 if (RefRelationship == Sema::Ref_Incompatible) {
2795 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2796 Kind, Initializer,
2797 /*AllowRValues=*/true,
2798 Sequence);
2799 if (ConvOvlResult)
2800 Sequence.SetOverloadFailure(
2801 InitializationSequence::FK_ReferenceInitOverloadFailed,
2802 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002804 return;
2805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002806
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002807 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2808 return;
2809 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002810
2811 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002812 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002814 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002815
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002816 // Determine whether we are allowed to call explicit constructors or
2817 // explicit conversion operators.
2818 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002819
2820 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2821
John McCall31168b02011-06-15 23:02:42 +00002822 ImplicitConversionSequence ICS
2823 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00002824 /*SuppressUserConversions*/ false,
2825 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002826 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00002827 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2828 /*AllowObjCWritebackConversion=*/false);
2829
2830 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002831 // FIXME: Use the conversion function set stored in ICS to turn
2832 // this into an overloading ambiguity diagnostic. However, we need
2833 // to keep that set as an OverloadCandidateSet rather than as some
2834 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002835 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2836 Sequence.SetOverloadFailure(
2837 InitializationSequence::FK_ReferenceInitOverloadFailed,
2838 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002839 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2840 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002841 else
2842 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002843 return;
John McCall31168b02011-06-15 23:02:42 +00002844 } else {
2845 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002846 }
2847
2848 // [...] If T1 is reference-related to T2, cv1 must be the
2849 // same cv-qualification as, or greater cv-qualification
2850 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002851 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2852 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002854 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002855 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2856 return;
2857 }
2858
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002859 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002860 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002861 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002862 InitCategory.isLValue()) {
2863 Sequence.SetFailed(
2864 InitializationSequence::FK_RValueReferenceBindingToLValue);
2865 return;
2866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002868 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2869 return;
2870}
2871
2872/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873/// (C++ [dcl.init.string], C99 6.7.8).
2874static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002875 const InitializedEntity &Entity,
2876 const InitializationKind &Kind,
2877 Expr *Initializer,
2878 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002879 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002880}
2881
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002882/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2883/// enumerates the constructors of the initialized entity and performs overload
2884/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002885static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002886 const InitializedEntity &Entity,
2887 const InitializationKind &Kind,
2888 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002889 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002890 InitializationSequence &Sequence) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002891 // Build the candidate set directly in the initialization sequence
2892 // structure, so that it will persist if we fail.
2893 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2894 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002895
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002896 // Determine whether we are allowed to call explicit constructors or
2897 // explicit conversion operators.
2898 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2899 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002900 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002901
2902 // The type we're constructing needs to be complete.
2903 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002904 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002905 return;
2906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002907
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002908 // The type we're converting to is a class type. Enumerate its constructors
2909 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002910 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002911 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002912 CXXRecordDecl *DestRecordDecl
2913 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002915 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002916 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002917 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002918 NamedDecl *D = *Con;
2919 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002920 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002921
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002922 // Find the constructor (which may be a template).
2923 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002924 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002925 if (ConstructorTmpl)
2926 Constructor = cast<CXXConstructorDecl>(
2927 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002928 else {
John McCalla0296f72010-03-19 07:35:19 +00002929 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002930
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002931 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00002932 // suppress user-defined conversions on the arguments.
2933 // FIXME: Move constructors?
2934 if (Kind.getKind() == InitializationKind::IK_Copy &&
2935 Constructor->isCopyConstructor())
2936 SuppressUserConversions = true;
2937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002939 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002940 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002941 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002942 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002943 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002944 Args, NumArgs, CandidateSet,
2945 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002946 else
John McCalla0296f72010-03-19 07:35:19 +00002947 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002948 Args, NumArgs, CandidateSet,
2949 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002951 }
2952
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002953 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954
2955 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002956 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002958 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002959 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002960 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002961 Result);
2962 return;
2963 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002964
2965 // C++0x [dcl.init]p6:
2966 // If a program calls for the default initialization of an object
2967 // of a const-qualified type T, T shall be a class type with a
2968 // user-provided default constructor.
2969 if (Kind.getKind() == InitializationKind::IK_Default &&
2970 Entity.getType().isConstQualified() &&
2971 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2972 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2973 return;
2974 }
2975
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002976 // Add the constructor initialization step. Any cv-qualification conversion is
2977 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002978 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002980 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002981 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002982}
2983
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002984/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002985static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002986 const InitializedEntity &Entity,
2987 const InitializationKind &Kind,
2988 InitializationSequence &Sequence) {
2989 // C++ [dcl.init]p5:
2990 //
2991 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002992 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002993
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002994 // -- if T is an array type, then each element is value-initialized;
2995 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2996 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002998 if (const RecordType *RT = T->getAs<RecordType>()) {
2999 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3000 // -- if T is a class type (clause 9) with a user-declared
3001 // constructor (12.1), then the default constructor for T is
3002 // called (and the initialization is ill-formed if T has no
3003 // accessible default constructor);
3004 //
3005 // FIXME: we really want to refer to a single subobject of the array,
3006 // but Entity doesn't have a way to capture that (yet).
3007 if (ClassDecl->hasUserDeclaredConstructor())
3008 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003010 // -- if T is a (possibly cv-qualified) non-union class type
3011 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003012 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003013 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003014 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003015 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003016 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003018 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003019 }
3020 }
3021
Douglas Gregor1b303932009-12-22 15:35:07 +00003022 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003023}
3024
Douglas Gregor85dabae2009-12-16 01:38:02 +00003025/// \brief Attempt default initialization (C++ [dcl.init]p6).
3026static void TryDefaultInitialization(Sema &S,
3027 const InitializedEntity &Entity,
3028 const InitializationKind &Kind,
3029 InitializationSequence &Sequence) {
3030 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031
Douglas Gregor85dabae2009-12-16 01:38:02 +00003032 // C++ [dcl.init]p6:
3033 // To default-initialize an object of type T means:
3034 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003035 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3036
Douglas Gregor85dabae2009-12-16 01:38:02 +00003037 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3038 // constructor for T is called (and the initialization is ill-formed if
3039 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003040 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003041 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3042 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
Douglas Gregor85dabae2009-12-16 01:38:02 +00003045 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003046
Douglas Gregor85dabae2009-12-16 01:38:02 +00003047 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003049 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003050 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003051 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003052 return;
3053 }
3054
3055 // If the destination type has a lifetime property, zero-initialize it.
3056 if (DestType.getQualifiers().hasObjCLifetime()) {
3057 Sequence.AddZeroInitializationStep(Entity.getType());
3058 return;
3059 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003060}
3061
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003062/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3063/// which enumerates all conversion functions and performs overload resolution
3064/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003065static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003066 const InitializedEntity &Entity,
3067 const InitializationKind &Kind,
3068 Expr *Initializer,
3069 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003070 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003071 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3072 QualType SourceType = Initializer->getType();
3073 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3074 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003075
Douglas Gregor540c3b02009-12-14 17:27:33 +00003076 // Build the candidate set directly in the initialization sequence
3077 // structure, so that it will persist if we fail.
3078 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3079 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003080
Douglas Gregor540c3b02009-12-14 17:27:33 +00003081 // Determine whether we are allowed to call explicit constructors or
3082 // explicit conversion operators.
3083 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084
Douglas Gregor540c3b02009-12-14 17:27:33 +00003085 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3086 // The type we're converting to is a class type. Enumerate its constructors
3087 // to see if there is a suitable conversion.
3088 CXXRecordDecl *DestRecordDecl
3089 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003090
Douglas Gregord9848152010-04-26 14:36:57 +00003091 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003093 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003094 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003095 Con != ConEnd; ++Con) {
3096 NamedDecl *D = *Con;
3097 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098
Douglas Gregord9848152010-04-26 14:36:57 +00003099 // Find the constructor (which may be a template).
3100 CXXConstructorDecl *Constructor = 0;
3101 FunctionTemplateDecl *ConstructorTmpl
3102 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003103 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003104 Constructor = cast<CXXConstructorDecl>(
3105 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003106 else
Douglas Gregord9848152010-04-26 14:36:57 +00003107 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003108
Douglas Gregord9848152010-04-26 14:36:57 +00003109 if (!Constructor->isInvalidDecl() &&
3110 Constructor->isConvertingConstructor(AllowExplicit)) {
3111 if (ConstructorTmpl)
3112 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3113 /*ExplicitArgs*/ 0,
3114 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003115 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003116 else
3117 S.AddOverloadCandidate(Constructor, FoundDecl,
3118 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003119 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121 }
Douglas Gregord9848152010-04-26 14:36:57 +00003122 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003123 }
Eli Friedman78275202009-12-19 08:11:05 +00003124
3125 SourceLocation DeclLoc = Initializer->getLocStart();
3126
Douglas Gregor540c3b02009-12-14 17:27:33 +00003127 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3128 // The type we're converting from is a class type, enumerate its conversion
3129 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003130
Eli Friedman4afe9a32009-12-20 22:12:03 +00003131 // We can only enumerate the conversion functions for a complete type; if
3132 // the type isn't complete, simply skip this step.
3133 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3134 CXXRecordDecl *SourceRecordDecl
3135 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003136
John McCallad371252010-01-20 00:46:10 +00003137 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003138 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003139 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003140 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003141 I != E; ++I) {
3142 NamedDecl *D = *I;
3143 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3144 if (isa<UsingShadowDecl>(D))
3145 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146
Eli Friedman4afe9a32009-12-20 22:12:03 +00003147 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3148 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003149 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003150 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003151 else
John McCallda4458e2010-03-31 01:36:47 +00003152 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
Eli Friedman4afe9a32009-12-20 22:12:03 +00003154 if (AllowExplicit || !Conv->isExplicit()) {
3155 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003156 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003157 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003158 CandidateSet);
3159 else
John McCalla0296f72010-03-19 07:35:19 +00003160 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003161 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003162 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003163 }
3164 }
3165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
3167 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003168 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003169 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003170 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003171 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003173 Result);
3174 return;
3175 }
John McCall0d1da222010-01-12 00:44:57 +00003176
Douglas Gregor540c3b02009-12-14 17:27:33 +00003177 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003178 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003179
Douglas Gregor540c3b02009-12-14 17:27:33 +00003180 if (isa<CXXConstructorDecl>(Function)) {
3181 // Add the user-defined conversion step. Any cv-qualification conversion is
3182 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003183 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003184 return;
3185 }
3186
3187 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003188 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003189 if (ConvType->getAs<RecordType>()) {
3190 // If we're converting to a class type, there may be an copy if
3191 // the resulting temporary object (possible to create an object of
3192 // a base class type). That copy is not a separate conversion, so
3193 // we just make a note of the actual destination type (possibly a
3194 // base class of the type returned by the conversion function) and
3195 // let the user-defined conversion step handle the conversion.
3196 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3197 return;
3198 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003199
Douglas Gregor5ab11652010-04-17 22:01:05 +00003200 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003201
Douglas Gregor5ab11652010-04-17 22:01:05 +00003202 // If the conversion following the call to the conversion function
3203 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003204 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3205 Best->FinalConversion.Third) {
3206 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003207 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003208 ICS.Standard = Best->FinalConversion;
3209 Sequence.AddConversionSequenceStep(ICS, DestType);
3210 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003211}
3212
John McCall31168b02011-06-15 23:02:42 +00003213/// The non-zero enum values here are indexes into diagnostic alternatives.
3214enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3215
3216/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003217static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3218 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003219 // Skip parens.
3220 e = e->IgnoreParens();
3221
3222 // Skip address-of nodes.
3223 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3224 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003225 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003226
3227 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003228 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3229 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003230 case CK_Dependent:
3231 case CK_BitCast:
3232 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003233 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003234 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003235
3236 case CK_ArrayToPointerDecay:
3237 return IIK_nonscalar;
3238
3239 case CK_NullToPointer:
3240 return IIK_okay;
3241
3242 default:
3243 break;
3244 }
3245
3246 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003247 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3248 if (!isAddressOf) return IIK_nonlocal;
3249
3250 VarDecl *var;
3251 if (isa<DeclRefExpr>(e)) {
3252 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3253 if (!var) return IIK_nonlocal;
3254 } else {
3255 var = cast<BlockDeclRefExpr>(e)->getDecl();
3256 }
3257
3258 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003259
3260 // If we have a conditional operator, check both sides.
3261 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003262 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003263 return iik;
3264
John McCall63f84442011-06-27 23:59:58 +00003265 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003266
3267 // These are never scalar.
3268 } else if (isa<ArraySubscriptExpr>(e)) {
3269 return IIK_nonscalar;
3270
3271 // Otherwise, it needs to be a null pointer constant.
3272 } else {
3273 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3274 ? IIK_okay : IIK_nonlocal);
3275 }
3276
3277 return IIK_nonlocal;
3278}
3279
3280/// Check whether the given expression is a valid operand for an
3281/// indirect copy/restore.
3282static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3283 assert(src->isRValue());
3284
John McCall63f84442011-06-27 23:59:58 +00003285 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003286 if (iik == IIK_okay) return;
3287
3288 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3289 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3290 << src->getSourceRange();
3291}
3292
Douglas Gregore2f943b2011-02-22 18:29:51 +00003293/// \brief Determine whether we have compatible array types for the
3294/// purposes of GNU by-copy array initialization.
3295static bool hasCompatibleArrayTypes(ASTContext &Context,
3296 const ArrayType *Dest,
3297 const ArrayType *Source) {
3298 // If the source and destination array types are equivalent, we're
3299 // done.
3300 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3301 return true;
3302
3303 // Make sure that the element types are the same.
3304 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3305 return false;
3306
3307 // The only mismatch we allow is when the destination is an
3308 // incomplete array type and the source is a constant array type.
3309 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3310}
3311
John McCall31168b02011-06-15 23:02:42 +00003312static bool tryObjCWritebackConversion(Sema &S,
3313 InitializationSequence &Sequence,
3314 const InitializedEntity &Entity,
3315 Expr *Initializer) {
3316 bool ArrayDecay = false;
3317 QualType ArgType = Initializer->getType();
3318 QualType ArgPointee;
3319 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3320 ArrayDecay = true;
3321 ArgPointee = ArgArrayType->getElementType();
3322 ArgType = S.Context.getPointerType(ArgPointee);
3323 }
3324
3325 // Handle write-back conversion.
3326 QualType ConvertedArgType;
3327 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3328 ConvertedArgType))
3329 return false;
3330
3331 // We should copy unless we're passing to an argument explicitly
3332 // marked 'out'.
3333 bool ShouldCopy = true;
3334 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3335 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3336
3337 // Do we need an lvalue conversion?
3338 if (ArrayDecay || Initializer->isGLValue()) {
3339 ImplicitConversionSequence ICS;
3340 ICS.setStandard();
3341 ICS.Standard.setAsIdentityConversion();
3342
3343 QualType ResultType;
3344 if (ArrayDecay) {
3345 ICS.Standard.First = ICK_Array_To_Pointer;
3346 ResultType = S.Context.getPointerType(ArgPointee);
3347 } else {
3348 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3349 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3350 }
3351
3352 Sequence.AddConversionSequenceStep(ICS, ResultType);
3353 }
3354
3355 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3356 return true;
3357}
3358
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003359InitializationSequence::InitializationSequence(Sema &S,
3360 const InitializedEntity &Entity,
3361 const InitializationKind &Kind,
3362 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003363 unsigned NumArgs)
3364 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003365 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003367 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368 // The semantics of initializers are as follows. The destination type is
3369 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003370 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003372 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003373 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003374
3375 if (DestType->isDependentType() ||
3376 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3377 SequenceKind = DependentSequence;
3378 return;
3379 }
3380
Sebastian Redld201edf2011-06-05 13:59:11 +00003381 // Almost everything is a normal sequence.
3382 setSequenceKind(NormalSequence);
3383
John McCalled75c092010-12-07 22:54:16 +00003384 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003385 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3386 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3387 if (Result.isInvalid()) {
3388 SetFailed(FK_ConversionFromPropertyFailed);
3389 return;
3390 }
3391 Args[I] = Result.take();
3392 }
John McCalled75c092010-12-07 22:54:16 +00003393
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003394 QualType SourceType;
3395 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003396 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003397 Initializer = Args[0];
3398 if (!isa<InitListExpr>(Initializer))
3399 SourceType = Initializer->getType();
3400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003401
3402 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003403 // list-initialized (8.5.4).
3404 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3405 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003406 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003409 // - If the destination type is a reference type, see 8.5.3.
3410 if (DestType->isReferenceType()) {
3411 // C++0x [dcl.init.ref]p1:
3412 // A variable declared to be a T& or T&&, that is, "reference to type T"
3413 // (8.3.2), shall be initialized by an object, or function, of type T or
3414 // by an object that can be converted into a T.
3415 // (Therefore, multiple arguments are not permitted.)
3416 if (NumArgs != 1)
3417 SetFailed(FK_TooManyInitsForReference);
3418 else
3419 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3420 return;
3421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003423 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003424 if (Kind.getKind() == InitializationKind::IK_Value ||
3425 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003426 TryValueInitialization(S, Entity, Kind, *this);
3427 return;
3428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003429
Douglas Gregor85dabae2009-12-16 01:38:02 +00003430 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003431 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003432 TryDefaultInitialization(S, Entity, Kind, *this);
3433 return;
3434 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003435
John McCall66884dd2011-02-21 07:22:22 +00003436 // - If the destination type is an array of characters, an array of
3437 // char16_t, an array of char32_t, or an array of wchar_t, and the
3438 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003440 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003441 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3442 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCall66884dd2011-02-21 07:22:22 +00003443 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3444 return;
3445 }
3446
Douglas Gregore2f943b2011-02-22 18:29:51 +00003447 // Note: as an GNU C extension, we allow initialization of an
3448 // array from a compound literal that creates an array of the same
3449 // type, so long as the initializer has no side effects.
3450 if (!S.getLangOptions().CPlusPlus && Initializer &&
3451 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3452 Initializer->getType()->isArrayType()) {
3453 const ArrayType *SourceAT
3454 = Context.getAsArrayType(Initializer->getType());
3455 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3456 SetFailed(FK_ArrayTypeMismatch);
3457 else if (Initializer->HasSideEffects(S.Context))
3458 SetFailed(FK_NonConstantArrayInit);
3459 else {
Douglas Gregore2f943b2011-02-22 18:29:51 +00003460 AddArrayInitStep(DestType);
3461 }
3462 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003463 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3464 else
3465 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003467 return;
3468 }
Eli Friedman78275202009-12-19 08:11:05 +00003469
John McCall31168b02011-06-15 23:02:42 +00003470 // Determine whether we should consider writeback conversions for
3471 // Objective-C ARC.
3472 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3473 Entity.getKind() == InitializedEntity::EK_Parameter;
3474
3475 // We're at the end of the line for C: it's either a write-back conversion
3476 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003477 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003478 // If allowed, check whether this is an Objective-C writeback conversion.
3479 if (allowObjCWritebackConversion &&
3480 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
3481 return;
3482 }
3483
3484 // Handle initialization in C
Eli Friedman78275202009-12-19 08:11:05 +00003485 AddCAssignmentStep(DestType);
John McCall31168b02011-06-15 23:02:42 +00003486 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003487 return;
3488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
John McCall31168b02011-06-15 23:02:42 +00003490 assert(S.getLangOptions().CPlusPlus);
3491
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003492 // - If the destination type is a (possibly cv-qualified) class type:
3493 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494 // - If the initialization is direct-initialization, or if it is
3495 // copy-initialization where the cv-unqualified version of the
3496 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003497 // class of the destination, constructors are considered. [...]
3498 if (Kind.getKind() == InitializationKind::IK_Direct ||
3499 (Kind.getKind() == InitializationKind::IK_Copy &&
3500 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3501 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003503 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003505 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003507 // used) to a derived class thereof are enumerated as described in
3508 // 13.3.1.4, and the best one is chosen through overload resolution
3509 // (13.3).
3510 else
3511 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3512 return;
3513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514
Douglas Gregor85dabae2009-12-16 01:38:02 +00003515 if (NumArgs > 1) {
3516 SetFailed(FK_TooManyInitsForScalar);
3517 return;
3518 }
3519 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520
3521 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003522 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003523 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003524 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
John McCall31168b02011-06-15 23:02:42 +00003525 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003526 return;
3527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003529 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003530 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003531 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003532 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003533 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003534
3535 ImplicitConversionSequence ICS
3536 = S.TryImplicitConversion(Initializer, Entity.getType(),
3537 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003538 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003539 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003540 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3541 allowObjCWritebackConversion);
3542
3543 if (ICS.isStandard() &&
3544 ICS.Standard.Second == ICK_Writeback_Conversion) {
3545 // Objective-C ARC writeback conversion.
3546
3547 // We should copy unless we're passing to an argument explicitly
3548 // marked 'out'.
3549 bool ShouldCopy = true;
3550 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3551 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3552
3553 // If there was an lvalue adjustment, add it as a separate conversion.
3554 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3555 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3556 ImplicitConversionSequence LvalueICS;
3557 LvalueICS.setStandard();
3558 LvalueICS.Standard.setAsIdentityConversion();
3559 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3560 LvalueICS.Standard.First = ICS.Standard.First;
3561 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
3562 }
3563
3564 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3565 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003566 DeclAccessPair dap;
3567 if (Initializer->getType() == Context.OverloadTy &&
3568 !S.ResolveAddressOfOverloadedFunction(Initializer
3569 , DestType, false, dap))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003570 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3571 else
3572 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003573 } else {
3574 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003575
3576 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003577 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003578}
3579
3580InitializationSequence::~InitializationSequence() {
3581 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3582 StepEnd = Steps.end();
3583 Step != StepEnd; ++Step)
3584 Step->Destroy();
3585}
3586
3587//===----------------------------------------------------------------------===//
3588// Perform initialization
3589//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003591getAssignmentAction(const InitializedEntity &Entity) {
3592 switch(Entity.getKind()) {
3593 case InitializedEntity::EK_Variable:
3594 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003595 case InitializedEntity::EK_Exception:
3596 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003597 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003598 return Sema::AA_Initializing;
3599
3600 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003601 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003602 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3603 return Sema::AA_Sending;
3604
Douglas Gregore1314a62009-12-18 05:02:21 +00003605 return Sema::AA_Passing;
3606
3607 case InitializedEntity::EK_Result:
3608 return Sema::AA_Returning;
3609
Douglas Gregore1314a62009-12-18 05:02:21 +00003610 case InitializedEntity::EK_Temporary:
3611 // FIXME: Can we tell apart casting vs. converting?
3612 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613
Douglas Gregore1314a62009-12-18 05:02:21 +00003614 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003615 case InitializedEntity::EK_ArrayElement:
3616 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003617 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003618 return Sema::AA_Initializing;
3619 }
3620
3621 return Sema::AA_Converting;
3622}
3623
Douglas Gregor95562572010-04-24 23:45:46 +00003624/// \brief Whether we should binding a created object as a temporary when
3625/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003626static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003627 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003628 case InitializedEntity::EK_ArrayElement:
3629 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003630 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003631 case InitializedEntity::EK_New:
3632 case InitializedEntity::EK_Variable:
3633 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003634 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003635 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003636 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003637 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003638 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639
Douglas Gregore1314a62009-12-18 05:02:21 +00003640 case InitializedEntity::EK_Parameter:
3641 case InitializedEntity::EK_Temporary:
3642 return true;
3643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644
Douglas Gregore1314a62009-12-18 05:02:21 +00003645 llvm_unreachable("missed an InitializedEntity kind?");
3646}
3647
Douglas Gregor95562572010-04-24 23:45:46 +00003648/// \brief Whether the given entity, when initialized with an object
3649/// created for that initialization, requires destruction.
3650static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3651 switch (Entity.getKind()) {
3652 case InitializedEntity::EK_Member:
3653 case InitializedEntity::EK_Result:
3654 case InitializedEntity::EK_New:
3655 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003656 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00003657 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003658 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003659 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660
Douglas Gregor95562572010-04-24 23:45:46 +00003661 case InitializedEntity::EK_Variable:
3662 case InitializedEntity::EK_Parameter:
3663 case InitializedEntity::EK_Temporary:
3664 case InitializedEntity::EK_ArrayElement:
3665 case InitializedEntity::EK_Exception:
3666 return true;
3667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668
3669 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003670}
3671
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003672/// \brief Make a (potentially elidable) temporary copy of the object
3673/// provided by the given initializer by calling the appropriate copy
3674/// constructor.
3675///
3676/// \param S The Sema object used for type-checking.
3677///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003678/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003679/// the type of the initializer expression or a superclass thereof.
3680///
3681/// \param Enter The entity being initialized.
3682///
3683/// \param CurInit The initializer expression.
3684///
3685/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3686/// is permitted in C++03 (but not C++0x) when binding a reference to
3687/// an rvalue.
3688///
3689/// \returns An expression that copies the initializer expression into
3690/// a temporary object, or an error expression if a copy could not be
3691/// created.
John McCalldadc5752010-08-24 06:29:42 +00003692static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003693 QualType T,
3694 const InitializedEntity &Entity,
3695 ExprResult CurInit,
3696 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003697 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003698 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003699 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003700 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003701 Class = cast<CXXRecordDecl>(Record->getDecl());
3702 if (!Class)
3703 return move(CurInit);
3704
Douglas Gregor5d369002011-01-21 18:05:27 +00003705 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003706 // When certain criteria are met, an implementation is allowed to
3707 // omit the copy/move construction of a class object, even if the
3708 // copy/move constructor and/or destructor for the object have
3709 // side effects. [...]
3710 // - when a temporary class object that has not been bound to a
3711 // reference (12.2) would be copied/moved to a class object
3712 // with the same cv-unqualified type, the copy/move operation
3713 // can be omitted by constructing the temporary object
3714 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003716 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003717 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003718 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003719 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003720 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003721 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003722 switch (Entity.getKind()) {
3723 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003724 Loc = Entity.getReturnLoc();
3725 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726
Douglas Gregore1314a62009-12-18 05:02:21 +00003727 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003728 Loc = Entity.getThrowLoc();
3729 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Douglas Gregore1314a62009-12-18 05:02:21 +00003731 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003732 Loc = Entity.getDecl()->getLocation();
3733 break;
3734
Anders Carlsson0bd52402010-01-24 00:19:41 +00003735 case InitializedEntity::EK_ArrayElement:
3736 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003737 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003738 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003739 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003740 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003741 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003742 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003743 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003744 Loc = CurInitExpr->getLocStart();
3745 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003746 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003747
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003749 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3750 return move(CurInit);
3751
Douglas Gregorf282a762011-01-21 19:38:21 +00003752 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003753 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003754 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003755 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003756 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003757 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003758 // C++0x [dcl.init]p16, second bullet to class types, this
3759 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003760 CXXConstructorDecl *Constructor = 0;
3761
3762 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003763 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003764 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003765 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003766 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003767 continue;
3768
3769 DeclAccessPair FoundDecl
3770 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3771 S.AddOverloadCandidate(Constructor, FoundDecl,
3772 &CurInitExpr, 1, CandidateSet);
3773 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003775
3776 // Handle constructor templates.
3777 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3778 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003779 continue;
John McCalla0296f72010-03-19 07:35:19 +00003780
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003781 Constructor = cast<CXXConstructorDecl>(
3782 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003783 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003784 continue;
3785
3786 // FIXME: Do we need to limit this to copy-constructor-like
3787 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003788 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003789 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3790 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3791 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003792 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003793
Douglas Gregore1314a62009-12-18 05:02:21 +00003794 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003795 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003796 case OR_Success:
3797 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003798
Douglas Gregore1314a62009-12-18 05:02:21 +00003799 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003800 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3801 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3802 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003803 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003804 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003805 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003806 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003807 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003808 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809
Douglas Gregore1314a62009-12-18 05:02:21 +00003810 case OR_Ambiguous:
3811 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003812 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003813 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003814 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003815 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
Douglas Gregore1314a62009-12-18 05:02:21 +00003817 case OR_Deleted:
3818 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003819 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003820 << CurInitExpr->getSourceRange();
3821 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00003822 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003823 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003824 }
3825
Douglas Gregor5ab11652010-04-17 22:01:05 +00003826 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003827 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003828 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003829
Anders Carlssona01874b2010-04-21 18:47:17 +00003830 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003831 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003832
3833 if (IsExtraneousCopy) {
3834 // If this is a totally extraneous copy for C++03 reference
3835 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003836 // expression. We don't generate an (elided) copy operation here
3837 // because doing so would require us to pass down a flag to avoid
3838 // infinite recursion, where each step adds another extraneous,
3839 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003840
Douglas Gregor30b52772010-04-18 07:57:34 +00003841 // Instantiate the default arguments of any extra parameters in
3842 // the selected copy constructor, as if we were going to create a
3843 // proper call to the copy constructor.
3844 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3845 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3846 if (S.RequireCompleteType(Loc, Parm->getType(),
3847 S.PDiag(diag::err_call_incomplete_argument)))
3848 break;
3849
3850 // Build the default argument expression; we don't actually care
3851 // if this succeeds or not, because this routine will complain
3852 // if there was a problem.
3853 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3854 }
3855
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003856 return S.Owned(CurInitExpr);
3857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858
Chandler Carruth30141632011-02-25 19:41:05 +00003859 S.MarkDeclarationReferenced(Loc, Constructor);
3860
Douglas Gregor5ab11652010-04-17 22:01:05 +00003861 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003862 // constructor call (we might have derived-to-base conversions, or
3863 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003864 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003865 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003866 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003867
Douglas Gregord0ace022010-04-25 00:55:24 +00003868 // Actually perform the constructor call.
3869 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003870 move_arg(ConstructorArgs),
3871 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003872 CXXConstructExpr::CK_Complete,
3873 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874
Douglas Gregord0ace022010-04-25 00:55:24 +00003875 // If we're supposed to bind temporaries, do so.
3876 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3877 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3878 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003879}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003880
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003881void InitializationSequence::PrintInitLocationNote(Sema &S,
3882 const InitializedEntity &Entity) {
3883 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3884 if (Entity.getDecl()->getLocation().isInvalid())
3885 return;
3886
3887 if (Entity.getDecl()->getDeclName())
3888 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3889 << Entity.getDecl()->getDeclName();
3890 else
3891 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3892 }
3893}
3894
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003896InitializationSequence::Perform(Sema &S,
3897 const InitializedEntity &Entity,
3898 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003899 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003900 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00003901 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003902 unsigned NumArgs = Args.size();
3903 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003904 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906
Sebastian Redld201edf2011-06-05 13:59:11 +00003907 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003908 // If the declaration is a non-dependent, incomplete array type
3909 // that has an initializer, then its type will be completed once
3910 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003911 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003912 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003913 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003914 if (const IncompleteArrayType *ArrayT
3915 = S.Context.getAsIncompleteArrayType(DeclType)) {
3916 // FIXME: We don't currently have the ability to accurately
3917 // compute the length of an initializer list without
3918 // performing full type-checking of the initializer list
3919 // (since we have to determine where braces are implicitly
3920 // introduced and such). So, we fall back to making the array
3921 // type a dependently-sized array type with no specified
3922 // bound.
3923 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3924 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003925
Douglas Gregor51e77d52009-12-10 17:56:55 +00003926 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003927 if (DeclaratorDecl *DD = Entity.getDecl()) {
3928 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3929 TypeLoc TL = TInfo->getTypeLoc();
3930 if (IncompleteArrayTypeLoc *ArrayLoc
3931 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3932 Brackets = ArrayLoc->getBracketsRange();
3933 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003934 }
3935
3936 *ResultType
3937 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3938 /*NumElts=*/0,
3939 ArrayT->getSizeModifier(),
3940 ArrayT->getIndexTypeCVRQualifiers(),
3941 Brackets);
3942 }
3943
3944 }
3945 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00003946 assert(Kind.getKind() == InitializationKind::IK_Copy ||
3947 Kind.isExplicitCast());
3948 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003949 }
3950
Sebastian Redld201edf2011-06-05 13:59:11 +00003951 // No steps means no initialization.
3952 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00003953 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954
Douglas Gregor1b303932009-12-22 15:35:07 +00003955 QualType DestType = Entity.getType().getNonReferenceType();
3956 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003957 // the same as Entity.getDecl()->getType() in cases involving type merging,
3958 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003959 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003960 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003961 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003962
John McCalldadc5752010-08-24 06:29:42 +00003963 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003964
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00003966 // grab the only argument out the Args and place it into the "current"
3967 // initializer.
3968 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003969 case SK_ResolveAddressOfOverloadedFunction:
3970 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003971 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003972 case SK_CastDerivedToBaseLValue:
3973 case SK_BindReference:
3974 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003975 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003976 case SK_UserConversion:
3977 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003978 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003979 case SK_QualificationConversionRValue:
3980 case SK_ConversionSequence:
3981 case SK_ListInitialization:
3982 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003983 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003984 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00003985 case SK_ArrayInit:
3986 case SK_PassByIndirectCopyRestore:
3987 case SK_PassByIndirectRestore:
3988 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00003989 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00003990 CurInit = Args.get()[0];
3991 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003992
3993 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00003994 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3995 CurInit = S.ConvertPropertyForRValue(CurInit.take());
3996 if (CurInit.isInvalid())
3997 return ExprError();
3998 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003999 break;
John McCall34376a62010-12-04 03:47:34 +00004000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001
Douglas Gregore1314a62009-12-18 05:02:21 +00004002 case SK_ConstructorInitialization:
4003 case SK_ZeroInitialization:
4004 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006
4007 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004008 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004009 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004010 for (step_iterator Step = step_begin(), StepEnd = step_end();
4011 Step != StepEnd; ++Step) {
4012 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004013 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
John Wiegley01296292011-04-08 18:41:53 +00004015 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004017 switch (Step->Kind) {
4018 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004020 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004021 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004022 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004023 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004024 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004025 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004026 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004027
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004028 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004029 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004030 case SK_CastDerivedToBaseLValue: {
4031 // We have a derived-to-base cast that produces either an rvalue or an
4032 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
John McCallcf142162010-08-07 06:22:56 +00004034 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004035
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004036 // Casts to inaccessible base classes are allowed with C-style casts.
4037 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4038 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004039 CurInit.get()->getLocStart(),
4040 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004041 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004042 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043
Douglas Gregor88d292c2010-05-13 16:44:06 +00004044 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4045 QualType T = SourceType;
4046 if (const PointerType *Pointer = T->getAs<PointerType>())
4047 T = Pointer->getPointeeType();
4048 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004049 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004050 cast<CXXRecordDecl>(RecordTy->getDecl()));
4051 }
4052
John McCall2536c6d2010-08-25 10:28:54 +00004053 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004054 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004055 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004056 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004057 VK_XValue :
4058 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004059 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4060 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004061 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004062 CurInit.get(),
4063 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004064 break;
4065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004067 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004068 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004069 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4070 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004071 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004072 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004073 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004074 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004075 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004076 }
Anders Carlssona91be642010-01-29 02:47:33 +00004077
John Wiegley01296292011-04-08 18:41:53 +00004078 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004079 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004080 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4081 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004082 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004083 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004084 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004086
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004087 // Reference binding does not have any corresponding ASTs.
4088
4089 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004090 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004091 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004092
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004093 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004094
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004095 case SK_BindReferenceToTemporary:
4096 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004097 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004098 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004099
Douglas Gregorfe314812011-06-21 17:03:29 +00004100 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004101 CurInit = new (S.Context) MaterializeTemporaryExpr(
4102 Entity.getType().getNonReferenceType(),
4103 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004104 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004105
4106 // If we're binding to an Objective-C object that has lifetime, we
4107 // need cleanups.
4108 if (S.getLangOptions().ObjCAutoRefCount &&
4109 CurInit.get()->getType()->isObjCLifetimeType())
4110 S.ExprNeedsCleanups = true;
4111
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004112 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004114 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004116 /*IsExtraneousCopy=*/true);
4117 break;
4118
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004119 case SK_UserConversion: {
4120 // We have a user-defined conversion that invokes either a constructor
4121 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004122 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004123 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004124 FunctionDecl *Fn = Step->Function.Function;
4125 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004126 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00004127 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00004128 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004129 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004130 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004131 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004132 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004133
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004134 // Determine the arguments required to actually perform the constructor
4135 // call.
John Wiegley01296292011-04-08 18:41:53 +00004136 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004137 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004138 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004139 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004140 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004142 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004144 move_arg(ConstructorArgs),
4145 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004146 CXXConstructExpr::CK_Complete,
4147 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004148 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004149 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004150
Anders Carlssona01874b2010-04-21 18:47:17 +00004151 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004152 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004153 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154
John McCalle3027922010-08-25 11:45:40 +00004155 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004156 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4157 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4158 S.IsDerivedFrom(SourceType, Class))
4159 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160
Douglas Gregor95562572010-04-24 23:45:46 +00004161 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004162 } else {
4163 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004164 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00004165 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00004166 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004167 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004168 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169
4170 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004171 // derived-to-base conversion? I believe the answer is "no", because
4172 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004173 ExprResult CurInitExprRes =
4174 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4175 FoundFn, Conversion);
4176 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004177 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004178 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004179
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004180 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004181 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004182 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004183 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184
John McCalle3027922010-08-25 11:45:40 +00004185 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186
Douglas Gregor95562572010-04-24 23:45:46 +00004187 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189
4190 bool RequiresCopy = !IsCopy &&
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004191 getKind() != InitializationSequence::ReferenceBinding;
4192 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004193 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004194 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004195 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004196 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004198 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004199 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004200 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004201 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4202 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004203 }
4204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004206 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00004207 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004208 CurInit.get()->getType(),
4209 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00004210 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004212 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004213 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4214 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004215
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004216 break;
4217 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004218
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004219 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004220 case SK_QualificationConversionXValue:
4221 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004222 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004223 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004224 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004225 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004226 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004227 VK_XValue :
4228 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004229 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004230 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004231 }
4232
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004233 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004234 Sema::CheckedConversionKind CCK
4235 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4236 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4237 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4238 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004239 ExprResult CurInitExprRes =
4240 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004241 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004242 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004243 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004244 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004245 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregor51e77d52009-12-10 17:56:55 +00004248 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004249 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004250 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00004251 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00004252 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004253
4254 CurInit.release();
4255 CurInit = S.Owned(InitList);
4256 break;
4257 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004258
4259 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004260 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004261 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004262 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004264 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004265 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004266 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4267 ? Kind.getEqualLoc()
4268 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004269
4270 if (Kind.getKind() == InitializationKind::IK_Default) {
4271 // Force even a trivial, implicit default constructor to be
4272 // semantically checked. We do this explicitly because we don't build
4273 // the definition for completely trivial constructors.
4274 CXXRecordDecl *ClassDecl = Constructor->getParent();
4275 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004276 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004277 ClassDecl->hasTrivialDefaultConstructor() &&
4278 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004279 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4280 }
4281
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004282 // Determine the arguments required to actually perform the constructor
4283 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004285 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004286 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287
4288
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004289 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004290 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004291 (Kind.getKind() == InitializationKind::IK_Direct ||
4292 Kind.getKind() == InitializationKind::IK_Value)) {
4293 // An explicitly-constructed temporary, e.g., X(1, 2).
4294 unsigned NumExprs = ConstructorArgs.size();
4295 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004296 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004297 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298
Douglas Gregor2b88c112010-09-08 00:15:04 +00004299 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4300 if (!TSInfo)
4301 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004303 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4304 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004305 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004307 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004308 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004309 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004310 } else {
4311 CXXConstructExpr::ConstructionKind ConstructKind =
4312 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004314 if (Entity.getKind() == InitializedEntity::EK_Base) {
4315 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004317 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004318 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004319 ConstructKind = CXXConstructExpr::CK_Delegating;
4320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321
Chandler Carruth01718152010-10-25 08:47:36 +00004322 // Only get the parenthesis range if it is a direct construction.
4323 SourceRange parenRange =
4324 Kind.getKind() == InitializationKind::IK_Direct ?
4325 Kind.getParenRange() : SourceRange();
4326
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004327 // If the entity allows NRVO, mark the construction as elidable
4328 // unconditionally.
4329 if (Entity.allowsNRVO())
4330 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4331 Constructor, /*Elidable=*/true,
4332 move_arg(ConstructorArgs),
4333 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004334 ConstructKind,
4335 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004336 else
4337 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004339 move_arg(ConstructorArgs),
4340 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004341 ConstructKind,
4342 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004343 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004344 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004345 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004346
4347 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004348 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004349 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004350 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004352 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004353 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004355 break;
4356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004358 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004359 step_iterator NextStep = Step;
4360 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004362 NextStep->Kind == SK_ConstructorInitialization) {
4363 // The need for zero-initialization is recorded directly into
4364 // the call to the object's constructor within the next step.
4365 ConstructorInitRequiresZeroInit = true;
4366 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4367 S.getLangOptions().CPlusPlus &&
4368 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004369 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4370 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004372 Kind.getRange().getBegin());
4373
4374 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4375 TSInfo->getType().getNonLValueExprType(S.Context),
4376 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004377 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004378 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004379 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004380 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004381 break;
4382 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004383
4384 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004385 QualType SourceType = CurInit.get()->getType();
4386 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004387 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004388 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4389 if (Result.isInvalid())
4390 return ExprError();
4391 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004392
4393 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004394 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004395 if (ConvTy != Sema::Compatible &&
4396 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004397 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004398 == Sema::Compatible)
4399 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004400 if (CurInitExprRes.isInvalid())
4401 return ExprError();
4402 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004403
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004404 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004405 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4406 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004407 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004408 getAssignmentAction(Entity),
4409 &Complained)) {
4410 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004411 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004412 } else if (Complained)
4413 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004414 break;
4415 }
Eli Friedman78275202009-12-19 08:11:05 +00004416
4417 case SK_StringInit: {
4418 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004419 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004420 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004421 break;
4422 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004423
4424 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004425 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004426 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004427 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004428 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004429
4430 case SK_ArrayInit:
4431 // Okay: we checked everything before creating this step. Note that
4432 // this is a GNU extension.
4433 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004434 << Step->Type << CurInit.get()->getType()
4435 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004436
4437 // If the destination type is an incomplete array type, update the
4438 // type accordingly.
4439 if (ResultType) {
4440 if (const IncompleteArrayType *IncompleteDest
4441 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4442 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004443 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004444 *ResultType = S.Context.getConstantArrayType(
4445 IncompleteDest->getElementType(),
4446 ConstantSource->getSize(),
4447 ArrayType::Normal, 0);
4448 }
4449 }
4450 }
John McCall31168b02011-06-15 23:02:42 +00004451 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004452
John McCall31168b02011-06-15 23:02:42 +00004453 case SK_PassByIndirectCopyRestore:
4454 case SK_PassByIndirectRestore:
4455 checkIndirectCopyRestoreSource(S, CurInit.get());
4456 CurInit = S.Owned(new (S.Context)
4457 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4458 Step->Kind == SK_PassByIndirectCopyRestore));
4459 break;
4460
4461 case SK_ProduceObjCObject:
4462 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4463 CK_ObjCProduceObject,
4464 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004465 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004466 }
4467 }
John McCall1f425642010-11-11 03:21:53 +00004468
4469 // Diagnose non-fatal problems with the completed initialization.
4470 if (Entity.getKind() == InitializedEntity::EK_Member &&
4471 cast<FieldDecl>(Entity.getDecl())->isBitField())
4472 S.CheckBitFieldInitialization(Kind.getLocation(),
4473 cast<FieldDecl>(Entity.getDecl()),
4474 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004476 return move(CurInit);
4477}
4478
4479//===----------------------------------------------------------------------===//
4480// Diagnose initialization failures
4481//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004483 const InitializedEntity &Entity,
4484 const InitializationKind &Kind,
4485 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004486 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004487 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004488
Douglas Gregor1b303932009-12-22 15:35:07 +00004489 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004490 switch (Failure) {
4491 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004492 // FIXME: Customize for the initialized entity?
4493 if (NumArgs == 0)
4494 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4495 << DestType.getNonReferenceType();
4496 else // FIXME: diagnostic below could be better!
4497 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4498 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004499 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004500
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004501 case FK_ArrayNeedsInitList:
4502 case FK_ArrayNeedsInitListOrStringLiteral:
4503 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4504 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4505 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Douglas Gregore2f943b2011-02-22 18:29:51 +00004507 case FK_ArrayTypeMismatch:
4508 case FK_NonConstantArrayInit:
4509 S.Diag(Kind.getLocation(),
4510 (Failure == FK_ArrayTypeMismatch
4511 ? diag::err_array_init_different_type
4512 : diag::err_array_init_non_constant_array))
4513 << DestType.getNonReferenceType()
4514 << Args[0]->getType()
4515 << Args[0]->getSourceRange();
4516 break;
4517
John McCall16df1e52010-03-30 21:47:33 +00004518 case FK_AddressOfOverloadFailed: {
4519 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004521 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004522 true,
4523 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004524 break;
John McCall16df1e52010-03-30 21:47:33 +00004525 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004527 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004528 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004529 switch (FailedOverloadResult) {
4530 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004531 if (Failure == FK_UserConversionOverloadFailed)
4532 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4533 << Args[0]->getType() << DestType
4534 << Args[0]->getSourceRange();
4535 else
4536 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4537 << DestType << Args[0]->getType()
4538 << Args[0]->getSourceRange();
4539
John McCall5c32be02010-08-24 20:38:10 +00004540 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004541 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004543 case OR_No_Viable_Function:
4544 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4545 << Args[0]->getType() << DestType.getNonReferenceType()
4546 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004547 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004548 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004549
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004550 case OR_Deleted: {
4551 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4552 << Args[0]->getType() << DestType.getNonReferenceType()
4553 << Args[0]->getSourceRange();
4554 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004555 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004556 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4557 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004558 if (Ovl == OR_Deleted) {
4559 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004560 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004561 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004562 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004563 }
4564 break;
4565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004567 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004568 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004569 break;
4570 }
4571 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004573 case FK_NonConstLValueReferenceBindingToTemporary:
4574 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004576 Failure == FK_NonConstLValueReferenceBindingToTemporary
4577 ? diag::err_lvalue_reference_bind_to_temporary
4578 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004579 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004580 << DestType.getNonReferenceType()
4581 << Args[0]->getType()
4582 << Args[0]->getSourceRange();
4583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004585 case FK_RValueReferenceBindingToLValue:
4586 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004587 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004588 << Args[0]->getSourceRange();
4589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004590
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004591 case FK_ReferenceInitDropsQualifiers:
4592 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4593 << DestType.getNonReferenceType()
4594 << Args[0]->getType()
4595 << Args[0]->getSourceRange();
4596 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004598 case FK_ReferenceInitFailed:
4599 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4600 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004601 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004602 << Args[0]->getType()
4603 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004604 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4605 Args[0]->getType()->isObjCObjectPointerType())
4606 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608
Douglas Gregorb491ed32011-02-19 21:32:49 +00004609 case FK_ConversionFailed: {
4610 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004611 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4612 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004613 << DestType
John McCall086a4642010-11-24 05:12:34 +00004614 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004615 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004616 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004617 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4618 Args[0]->getType()->isObjCObjectPointerType())
4619 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004620 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004621 }
John Wiegley01296292011-04-08 18:41:53 +00004622
4623 case FK_ConversionFromPropertyFailed:
4624 // No-op. This error has already been reported.
4625 break;
4626
Douglas Gregor51e77d52009-12-10 17:56:55 +00004627 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004628 SourceRange R;
4629
4630 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004631 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004632 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004633 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004634 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004635
Douglas Gregor8ec51732010-09-08 21:40:08 +00004636 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4637 if (Kind.isCStyleOrFunctionalCast())
4638 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4639 << R;
4640 else
4641 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4642 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004643 break;
4644 }
4645
4646 case FK_ReferenceBindingToInitList:
4647 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4648 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4649 break;
4650
4651 case FK_InitListBadDestinationType:
4652 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4653 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4654 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004656 case FK_ConstructorOverloadFailed: {
4657 SourceRange ArgsRange;
4658 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004659 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004660 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004662 // FIXME: Using "DestType" for the entity we're printing is probably
4663 // bad.
4664 switch (FailedOverloadResult) {
4665 case OR_Ambiguous:
4666 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4667 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004668 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4669 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004670 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004672 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004673 if (Kind.getKind() == InitializationKind::IK_Default &&
4674 (Entity.getKind() == InitializedEntity::EK_Base ||
4675 Entity.getKind() == InitializedEntity::EK_Member) &&
4676 isa<CXXConstructorDecl>(S.CurContext)) {
4677 // This is implicit default initialization of a member or
4678 // base within a constructor. If no viable function was
4679 // found, notify the user that she needs to explicitly
4680 // initialize this base/member.
4681 CXXConstructorDecl *Constructor
4682 = cast<CXXConstructorDecl>(S.CurContext);
4683 if (Entity.getKind() == InitializedEntity::EK_Base) {
4684 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4685 << Constructor->isImplicit()
4686 << S.Context.getTypeDeclType(Constructor->getParent())
4687 << /*base=*/0
4688 << Entity.getType();
4689
4690 RecordDecl *BaseDecl
4691 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4692 ->getDecl();
4693 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4694 << S.Context.getTagDeclType(BaseDecl);
4695 } else {
4696 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4697 << Constructor->isImplicit()
4698 << S.Context.getTypeDeclType(Constructor->getParent())
4699 << /*member=*/1
4700 << Entity.getName();
4701 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4702
4703 if (const RecordType *Record
4704 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004706 diag::note_previous_decl)
4707 << S.Context.getTagDeclType(Record->getDecl());
4708 }
4709 break;
4710 }
4711
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004712 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4713 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004714 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004715 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004717 case OR_Deleted: {
4718 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4719 << true << DestType << ArgsRange;
4720 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004721 OverloadingResult Ovl
4722 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004723 if (Ovl == OR_Deleted) {
4724 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004725 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004726 } else {
4727 llvm_unreachable("Inconsistent overload resolution?");
4728 }
4729 break;
4730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004732 case OR_Success:
4733 llvm_unreachable("Conversion did not fail!");
4734 break;
4735 }
4736 break;
4737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Douglas Gregor85dabae2009-12-16 01:38:02 +00004739 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004740 if (Entity.getKind() == InitializedEntity::EK_Member &&
4741 isa<CXXConstructorDecl>(S.CurContext)) {
4742 // This is implicit default-initialization of a const member in
4743 // a constructor. Complain that it needs to be explicitly
4744 // initialized.
4745 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4746 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4747 << Constructor->isImplicit()
4748 << S.Context.getTypeDeclType(Constructor->getParent())
4749 << /*const=*/1
4750 << Entity.getName();
4751 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4752 << Entity.getName();
4753 } else {
4754 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4755 << DestType << (bool)DestType->getAs<RecordType>();
4756 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004757 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004759 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004761 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004762 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004765 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004766 return true;
4767}
Douglas Gregore1314a62009-12-18 05:02:21 +00004768
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004769void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4770 switch (SequenceKind) {
4771 case FailedSequence: {
4772 OS << "Failed sequence: ";
4773 switch (Failure) {
4774 case FK_TooManyInitsForReference:
4775 OS << "too many initializers for reference";
4776 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004778 case FK_ArrayNeedsInitList:
4779 OS << "array requires initializer list";
4780 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004782 case FK_ArrayNeedsInitListOrStringLiteral:
4783 OS << "array requires initializer list or string literal";
4784 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004785
Douglas Gregore2f943b2011-02-22 18:29:51 +00004786 case FK_ArrayTypeMismatch:
4787 OS << "array type mismatch";
4788 break;
4789
4790 case FK_NonConstantArrayInit:
4791 OS << "non-constant array initializer";
4792 break;
4793
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004794 case FK_AddressOfOverloadFailed:
4795 OS << "address of overloaded function failed";
4796 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004798 case FK_ReferenceInitOverloadFailed:
4799 OS << "overload resolution for reference initialization failed";
4800 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004802 case FK_NonConstLValueReferenceBindingToTemporary:
4803 OS << "non-const lvalue reference bound to temporary";
4804 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004806 case FK_NonConstLValueReferenceBindingToUnrelated:
4807 OS << "non-const lvalue reference bound to unrelated type";
4808 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004810 case FK_RValueReferenceBindingToLValue:
4811 OS << "rvalue reference bound to an lvalue";
4812 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004814 case FK_ReferenceInitDropsQualifiers:
4815 OS << "reference initialization drops qualifiers";
4816 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004818 case FK_ReferenceInitFailed:
4819 OS << "reference initialization failed";
4820 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004822 case FK_ConversionFailed:
4823 OS << "conversion failed";
4824 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004825
John Wiegley01296292011-04-08 18:41:53 +00004826 case FK_ConversionFromPropertyFailed:
4827 OS << "conversion from property failed";
4828 break;
4829
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004830 case FK_TooManyInitsForScalar:
4831 OS << "too many initializers for scalar";
4832 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004834 case FK_ReferenceBindingToInitList:
4835 OS << "referencing binding to initializer list";
4836 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004837
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004838 case FK_InitListBadDestinationType:
4839 OS << "initializer list for non-aggregate, non-scalar type";
4840 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004842 case FK_UserConversionOverloadFailed:
4843 OS << "overloading failed for user-defined conversion";
4844 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004846 case FK_ConstructorOverloadFailed:
4847 OS << "constructor overloading failed";
4848 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004849
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004850 case FK_DefaultInitOfConst:
4851 OS << "default initialization of a const variable";
4852 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004853
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004854 case FK_Incomplete:
4855 OS << "initialization of incomplete type";
4856 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004857 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004858 OS << '\n';
4859 return;
4860 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004862 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00004863 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004864 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865
Sebastian Redld201edf2011-06-05 13:59:11 +00004866 case NormalSequence:
4867 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004868 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004870 case ReferenceBinding:
4871 OS << "Reference binding: ";
4872 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004874
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004875 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4876 if (S != step_begin()) {
4877 OS << " -> ";
4878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004880 switch (S->Kind) {
4881 case SK_ResolveAddressOfOverloadedFunction:
4882 OS << "resolve address of overloaded function";
4883 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004885 case SK_CastDerivedToBaseRValue:
4886 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4887 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004889 case SK_CastDerivedToBaseXValue:
4890 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4891 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004892
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004893 case SK_CastDerivedToBaseLValue:
4894 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004897 case SK_BindReference:
4898 OS << "bind reference to lvalue";
4899 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004900
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004901 case SK_BindReferenceToTemporary:
4902 OS << "bind reference to a temporary";
4903 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004904
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004905 case SK_ExtraneousCopyToTemporary:
4906 OS << "extraneous C++03 copy to temporary";
4907 break;
4908
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004909 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004910 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004911 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004912
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004913 case SK_QualificationConversionRValue:
4914 OS << "qualification conversion (rvalue)";
4915
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004916 case SK_QualificationConversionXValue:
4917 OS << "qualification conversion (xvalue)";
4918
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004919 case SK_QualificationConversionLValue:
4920 OS << "qualification conversion (lvalue)";
4921 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004923 case SK_ConversionSequence:
4924 OS << "implicit conversion sequence (";
4925 S->ICS->DebugPrint(); // FIXME: use OS
4926 OS << ")";
4927 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004929 case SK_ListInitialization:
4930 OS << "list initialization";
4931 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004933 case SK_ConstructorInitialization:
4934 OS << "constructor initialization";
4935 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004936
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004937 case SK_ZeroInitialization:
4938 OS << "zero initialization";
4939 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004941 case SK_CAssignment:
4942 OS << "C assignment";
4943 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004945 case SK_StringInit:
4946 OS << "string initialization";
4947 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004948
4949 case SK_ObjCObjectConversion:
4950 OS << "Objective-C object conversion";
4951 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004952
4953 case SK_ArrayInit:
4954 OS << "array initialization";
4955 break;
John McCall31168b02011-06-15 23:02:42 +00004956
4957 case SK_PassByIndirectCopyRestore:
4958 OS << "pass by indirect copy and restore";
4959 break;
4960
4961 case SK_PassByIndirectRestore:
4962 OS << "pass by indirect restore";
4963 break;
4964
4965 case SK_ProduceObjCObject:
4966 OS << "Objective-C object retension";
4967 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004968 }
4969 }
4970}
4971
4972void InitializationSequence::dump() const {
4973 dump(llvm::errs());
4974}
4975
Douglas Gregore1314a62009-12-18 05:02:21 +00004976//===----------------------------------------------------------------------===//
4977// Initialization helper functions
4978//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00004979bool
4980Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
4981 ExprResult Init) {
4982 if (Init.isInvalid())
4983 return false;
4984
4985 Expr *InitE = Init.get();
4986 assert(InitE && "No initialization expression");
4987
4988 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
4989 SourceLocation());
4990 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004991 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00004992}
4993
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004994ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004995Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4996 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004997 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004998 if (Init.isInvalid())
4999 return ExprError();
5000
John McCall1f425642010-11-11 03:21:53 +00005001 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005002 assert(InitE && "No initialization expression?");
5003
5004 if (EqualLoc.isInvalid())
5005 EqualLoc = InitE->getLocStart();
5006
5007 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5008 EqualLoc);
5009 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5010 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00005011 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005012}