blob: e93d2d83cdfa2e0223b6141e6161b286f9153f79 [file] [log] [blame]
Steve Naroff0cca7492008-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 Lattnerdd8e0062009-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 Naroff0cca7492008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
John McCallce6c9b72011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-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 Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-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 Friedmanbb6415c2009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000055
Eli Friedmanbb6415c2009-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 Lattner8879e3b2009-02-26 23:26:43 +000062 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnerdd8e0062009-02-24 22:27:37 +000064 return 0;
65}
66
John McCallce6c9b72011-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 McCallfef8b342011-02-21 07:57:55 +000074static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
75 Sema &S) {
Chris Lattner79e079d2009-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 Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattnerdd8e0062009-02-24 22:27:37 +000081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000082 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000083 // being initialized to a string literal.
84 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000085 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000087 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
88 ConstVal,
89 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000090 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000091 }
Mike Stump1eb44332009-09-09 15:08:12 +000092
Eli Friedman8718a6a2009-05-29 18:22:49 +000093 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000094
Eli Friedmanbc34b1d2011-04-11 00:23:45 +000095 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-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 Friedmanbc34b1d2011-04-11 00:23:45 +000098 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-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 Friedmanbc34b1d2011-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 Stump1eb44332009-09-09 15:08:12 +0000120
Eli Friedman8718a6a2009-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 Lattnerdd8e0062009-02-24 22:27:37 +0000126}
127
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000128//===----------------------------------------------------------------------===//
129// Semantic checking for initializer lists.
130//===----------------------------------------------------------------------===//
131
Douglas Gregor9e80f722009-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 Bagnara63e7d252011-01-27 19:55:10 +0000146/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-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 Lattner8b419b92009-02-24 22:48:58 +0000159namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000160class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000161 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000162 bool hadError;
163 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
164 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000166 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000167 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000168 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000169 unsigned &StructuredIndex,
170 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000171 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000172 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000173 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000174 unsigned &StructuredIndex,
175 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000178 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000179 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000180 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000181 unsigned &StructuredIndex,
182 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000183 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000185 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000186 InitListExpr *StructuredList,
187 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000188 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 void CheckReferenceType(const InitializedEntity &Entity,
194 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000195 unsigned &Index,
196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000198 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000202 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000203 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000204 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000205 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000210 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000211 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000212 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000215 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000216 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregorc34ee5e2009-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 Gregor9e80f722009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000236
Douglas Gregord6d37de2009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-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 Lattner8b419b92009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000255 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000259 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-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 Takumidfbb02a2011-01-27 07:10:08 +0000278
Douglas Gregord6d37de2009-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 Takumidfbb02a2011-01-27 07:10:08 +0000287
John McCall60d7b3a2010-08-24 06:29:42 +0000288 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 if (MemberInit.isInvalid()) {
291 hadError = true;
292 return;
293 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294
Douglas Gregord6d37de2009-12-22 00:05:34 +0000295 if (hadError) {
296 // Do nothing
297 } else if (Init < NumInits) {
298 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000299 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-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 Kremenek709210f2010-04-13 23:39:13 +0000304 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000305 RequiresSecondPass = true;
306 }
307 } else if (InitListExpr *InnerILE
308 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000309 FillInValueInitializations(MemberEntity, InnerILE,
310 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000311}
312
Douglas Gregor4c678342009-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 Takumidfbb02a2011-01-27 07:10:08 +0000316void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000317InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
318 InitListExpr *ILE,
319 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000320 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000321 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000322 SourceLocation Loc = ILE->getSourceRange().getBegin();
323 if (ILE->getSyntacticForm())
324 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Ted Kremenek6217b802009-07-29 21:53:49 +0000326 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-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 Gregor4c678342009-01-28 21:54:33 +0000339
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000341 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000342
343 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
344 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000345 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000346
Douglas Gregord6d37de2009-12-22 00:05:34 +0000347 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000348
Douglas Gregord6d37de2009-12-22 00:05:34 +0000349 // Only look at the first initialization of a union.
350 if (RType->getDecl()->isUnion())
351 break;
352 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000353 }
354
355 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000356 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000357
358 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000360 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000361 unsigned NumInits = ILE->getNumInits();
362 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000363 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000364 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000365 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
366 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000367 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000368 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000369 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000370 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000371 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000372 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000373 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000374 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000375 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000376
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000377
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000379 if (hadError)
380 return;
381
Anders Carlssond3d824d2010-01-23 04:34:47 +0000382 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
383 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000384 ElementEntity.setElementIndex(Init);
385
Douglas Gregor87fd7032009-02-02 17:43:21 +0000386 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-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 Gregor87fd7032009-02-02 17:43:21 +0000392 hadError = true;
393 return;
394 }
395
John McCall60d7b3a2010-08-24 06:29:42 +0000396 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000397 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000399 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000400 return;
401 }
402
403 if (hadError) {
404 // Do nothing
405 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-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 Kyrtzidis4423ac02011-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 Redl7491c492011-06-05 13:59:11 +0000420 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-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 Gregorcb57fb92009-12-16 06:35:08 +0000428 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000429 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000430 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
431 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000432 }
433}
434
Chris Lattner68355a52009-01-29 05:10:57 +0000435
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000436InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
437 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000438 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000439 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000440
Eli Friedmanb85f7072008-05-19 19:16:24 +0000441 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000442 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000443 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000444 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000445 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000446 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000447 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000448
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000449 if (!hadError) {
450 bool RequiresSecondPass = false;
451 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000452 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000453 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000454 RequiresSecondPass);
455 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000456}
457
458int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000459 // FIXME: use a proper constant
460 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000461 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000462 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-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 Kremenek6217b802009-07-29 21:53:49 +0000469 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000470 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000471 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000472 Field = structDecl->field_begin(),
473 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000474 Field != FieldEnd; ++Field) {
475 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
476 ++InitializableMembers;
477 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000478 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000479 return std::min(InitializableMembers, 1);
480 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000481}
482
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000483void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000484 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000485 QualType T, unsigned &Index,
486 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000487 unsigned &StructuredIndex,
488 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000489 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Steve Naroff0cca7492008-05-01 22:18:59 +0000491 if (T->isArrayType())
492 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000493 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000494 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000495 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000496 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000497 else
498 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000499
Eli Friedman402256f2008-05-25 13:49:22 +0000500 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000501 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000502 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000504 hadError = true;
505 return;
506 }
507
Douglas Gregor4c678342009-01-28 21:54:33 +0000508 // Build a structured initializer list corresponding to this subobject.
509 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000510 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
511 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000512 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
513 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000515
Douglas Gregor4c678342009-01-28 21:54:33 +0000516 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000517 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000518 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000519 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000520 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000521 StructuredSubobjectInitIndex,
522 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000523 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000524 StructuredSubobjectInitList->setType(T);
525
Douglas Gregored8a93d2009-03-01 17:12:46 +0000526 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000527 // range corresponds with the end of the last initializer it used.
528 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000529 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000530 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
531 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
532 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000533
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000534 // Warn about missing braces.
535 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000536 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
537 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000538 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000539 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000540 "{")
541 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000542 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000543 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000544 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000545}
546
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000547void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000548 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000549 unsigned &Index,
550 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000551 unsigned &StructuredIndex,
552 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000553 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000554 SyntacticToSemantic[IList] = StructuredList;
555 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000557 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000558 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
559 IList->setType(ExprTy);
560 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000561 if (hadError)
562 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000563
Eli Friedman638e1442008-05-25 13:22:35 +0000564 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000565 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000566 if (StructuredIndex == 1 &&
567 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000568 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000569 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000570 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000571 hadError = true;
572 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000573 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000574 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000575 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000576 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000577 // Don't complain for incomplete types, since we'll get an error
578 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000579 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000580 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000581 CurrentObjectType->isArrayType()? 0 :
582 CurrentObjectType->isVectorType()? 1 :
583 CurrentObjectType->isScalarType()? 2 :
584 CurrentObjectType->isUnionType()? 3 :
585 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000586
587 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000588 if (SemaRef.getLangOptions().CPlusPlus) {
589 DK = diag::err_excess_initializers;
590 hadError = true;
591 }
Nate Begeman08634522009-07-07 21:53:06 +0000592 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
593 DK = diag::err_excess_initializers;
594 hadError = true;
595 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000596
Chris Lattner08202542009-02-24 22:50:46 +0000597 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000598 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000599 }
600 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000601
Eli Friedman759f2522009-05-16 11:45:48 +0000602 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000603 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000604 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000605 << FixItHint::CreateRemoval(IList->getLocStart())
606 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000607}
608
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000609void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000610 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000611 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000612 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000613 unsigned &Index,
614 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000615 unsigned &StructuredIndex,
616 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000617 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000618 CheckScalarType(Entity, IList, DeclType, Index,
619 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000620 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000621 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000622 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000623 } else if (DeclType->isAggregateType()) {
624 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000625 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000626 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000627 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000628 StructuredList, StructuredIndex,
629 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000630 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000631 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000632 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000633 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000634 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000635 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000636 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000637 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000639 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
640 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000641 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000642 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000643 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000644 hadError = true;
Douglas Gregor930d8b52009-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 Lattner08202542009-02-24 22:50:46 +0000654 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000655 << DeclType << IList->getSourceRange();
656 hadError = true;
657 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000658 CheckReferenceType(Entity, IList, DeclType, Index,
659 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000660 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000661 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
662 << DeclType;
663 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000664 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000665 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
666 << DeclType;
667 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000668 }
669}
670
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000671void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000672 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000673 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 unsigned &Index,
675 InitListExpr *StructuredList,
676 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000677 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000678 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
679 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000680 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000681 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000682 = getStructuredSubobjectInit(IList, Index, ElemType,
683 StructuredList, StructuredIndex,
684 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000685 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000686 newStructuredList, newStructuredIndex);
687 ++StructuredIndex;
688 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000689 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000690 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000691 return CheckScalarType(Entity, IList, ElemType, Index,
692 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000693 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000694 return CheckReferenceType(Entity, IList, ElemType, Index,
695 StructuredList, StructuredIndex);
696 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000697
John McCallfef8b342011-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 Takumidfbb02a2011-01-27 07:10:08 +0000702
John McCallfef8b342011-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 Gregor930d8b52009-01-30 22:09:00 +0000706 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000707 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000708 }
John McCallfef8b342011-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 Wiegley429bb272011-04-08 18:41:53 +0000746 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000747 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley429bb272011-04-08 18:41:53 +0000748 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCallfef8b342011-02-21 07:57:55 +0000749 == Sema::Compatible) {
John Wiegley429bb272011-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 McCallfef8b342011-02-21 07:57:55 +0000759 ++Index;
760 return;
761 }
John Wiegley429bb272011-04-08 18:41:53 +0000762 ExprRes.release();
John McCallfef8b342011-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 Gregor930d8b52009-01-30 22:09:00 +0000784 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000785}
786
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000787void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000788 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000789 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000790 InitListExpr *StructuredList,
791 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000792 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000793 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000794 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000795 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000796 ++Index;
797 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000798 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000799 }
John McCallb934c2d2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000830
John McCallb934c2d2010-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 Naroff0cca7492008-05-01 22:18:59 +0000841}
842
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000843void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
844 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-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 Lattner08202542009-02-24 22:50:46 +0000851 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000852 << DeclType << IList->getSourceRange();
853 hadError = true;
854 ++Index;
855 ++StructuredIndex;
856 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000857 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000858
John McCall60d7b3a2010-08-24 06:29:42 +0000859 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000860 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
861 SemaRef.Owned(expr));
862
863 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000864 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000865
866 expr = Result.takeAs<Expr>();
867 IList->setInit(Index, expr);
868
Douglas Gregor930d8b52009-01-30 22:09:00 +0000869 if (hadError)
870 ++StructuredIndex;
871 else
872 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
873 ++Index;
874 } else {
Mike Stump390b4cc2009-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 Stump1eb44332009-09-09 15:08:12 +0000879 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-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 Carlsson8ff9e862010-01-23 23:23:01 +0000890void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000891 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000892 unsigned &Index,
893 InitListExpr *StructuredList,
894 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000895 if (Index >= IList->getNumInits())
896 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
John McCall20e047a2010-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 Carlsson46f46592010-01-23 19:55:29 +0000902
John McCall20e047a2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000917
John McCall20e047a2010-10-30 00:11:39 +0000918 if (ResultExpr != Init) {
919 // The type was promoted, update initializer list.
920 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000921 }
922 }
John McCall20e047a2010-10-30 00:11:39 +0000923 if (hadError)
924 ++StructuredIndex;
925 else
926 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
927 ++Index;
928 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000929 }
Mike Stump1eb44332009-09-09 15:08:12 +0000930
John McCall20e047a2010-10-30 00:11:39 +0000931 InitializedEntity ElementEntity =
932 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933
John McCall20e047a2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000938
John McCall20e047a2010-10-30 00:11:39 +0000939 ElementEntity.setElementIndex(Index);
940 CheckSubElementType(ElementEntity, IList, elementType, Index,
941 StructuredList, StructuredIndex);
942 }
943 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000944 }
John McCall20e047a2010-10-30 00:11:39 +0000945
946 InitializedEntity ElementEntity =
947 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000948
John McCall20e047a2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000954
John McCall20e047a2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000966
John McCall20e047a2010-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 Wilsone86d78c2010-11-10 21:56:12 +0000971 IVT->getVectorKind());
John McCall20e047a2010-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 Naroff0cca7492008-05-01 22:18:59 +0000984}
985
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000986void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000987 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000988 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000989 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000990 unsigned &Index,
991 InitListExpr *StructuredList,
992 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +0000993 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
994
Steve Naroff0cca7492008-05-01 22:18:59 +0000995 // Check for the special-case of initializing an array with a string.
996 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +0000997 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +0000998 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +0000999 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-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 Lattnerf71ae8d2009-02-24 22:41:04 +00001005 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001006 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001007 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001008 return;
1009 }
1010 }
John McCallce6c9b72011-02-21 07:22:22 +00001011 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-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 Lattner08202542009-02-24 22:50:46 +00001015 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001016 diag::err_variable_object_no_init)
1017 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001018 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001019 ++Index;
1020 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001021 return;
1022 }
1023
Douglas Gregor05c13a32009-01-22 00:58:24 +00001024 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001025 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1026 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001027 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001028 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001029 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001030 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001031 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001032 maxElementsKnown = true;
1033 }
1034
John McCallce6c9b72011-02-21 07:22:22 +00001035 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-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 Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +00001044
Douglas Gregor87f55cf2009-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 Carlsson9a8a70e2010-01-23 22:49:02 +00001047 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001048 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001049 StructuredList, StructuredIndex, true,
1050 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001051 hadError = true;
1052 continue;
1053 }
1054
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001055 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001056 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001057 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001058 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001059 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001060
Douglas Gregor87f55cf2009-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 Gregor05c13a32009-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 Naroff0cca7492008-05-01 22:18:59 +00001072 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001073
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001074 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001075 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001076 Entity);
1077 // Check this element.
1078 CheckSubElementType(ElementEntity, IList, elementType, Index,
1079 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-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 Naroff0cca7492008-05-01 22:18:59 +00001086 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001087 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001088 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001089 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001090 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001091 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-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 Lattner08202542009-02-24 22:50:46 +00001094 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001095 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001096 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001097
Mike Stump1eb44332009-09-09 15:08:12 +00001098 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001099 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001100 }
1101}
1102
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001103void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001104 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001105 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001106 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001107 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001108 unsigned &Index,
1109 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001110 unsigned &StructuredIndex,
1111 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001112 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Eli Friedmanb85f7072008-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 Stump1eb44332009-09-09 15:08:12 +00001119 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001120
1121 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1122 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001123 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001124 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-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 Gregor05c13a32009-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 Kremenek6217b802009-07-29 21:53:49 +00001138 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001139 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001140 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001141 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-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 Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +00001151
Douglas Gregor87f55cf2009-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 Carlsson9a8a70e2010-01-23 22:49:02 +00001154 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001155 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001156 StructuredList, StructuredIndex,
1157 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001158 hadError = true;
1159
Douglas Gregordfb5e592009-02-12 19:00:39 +00001160 InitializedSomething = true;
John McCall80639de2010-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 Gregor05c13a32009-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 Gregordfb5e592009-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 Gregor44b43212008-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 Gregor0bb76892009-01-29 16:53:55 +00001181 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001182 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001183 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001184 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001185 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001186
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001187 InitializedEntity MemberEntity =
1188 InitializedEntity::InitializeMember(*Field, &Entity);
1189 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1190 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001191 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001192
1193 if (DeclType->isUnionType()) {
1194 // Initialize the first field within the union.
1195 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001196 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001197
1198 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001199 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001200
John McCall80639de2010-03-11 19:32:38 +00001201 // Emit warnings for missing struct field initializers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001202 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001203 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1204 // It is possible we have one or more unnamed bitfields remaining.
1205 // Find first (if any) named field and emit warning.
1206 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1207 it != end; ++it) {
1208 if (!it->isUnnamedBitfield()) {
1209 SemaRef.Diag(IList->getSourceRange().getEnd(),
1210 diag::warn_missing_field_initializers) << it->getName();
1211 break;
1212 }
1213 }
1214 }
1215
Mike Stump1eb44332009-09-09 15:08:12 +00001216 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001217 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001218 return;
1219
1220 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001221 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001222 (!isa<InitListExpr>(IList->getInit(Index)) ||
1223 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001224 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001225 diag::err_flexible_array_init_nonempty)
1226 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001227 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001228 << *Field;
1229 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001230 ++Index;
1231 return;
1232 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001233 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001234 diag::ext_flexible_array_init)
1235 << IList->getInit(Index)->getSourceRange().getBegin();
1236 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1237 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001238 }
1239
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001240 InitializedEntity MemberEntity =
1241 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001242
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001243 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001245 StructuredList, StructuredIndex);
1246 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001247 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001248 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001249}
Steve Naroff0cca7492008-05-01 22:18:59 +00001250
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001251/// \brief Expand a field designator that refers to a member of an
1252/// anonymous struct or union into a series of field designators that
1253/// refers to the field within the appropriate subobject.
1254///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001255static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001256 DesignatedInitExpr *DIE,
1257 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001258 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001259 typedef DesignatedInitExpr::Designator Designator;
1260
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001261 // Build the replacement designators.
1262 llvm::SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001263 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1264 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1265 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001266 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001267 DIE->getDesignator(DesigIdx)->getDotLoc(),
1268 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1269 else
1270 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1271 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001272 assert(isa<FieldDecl>(*PI));
1273 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001274 }
1275
1276 // Expand the current designator into the set of replacement
1277 // designators, so we have a full subobject path down to where the
1278 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001279 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001280 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001281}
Mike Stump1eb44332009-09-09 15:08:12 +00001282
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001283/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001284/// corresponds to FieldName.
1285static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1286 IdentifierInfo *FieldName) {
1287 assert(AnonField->isAnonymousStructOrUnion());
1288 Decl *NextDecl = AnonField->getNextDeclInContext();
1289 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1290 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1291 return IF;
1292 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001293 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001294 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001295}
1296
Douglas Gregor05c13a32009-01-22 00:58:24 +00001297/// @brief Check the well-formedness of a C99 designated initializer.
1298///
1299/// Determines whether the designated initializer @p DIE, which
1300/// resides at the given @p Index within the initializer list @p
1301/// IList, is well-formed for a current object of type @p DeclType
1302/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001303/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001304/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001305///
1306/// @param IList The initializer list in which this designated
1307/// initializer occurs.
1308///
Douglas Gregor71199712009-04-15 04:56:10 +00001309/// @param DIE The designated initializer expression.
1310///
1311/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001312///
1313/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1314/// into which the designation in @p DIE should refer.
1315///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001316/// @param NextField If non-NULL and the first designator in @p DIE is
1317/// a field, this will be set to the field declaration corresponding
1318/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001319///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001320/// @param NextElementIndex If non-NULL and the first designator in @p
1321/// DIE is an array designator or GNU array-range designator, this
1322/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001323///
1324/// @param Index Index into @p IList where the designated initializer
1325/// @p DIE occurs.
1326///
Douglas Gregor4c678342009-01-28 21:54:33 +00001327/// @param StructuredList The initializer list expression that
1328/// describes all of the subobject initializers in the order they'll
1329/// actually be initialized.
1330///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001331/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001332bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001333InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001334 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001335 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001336 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001337 QualType &CurrentObjectType,
1338 RecordDecl::field_iterator *NextField,
1339 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001340 unsigned &Index,
1341 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001342 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001343 bool FinishSubobjectInit,
1344 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001345 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001346 // Check the actual initialization for the designated object type.
1347 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001348
1349 // Temporarily remove the designator expression from the
1350 // initializer list that the child calls see, so that we don't try
1351 // to re-process the designator.
1352 unsigned OldIndex = Index;
1353 IList->setInit(OldIndex, DIE->getInit());
1354
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001355 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001356 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001357
1358 // Restore the designated initializer expression in the syntactic
1359 // form of the initializer list.
1360 if (IList->getInit(OldIndex) != DIE->getInit())
1361 DIE->setInit(IList->getInit(OldIndex));
1362 IList->setInit(OldIndex, DIE);
1363
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001364 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001365 }
1366
Douglas Gregor71199712009-04-15 04:56:10 +00001367 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001368 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001369 "Need a non-designated initializer list to start from");
1370
Douglas Gregor71199712009-04-15 04:56:10 +00001371 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001372 // Determine the structural initializer list that corresponds to the
1373 // current subobject.
1374 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001375 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001376 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001377 SourceRange(D->getStartLocation(),
1378 DIE->getSourceRange().getEnd()));
1379 assert(StructuredList && "Expected a structured initializer list");
1380
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001381 if (D->isFieldDesignator()) {
1382 // C99 6.7.8p7:
1383 //
1384 // If a designator has the form
1385 //
1386 // . identifier
1387 //
1388 // then the current object (defined below) shall have
1389 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001390 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001391 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001392 if (!RT) {
1393 SourceLocation Loc = D->getDotLoc();
1394 if (Loc.isInvalid())
1395 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001396 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1397 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001398 ++Index;
1399 return true;
1400 }
1401
Douglas Gregor4c678342009-01-28 21:54:33 +00001402 // Note: we perform a linear search of the fields here, despite
1403 // the fact that we have a faster lookup method, because we always
1404 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001405 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001407 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001408 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001409 Field = RT->getDecl()->field_begin(),
1410 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001411 for (; Field != FieldEnd; ++Field) {
1412 if (Field->isUnnamedBitfield())
1413 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414
Francois Picheta0e27f02010-12-22 03:46:10 +00001415 // If we find a field representing an anonymous field, look in the
1416 // IndirectFieldDecl that follow for the designated initializer.
1417 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1418 if (IndirectFieldDecl *IF =
1419 FindIndirectFieldDesignator(*Field, FieldName)) {
1420 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1421 D = DIE->getDesignator(DesigIdx);
1422 break;
1423 }
1424 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001425 if (KnownField && KnownField == *Field)
1426 break;
1427 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001428 break;
1429
1430 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001431 }
1432
Douglas Gregor4c678342009-01-28 21:54:33 +00001433 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001434 // There was no normal field in the struct with the designated
1435 // name. Perform another lookup for this name, which may find
1436 // something that we can't designate (e.g., a member function),
1437 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001438 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001439 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001440 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001441 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001442 // Name lookup didn't find anything. Determine whether this
1443 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001444 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001445 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001446 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001447 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001448 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001449 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001450 ->Equals(RT->getDecl())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001451 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001452 diag::err_field_designator_unknown_suggest)
1453 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001454 << FixItHint::CreateReplacement(D->getFieldLoc(),
1455 R.getLookupName().getAsString());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001456 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001457 diag::note_previous_decl)
1458 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001459 } else {
1460 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1461 << FieldName << CurrentObjectType;
1462 ++Index;
1463 return true;
1464 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001467 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001468 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001469 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001470 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001471 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001472 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001473 ++Index;
1474 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001475 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001476
Francois Picheta0e27f02010-12-22 03:46:10 +00001477 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001478 // The replacement field comes from typo correction; find it
1479 // in the list of fields.
1480 FieldIndex = 0;
1481 Field = RT->getDecl()->field_begin();
1482 for (; Field != FieldEnd; ++Field) {
1483 if (Field->isUnnamedBitfield())
1484 continue;
1485
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001486 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001487 Field->getIdentifier() == ReplacementField->getIdentifier())
1488 break;
1489
1490 ++FieldIndex;
1491 }
1492 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001493 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001494
1495 // All of the fields of a union are located at the same place in
1496 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001497 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001498 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001499 StructuredList->setInitializedFieldInUnion(*Field);
1500 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001501
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001502 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001503 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Douglas Gregor4c678342009-01-28 21:54:33 +00001505 // Make sure that our non-designated initializer list has space
1506 // for a subobject corresponding to this field.
1507 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001508 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001509
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001510 // This designator names a flexible array member.
1511 if (Field->getType()->isIncompleteArrayType()) {
1512 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001513 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001514 // We can't designate an object within the flexible array
1515 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001516 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001517 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001518 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001519 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001520 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001521 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001522 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001523 << *Field;
1524 Invalid = true;
1525 }
1526
Chris Lattner9046c222010-10-10 17:49:49 +00001527 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1528 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001529 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001530 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001531 diag::err_flexible_array_init_needs_braces)
1532 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001533 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001534 << *Field;
1535 Invalid = true;
1536 }
1537
1538 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001539 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001540 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001541 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001542 diag::err_flexible_array_init_nonempty)
1543 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001544 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001545 << *Field;
1546 Invalid = true;
1547 }
1548
1549 if (Invalid) {
1550 ++Index;
1551 return true;
1552 }
1553
1554 // Initialize the array.
1555 bool prevHadError = hadError;
1556 unsigned newStructuredIndex = FieldIndex;
1557 unsigned OldIndex = Index;
1558 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001559
1560 InitializedEntity MemberEntity =
1561 InitializedEntity::InitializeMember(*Field, &Entity);
1562 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001563 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001564
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001565 IList->setInit(OldIndex, DIE);
1566 if (hadError && !prevHadError) {
1567 ++Field;
1568 ++FieldIndex;
1569 if (NextField)
1570 *NextField = Field;
1571 StructuredIndex = FieldIndex;
1572 return true;
1573 }
1574 } else {
1575 // Recurse to check later designated subobjects.
1576 QualType FieldType = (*Field)->getType();
1577 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001578
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001579 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001580 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001581 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1582 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001583 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001584 true, false))
1585 return true;
1586 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001587
1588 // Find the position of the next field to be initialized in this
1589 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001590 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001591 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001592
1593 // If this the first designator, our caller will continue checking
1594 // the rest of this struct/class/union subobject.
1595 if (IsFirstDesignator) {
1596 if (NextField)
1597 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001598 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001599 return false;
1600 }
1601
Douglas Gregor34e79462009-01-28 23:36:17 +00001602 if (!FinishSubobjectInit)
1603 return false;
1604
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001605 // We've already initialized something in the union; we're done.
1606 if (RT->getDecl()->isUnion())
1607 return hadError;
1608
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001609 // Check the remaining fields within this class/struct/union subobject.
1610 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001611
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001612 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001613 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001614 return hadError && !prevHadError;
1615 }
1616
1617 // C99 6.7.8p6:
1618 //
1619 // If a designator has the form
1620 //
1621 // [ constant-expression ]
1622 //
1623 // then the current object (defined below) shall have array
1624 // type and the expression shall be an integer constant
1625 // expression. If the array is of unknown size, any
1626 // nonnegative value is valid.
1627 //
1628 // Additionally, cope with the GNU extension that permits
1629 // designators of the form
1630 //
1631 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001632 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001633 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001634 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001635 << CurrentObjectType;
1636 ++Index;
1637 return true;
1638 }
1639
1640 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001641 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1642 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001643 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001644 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001645 DesignatedEndIndex = DesignatedStartIndex;
1646 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001647 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001648
Mike Stump1eb44332009-09-09 15:08:12 +00001649 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001650 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001651 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001652 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001653 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001654
Chris Lattnere0fd8322011-02-19 22:28:58 +00001655 // Codegen can't handle evaluating array range designators that have side
1656 // effects, because we replicate the AST value for each initialized element.
1657 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1658 // elements with something that has a side effect, so codegen can emit an
1659 // "error unsupported" error instead of miscompiling the app.
1660 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1661 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregora9c87802009-01-29 19:42:23 +00001662 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001663 }
1664
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001665 if (isa<ConstantArrayType>(AT)) {
1666 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001667 DesignatedStartIndex
1668 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001669 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001670 DesignatedEndIndex
1671 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001672 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1673 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001674 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001675 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001676 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001677 << IndexExpr->getSourceRange();
1678 ++Index;
1679 return true;
1680 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001681 } else {
1682 // Make sure the bit-widths and signedness match.
1683 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001684 DesignatedEndIndex
1685 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001686 else if (DesignatedStartIndex.getBitWidth() <
1687 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001688 DesignatedStartIndex
1689 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001690 DesignatedStartIndex.setIsUnsigned(true);
1691 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Douglas Gregor4c678342009-01-28 21:54:33 +00001694 // Make sure that our non-designated initializer list has space
1695 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001696 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001697 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001698 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001699
Douglas Gregor34e79462009-01-28 23:36:17 +00001700 // Repeatedly perform subobject initializations in the range
1701 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001702
Douglas Gregor34e79462009-01-28 23:36:17 +00001703 // Move to the next designator
1704 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1705 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001706
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001707 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001708 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001709
Douglas Gregor34e79462009-01-28 23:36:17 +00001710 while (DesignatedStartIndex <= DesignatedEndIndex) {
1711 // Recurse to check later designated subobjects.
1712 QualType ElementType = AT->getElementType();
1713 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001714
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001715 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001716 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1717 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001718 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001719 (DesignatedStartIndex == DesignatedEndIndex),
1720 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001721 return true;
1722
1723 // Move to the next index in the array that we'll be initializing.
1724 ++DesignatedStartIndex;
1725 ElementIndex = DesignatedStartIndex.getZExtValue();
1726 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001727
1728 // If this the first designator, our caller will continue checking
1729 // the rest of this array subobject.
1730 if (IsFirstDesignator) {
1731 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001732 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001733 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001734 return false;
1735 }
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Douglas Gregor34e79462009-01-28 23:36:17 +00001737 if (!FinishSubobjectInit)
1738 return false;
1739
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001740 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001741 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001742 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001743 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001744 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001745 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001746}
1747
Douglas Gregor4c678342009-01-28 21:54:33 +00001748// Get the structured initializer list for a subobject of type
1749// @p CurrentObjectType.
1750InitListExpr *
1751InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1752 QualType CurrentObjectType,
1753 InitListExpr *StructuredList,
1754 unsigned StructuredIndex,
1755 SourceRange InitRange) {
1756 Expr *ExistingInit = 0;
1757 if (!StructuredList)
1758 ExistingInit = SyntacticToSemantic[IList];
1759 else if (StructuredIndex < StructuredList->getNumInits())
1760 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor4c678342009-01-28 21:54:33 +00001762 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1763 return Result;
1764
1765 if (ExistingInit) {
1766 // We are creating an initializer list that initializes the
1767 // subobjects of the current object, but there was already an
1768 // initialization that completely initialized the current
1769 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001770 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001771 // struct X { int a, b; };
1772 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001773 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001774 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1775 // designated initializer re-initializes the whole
1776 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001777 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001778 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001780 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001781 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001782 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001783 << ExistingInit->getSourceRange();
1784 }
1785
Mike Stump1eb44332009-09-09 15:08:12 +00001786 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001787 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1788 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001789 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001790
Douglas Gregor63982352010-07-13 18:40:04 +00001791 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001792
Douglas Gregorfa219202009-03-20 23:58:33 +00001793 // Pre-allocate storage for the structured initializer list.
1794 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001795 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001796 bool GotNumInits = false;
1797 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00001798 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001799 GotNumInits = true;
1800 } else if (Index < IList->getNumInits()) {
1801 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00001802 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001803 GotNumInits = true;
1804 }
Douglas Gregor08457732009-03-21 18:13:52 +00001805 }
1806
Mike Stump1eb44332009-09-09 15:08:12 +00001807 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001808 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1809 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1810 NumElements = CAType->getSize().getZExtValue();
1811 // Simple heuristic so that we don't allocate a very large
1812 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001813 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001814 NumElements = 0;
1815 }
John McCall183700f2009-09-21 23:43:11 +00001816 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001817 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001818 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001819 RecordDecl *RDecl = RType->getDecl();
1820 if (RDecl->isUnion())
1821 NumElements = 1;
1822 else
Mike Stump1eb44332009-09-09 15:08:12 +00001823 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001824 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001825 }
1826
Douglas Gregor08457732009-03-21 18:13:52 +00001827 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001828 NumElements = IList->getNumInits();
1829
Ted Kremenek709210f2010-04-13 23:39:13 +00001830 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001831
Douglas Gregor4c678342009-01-28 21:54:33 +00001832 // Link this new initializer list into the structured initializer
1833 // lists.
1834 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001835 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001836 else {
1837 Result->setSyntacticForm(IList);
1838 SyntacticToSemantic[IList] = Result;
1839 }
1840
1841 return Result;
1842}
1843
1844/// Update the initializer at index @p StructuredIndex within the
1845/// structured initializer list to the value @p expr.
1846void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1847 unsigned &StructuredIndex,
1848 Expr *expr) {
1849 // No structured initializer list to update
1850 if (!StructuredList)
1851 return;
1852
Ted Kremenek709210f2010-04-13 23:39:13 +00001853 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1854 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001855 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001856 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001857 diag::warn_initializer_overrides)
1858 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001859 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001860 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001861 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001862 << PrevInit->getSourceRange();
1863 }
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregor4c678342009-01-28 21:54:33 +00001865 ++StructuredIndex;
1866}
1867
Douglas Gregor05c13a32009-01-22 00:58:24 +00001868/// Check that the given Index expression is a valid array designator
1869/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001870/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001871/// and produces a reasonable diagnostic if there is a
1872/// failure. Returns true if there was an error, false otherwise. If
1873/// everything went okay, Value will receive the value of the constant
1874/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001875static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001876CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001877 SourceLocation Loc = Index->getSourceRange().getBegin();
1878
1879 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001880 if (S.VerifyIntegerConstantExpression(Index, &Value))
1881 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001882
Chris Lattner3bf68932009-04-25 21:59:05 +00001883 if (Value.isSigned() && Value.isNegative())
1884 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001885 << Value.toString(10) << Index->getSourceRange();
1886
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001887 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001888 return false;
1889}
1890
John McCall60d7b3a2010-08-24 06:29:42 +00001891ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001892 SourceLocation Loc,
1893 bool GNUSyntax,
1894 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001895 typedef DesignatedInitExpr::Designator ASTDesignator;
1896
1897 bool Invalid = false;
1898 llvm::SmallVector<ASTDesignator, 32> Designators;
1899 llvm::SmallVector<Expr *, 32> InitExpressions;
1900
1901 // Build designators and check array designator expressions.
1902 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1903 const Designator &D = Desig.getDesignator(Idx);
1904 switch (D.getKind()) {
1905 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001906 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001907 D.getFieldLoc()));
1908 break;
1909
1910 case Designator::ArrayDesignator: {
1911 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1912 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001913 if (!Index->isTypeDependent() &&
1914 !Index->isValueDependent() &&
1915 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001916 Invalid = true;
1917 else {
1918 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001919 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001920 D.getRBracketLoc()));
1921 InitExpressions.push_back(Index);
1922 }
1923 break;
1924 }
1925
1926 case Designator::ArrayRangeDesignator: {
1927 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1928 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1929 llvm::APSInt StartValue;
1930 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001931 bool StartDependent = StartIndex->isTypeDependent() ||
1932 StartIndex->isValueDependent();
1933 bool EndDependent = EndIndex->isTypeDependent() ||
1934 EndIndex->isValueDependent();
1935 if ((!StartDependent &&
1936 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1937 (!EndDependent &&
1938 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001939 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001940 else {
1941 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001942 if (StartDependent || EndDependent) {
1943 // Nothing to compute.
1944 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001945 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001946 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001947 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001948
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001949 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001950 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001951 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001952 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1953 Invalid = true;
1954 } else {
1955 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001956 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001957 D.getEllipsisLoc(),
1958 D.getRBracketLoc()));
1959 InitExpressions.push_back(StartIndex);
1960 InitExpressions.push_back(EndIndex);
1961 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001962 }
1963 break;
1964 }
1965 }
1966 }
1967
1968 if (Invalid || Init.isInvalid())
1969 return ExprError();
1970
1971 // Clear out the expressions within the designation.
1972 Desig.ClearExprs(*this);
1973
1974 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001975 = DesignatedInitExpr::Create(Context,
1976 Designators.data(), Designators.size(),
1977 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001978 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001979
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00001980 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00001981 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
1982 << DIE->getSourceRange();
1983 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00001984 Diag(DIE->getLocStart(), diag::ext_designated_init)
1985 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001986
Douglas Gregor05c13a32009-01-22 00:58:24 +00001987 return Owned(DIE);
1988}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001989
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001990bool Sema::CheckInitList(const InitializedEntity &Entity,
1991 InitListExpr *&InitList, QualType &DeclType) {
1992 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001993 if (!CheckInitList.HadError())
1994 InitList = CheckInitList.getFullyStructuredList();
1995
1996 return CheckInitList.HadError();
1997}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001998
Douglas Gregor20093b42009-12-09 23:02:17 +00001999//===----------------------------------------------------------------------===//
2000// Initialization entity
2001//===----------------------------------------------------------------------===//
2002
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002003InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002004 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002005 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002006{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002007 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2008 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002009 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002010 } else {
2011 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002012 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002013 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002014}
2015
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002016InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002017 CXXBaseSpecifier *Base,
2018 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002019{
2020 InitializedEntity Result;
2021 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002022 Result.Base = reinterpret_cast<uintptr_t>(Base);
2023 if (IsInheritedVirtualBase)
2024 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002025
Douglas Gregord6542d82009-12-22 15:35:07 +00002026 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002027 return Result;
2028}
2029
Douglas Gregor99a2e602009-12-16 01:38:02 +00002030DeclarationName InitializedEntity::getName() const {
2031 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002032 case EK_Parameter: {
2033 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2034 return (D ? D->getDeclName() : DeclarationName());
2035 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002036
2037 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002038 case EK_Member:
2039 return VariableOrMember->getDeclName();
2040
2041 case EK_Result:
2042 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002043 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002044 case EK_Temporary:
2045 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002046 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002047 case EK_ArrayElement:
2048 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002049 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002050 return DeclarationName();
2051 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002052
Douglas Gregor99a2e602009-12-16 01:38:02 +00002053 // Silence GCC warning
2054 return DeclarationName();
2055}
2056
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002057DeclaratorDecl *InitializedEntity::getDecl() const {
2058 switch (getKind()) {
2059 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002060 case EK_Member:
2061 return VariableOrMember;
2062
John McCallf85e1932011-06-15 23:02:42 +00002063 case EK_Parameter:
2064 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2065
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002066 case EK_Result:
2067 case EK_Exception:
2068 case EK_New:
2069 case EK_Temporary:
2070 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002071 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002072 case EK_ArrayElement:
2073 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002074 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002075 return 0;
2076 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002077
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002078 // Silence GCC warning
2079 return 0;
2080}
2081
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002082bool InitializedEntity::allowsNRVO() const {
2083 switch (getKind()) {
2084 case EK_Result:
2085 case EK_Exception:
2086 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002088 case EK_Variable:
2089 case EK_Parameter:
2090 case EK_Member:
2091 case EK_New:
2092 case EK_Temporary:
2093 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002094 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002095 case EK_ArrayElement:
2096 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002097 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002098 break;
2099 }
2100
2101 return false;
2102}
2103
Douglas Gregor20093b42009-12-09 23:02:17 +00002104//===----------------------------------------------------------------------===//
2105// Initialization sequence
2106//===----------------------------------------------------------------------===//
2107
2108void InitializationSequence::Step::Destroy() {
2109 switch (Kind) {
2110 case SK_ResolveAddressOfOverloadedFunction:
2111 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002112 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002113 case SK_CastDerivedToBaseLValue:
2114 case SK_BindReference:
2115 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002116 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002117 case SK_UserConversion:
2118 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002119 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002120 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002121 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002122 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002123 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002124 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002125 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002126 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002127 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002128 case SK_PassByIndirectCopyRestore:
2129 case SK_PassByIndirectRestore:
2130 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002131 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002132
Douglas Gregor20093b42009-12-09 23:02:17 +00002133 case SK_ConversionSequence:
2134 delete ICS;
2135 }
2136}
2137
Douglas Gregorb70cf442010-03-26 20:14:36 +00002138bool InitializationSequence::isDirectReferenceBinding() const {
2139 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2140}
2141
2142bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002143 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002144 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002145
Douglas Gregorb70cf442010-03-26 20:14:36 +00002146 switch (getFailureKind()) {
2147 case FK_TooManyInitsForReference:
2148 case FK_ArrayNeedsInitList:
2149 case FK_ArrayNeedsInitListOrStringLiteral:
2150 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2151 case FK_NonConstLValueReferenceBindingToTemporary:
2152 case FK_NonConstLValueReferenceBindingToUnrelated:
2153 case FK_RValueReferenceBindingToLValue:
2154 case FK_ReferenceInitDropsQualifiers:
2155 case FK_ReferenceInitFailed:
2156 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002157 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002158 case FK_TooManyInitsForScalar:
2159 case FK_ReferenceBindingToInitList:
2160 case FK_InitListBadDestinationType:
2161 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002162 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002163 case FK_ArrayTypeMismatch:
2164 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002165 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002166
Douglas Gregorb70cf442010-03-26 20:14:36 +00002167 case FK_ReferenceInitOverloadFailed:
2168 case FK_UserConversionOverloadFailed:
2169 case FK_ConstructorOverloadFailed:
2170 return FailedOverloadResult == OR_Ambiguous;
2171 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002172
Douglas Gregorb70cf442010-03-26 20:14:36 +00002173 return false;
2174}
2175
Douglas Gregord6e44a32010-04-16 22:09:46 +00002176bool InitializationSequence::isConstructorInitialization() const {
2177 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2178}
2179
Douglas Gregor20093b42009-12-09 23:02:17 +00002180void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002181 FunctionDecl *Function,
2182 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002183 Step S;
2184 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2185 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002186 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002187 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002188 Steps.push_back(S);
2189}
2190
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002191void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002192 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002193 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002194 switch (VK) {
2195 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2196 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2197 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002198 default: llvm_unreachable("No such category");
2199 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002200 S.Type = BaseType;
2201 Steps.push_back(S);
2202}
2203
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002204void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002205 bool BindingTemporary) {
2206 Step S;
2207 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2208 S.Type = T;
2209 Steps.push_back(S);
2210}
2211
Douglas Gregor523d46a2010-04-18 07:40:54 +00002212void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2213 Step S;
2214 S.Kind = SK_ExtraneousCopyToTemporary;
2215 S.Type = T;
2216 Steps.push_back(S);
2217}
2218
Eli Friedman03981012009-12-11 02:42:07 +00002219void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002220 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002221 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002222 Step S;
2223 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002224 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002225 S.Function.Function = Function;
2226 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002227 Steps.push_back(S);
2228}
2229
2230void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002231 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002232 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002233 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002234 switch (VK) {
2235 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002236 S.Kind = SK_QualificationConversionRValue;
2237 break;
John McCall5baba9d2010-08-25 10:28:54 +00002238 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002239 S.Kind = SK_QualificationConversionXValue;
2240 break;
John McCall5baba9d2010-08-25 10:28:54 +00002241 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002242 S.Kind = SK_QualificationConversionLValue;
2243 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002244 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002245 S.Type = Ty;
2246 Steps.push_back(S);
2247}
2248
2249void InitializationSequence::AddConversionSequenceStep(
2250 const ImplicitConversionSequence &ICS,
2251 QualType T) {
2252 Step S;
2253 S.Kind = SK_ConversionSequence;
2254 S.Type = T;
2255 S.ICS = new ImplicitConversionSequence(ICS);
2256 Steps.push_back(S);
2257}
2258
Douglas Gregord87b61f2009-12-10 17:56:55 +00002259void InitializationSequence::AddListInitializationStep(QualType T) {
2260 Step S;
2261 S.Kind = SK_ListInitialization;
2262 S.Type = T;
2263 Steps.push_back(S);
2264}
2265
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002266void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002267InitializationSequence::AddConstructorInitializationStep(
2268 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002269 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002270 QualType T) {
2271 Step S;
2272 S.Kind = SK_ConstructorInitialization;
2273 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002274 S.Function.Function = Constructor;
2275 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002276 Steps.push_back(S);
2277}
2278
Douglas Gregor71d17402009-12-15 00:01:57 +00002279void InitializationSequence::AddZeroInitializationStep(QualType T) {
2280 Step S;
2281 S.Kind = SK_ZeroInitialization;
2282 S.Type = T;
2283 Steps.push_back(S);
2284}
2285
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002286void InitializationSequence::AddCAssignmentStep(QualType T) {
2287 Step S;
2288 S.Kind = SK_CAssignment;
2289 S.Type = T;
2290 Steps.push_back(S);
2291}
2292
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002293void InitializationSequence::AddStringInitStep(QualType T) {
2294 Step S;
2295 S.Kind = SK_StringInit;
2296 S.Type = T;
2297 Steps.push_back(S);
2298}
2299
Douglas Gregor569c3162010-08-07 11:51:51 +00002300void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2301 Step S;
2302 S.Kind = SK_ObjCObjectConversion;
2303 S.Type = T;
2304 Steps.push_back(S);
2305}
2306
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002307void InitializationSequence::AddArrayInitStep(QualType T) {
2308 Step S;
2309 S.Kind = SK_ArrayInit;
2310 S.Type = T;
2311 Steps.push_back(S);
2312}
2313
John McCallf85e1932011-06-15 23:02:42 +00002314void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2315 bool shouldCopy) {
2316 Step s;
2317 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2318 : SK_PassByIndirectRestore);
2319 s.Type = type;
2320 Steps.push_back(s);
2321}
2322
2323void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2324 Step S;
2325 S.Kind = SK_ProduceObjCObject;
2326 S.Type = T;
2327 Steps.push_back(S);
2328}
2329
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002330void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002331 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002332 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002333 this->Failure = Failure;
2334 this->FailedOverloadResult = Result;
2335}
2336
2337//===----------------------------------------------------------------------===//
2338// Attempt initialization
2339//===----------------------------------------------------------------------===//
2340
John McCallf85e1932011-06-15 23:02:42 +00002341static void MaybeProduceObjCObject(Sema &S,
2342 InitializationSequence &Sequence,
2343 const InitializedEntity &Entity) {
2344 if (!S.getLangOptions().ObjCAutoRefCount) return;
2345
2346 /// When initializing a parameter, produce the value if it's marked
2347 /// __attribute__((ns_consumed)).
2348 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2349 if (!Entity.isParameterConsumed())
2350 return;
2351
2352 assert(Entity.getType()->isObjCRetainableType() &&
2353 "consuming an object of unretainable type?");
2354 Sequence.AddProduceObjCObjectStep(Entity.getType());
2355
2356 /// When initializing a return value, if the return type is a
2357 /// retainable type, then returns need to immediately retain the
2358 /// object. If an autorelease is required, it will be done at the
2359 /// last instant.
2360 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2361 if (!Entity.getType()->isObjCRetainableType())
2362 return;
2363
2364 Sequence.AddProduceObjCObjectStep(Entity.getType());
2365 }
2366}
2367
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002368/// \brief Attempt list initialization (C++0x [dcl.init.list])
2369static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002370 const InitializedEntity &Entity,
2371 const InitializationKind &Kind,
2372 InitListExpr *InitList,
2373 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002374 // FIXME: We only perform rudimentary checking of list
2375 // initializations at this point, then assume that any list
2376 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002377 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002378 // do all of the necessary checking. C++0x initializer lists will
2379 // force us to perform more checking here.
Douglas Gregord87b61f2009-12-10 17:56:55 +00002380
Douglas Gregord6542d82009-12-22 15:35:07 +00002381 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002382
2383 // C++ [dcl.init]p13:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002384 // If T is a scalar type, then a declaration of the form
Douglas Gregord87b61f2009-12-10 17:56:55 +00002385 //
2386 // T x = { a };
2387 //
2388 // is equivalent to
2389 //
2390 // T x = a;
2391 if (DestType->isScalarType()) {
2392 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2393 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2394 return;
2395 }
2396
2397 // Assume scalar initialization from a single value works.
2398 } else if (DestType->isAggregateType()) {
2399 // Assume aggregate initialization works.
2400 } else if (DestType->isVectorType()) {
2401 // Assume vector initialization works.
2402 } else if (DestType->isReferenceType()) {
2403 // FIXME: C++0x defines behavior for this.
2404 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2405 return;
2406 } else if (DestType->isRecordType()) {
2407 // FIXME: C++0x defines behavior for this
2408 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2409 }
2410
2411 // Add a general "list initialization" step.
2412 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002413}
2414
2415/// \brief Try a reference initialization that involves calling a conversion
2416/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002417static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2418 const InitializedEntity &Entity,
2419 const InitializationKind &Kind,
2420 Expr *Initializer,
2421 bool AllowRValues,
2422 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002423 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002424 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2425 QualType T1 = cv1T1.getUnqualifiedType();
2426 QualType cv2T2 = Initializer->getType();
2427 QualType T2 = cv2T2.getUnqualifiedType();
2428
2429 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002430 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002431 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002432 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002433 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002434 ObjCConversion,
2435 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002436 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002437 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002438 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002439 (void)ObjCLifetimeConversion;
2440
Douglas Gregor20093b42009-12-09 23:02:17 +00002441 // Build the candidate set directly in the initialization sequence
2442 // structure, so that it will persist if we fail.
2443 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2444 CandidateSet.clear();
2445
2446 // Determine whether we are allowed to call explicit constructors or
2447 // explicit conversion operators.
2448 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002449
Douglas Gregor20093b42009-12-09 23:02:17 +00002450 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002451 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2452 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002453 // The type we're converting to is a class type. Enumerate its constructors
2454 // to see if there is a suitable conversion.
2455 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002456
Douglas Gregor20093b42009-12-09 23:02:17 +00002457 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002458 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002459 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002460 NamedDecl *D = *Con;
2461 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2462
Douglas Gregor20093b42009-12-09 23:02:17 +00002463 // Find the constructor (which may be a template).
2464 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002465 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002466 if (ConstructorTmpl)
2467 Constructor = cast<CXXConstructorDecl>(
2468 ConstructorTmpl->getTemplatedDecl());
2469 else
John McCall9aa472c2010-03-19 07:35:19 +00002470 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002471
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 if (!Constructor->isInvalidDecl() &&
2473 Constructor->isConvertingConstructor(AllowExplicit)) {
2474 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002475 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002476 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002477 &Initializer, 1, CandidateSet,
2478 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002479 else
John McCall9aa472c2010-03-19 07:35:19 +00002480 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002481 &Initializer, 1, CandidateSet,
2482 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002483 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002484 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002485 }
John McCall572fc622010-08-17 07:23:57 +00002486 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2487 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002488
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002489 const RecordType *T2RecordType = 0;
2490 if ((T2RecordType = T2->getAs<RecordType>()) &&
2491 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002492 // The type we're converting from is a class type, enumerate its conversion
2493 // functions.
2494 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2495
John McCalleec51cf2010-01-20 00:46:10 +00002496 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002497 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002498 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2499 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002500 NamedDecl *D = *I;
2501 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2502 if (isa<UsingShadowDecl>(D))
2503 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002504
Douglas Gregor20093b42009-12-09 23:02:17 +00002505 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2506 CXXConversionDecl *Conv;
2507 if (ConvTemplate)
2508 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2509 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002510 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002511
Douglas Gregor20093b42009-12-09 23:02:17 +00002512 // If the conversion function doesn't return a reference type,
2513 // it can't be considered for this conversion unless we're allowed to
2514 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002515 // FIXME: Do we need to make sure that we only consider conversion
2516 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002517 // break recursion.
2518 if ((AllowExplicit || !Conv->isExplicit()) &&
2519 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2520 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002521 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002522 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002523 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002524 else
John McCall9aa472c2010-03-19 07:35:19 +00002525 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002526 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002527 }
2528 }
2529 }
John McCall572fc622010-08-17 07:23:57 +00002530 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2531 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002532
Douglas Gregor20093b42009-12-09 23:02:17 +00002533 SourceLocation DeclLoc = Initializer->getLocStart();
2534
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002535 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002537 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002538 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002539 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002540
Douglas Gregor20093b42009-12-09 23:02:17 +00002541 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002542
Chandler Carruth25ca4212011-02-25 19:41:05 +00002543 // This is the overload that will actually be used for the initialization, so
2544 // mark it as used.
2545 S.MarkDeclarationReferenced(DeclLoc, Function);
2546
Eli Friedman03981012009-12-11 02:42:07 +00002547 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002548 if (isa<CXXConversionDecl>(Function))
2549 T2 = Function->getResultType();
2550 else
2551 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002552
2553 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002554 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002555 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002556
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002557 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002558 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002559 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002560 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002561 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002562 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002563 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002564
Douglas Gregor20093b42009-12-09 23:02:17 +00002565 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002566 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002567 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002568 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002569 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002570 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002571 NewDerivedToBase, NewObjCConversion,
2572 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002573 if (NewRefRelationship == Sema::Ref_Incompatible) {
2574 // If the type we've converted to is not reference-related to the
2575 // type we're looking for, then there is another conversion step
2576 // we need to perform to produce a temporary of the right type
2577 // that we'll be binding to.
2578 ImplicitConversionSequence ICS;
2579 ICS.setStandard();
2580 ICS.Standard = Best->FinalConversion;
2581 T2 = ICS.Standard.getToType(2);
2582 Sequence.AddConversionSequenceStep(ICS, T2);
2583 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002584 Sequence.AddDerivedToBaseCastStep(
2585 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002586 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002587 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002588 else if (NewObjCConversion)
2589 Sequence.AddObjCObjectConversionStep(
2590 S.Context.getQualifiedType(T1,
2591 T2.getNonReferenceType().getQualifiers()));
2592
Douglas Gregor20093b42009-12-09 23:02:17 +00002593 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002594 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595
Douglas Gregor20093b42009-12-09 23:02:17 +00002596 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2597 return OR_Success;
2598}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002599
2600/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2601static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002602 const InitializedEntity &Entity,
2603 const InitializationKind &Kind,
2604 Expr *Initializer,
2605 InitializationSequence &Sequence) {
2606 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002607
Douglas Gregord6542d82009-12-22 15:35:07 +00002608 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002609 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002610 Qualifiers T1Quals;
2611 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002613 Qualifiers T2Quals;
2614 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002615 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002616
Douglas Gregor20093b42009-12-09 23:02:17 +00002617 // If the initializer is the address of an overloaded function, try
2618 // to resolve the overloaded function. If all goes well, T2 is the
2619 // type of the resulting function.
2620 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002621 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002622 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002623 T1,
2624 false,
2625 Found)) {
2626 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2627 cv2T2 = Fn->getType();
2628 T2 = cv2T2.getUnqualifiedType();
2629 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002630 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2631 return;
2632 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002633 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002634
Douglas Gregor20093b42009-12-09 23:02:17 +00002635 // Compute some basic properties of the types and the initializer.
2636 bool isLValueRef = DestType->isLValueReferenceType();
2637 bool isRValueRef = !isLValueRef;
2638 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002639 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002640 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002641 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002642 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002643 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002644 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002645
Douglas Gregor20093b42009-12-09 23:02:17 +00002646 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002647 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002648 // "cv2 T2" as follows:
2649 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002650 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002651 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002652 // Note the analogous bullet points for rvlaue refs to functions. Because
2653 // there are no function rvalues in C++, rvalue refs to functions are treated
2654 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002655 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002656 bool T1Function = T1->isFunctionType();
2657 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002658 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002659 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002660 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002661 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002662 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002663 // reference-compatible with "cv2 T2," or
2664 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002665 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002666 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002667 // can occur. However, we do pay attention to whether it is a bit-field
2668 // to decide whether we're actually binding to a temporary created from
2669 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002670 if (DerivedToBase)
2671 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002672 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002673 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002674 else if (ObjCConversion)
2675 Sequence.AddObjCObjectConversionStep(
2676 S.Context.getQualifiedType(T1, T2Quals));
2677
Chandler Carruth5535c382010-01-12 20:32:25 +00002678 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002679 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002680 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002681 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002682 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002683 return;
2684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002685
2686 // - has a class type (i.e., T2 is a class type), where T1 is not
2687 // reference-related to T2, and can be implicitly converted to an
2688 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2689 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002690 // applicable conversion functions (13.3.1.6) and choosing the best
2691 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002692 // If we have an rvalue ref to function type here, the rhs must be
2693 // an rvalue.
2694 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2695 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002696 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002697 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002698 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002699 Sequence);
2700 if (ConvOvlResult == OR_Success)
2701 return;
John McCall1d318332010-01-12 00:44:57 +00002702 if (ConvOvlResult != OR_No_Viable_Function) {
2703 Sequence.SetOverloadFailure(
2704 InitializationSequence::FK_ReferenceInitOverloadFailed,
2705 ConvOvlResult);
2706 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002707 }
2708 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002709
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002710 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002711 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002712 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002713 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002714 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2715 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2716 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002717 Sequence.SetOverloadFailure(
2718 InitializationSequence::FK_ReferenceInitOverloadFailed,
2719 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002720 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002721 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002722 ? (RefRelationship == Sema::Ref_Related
2723 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2724 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2725 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002726
Douglas Gregor20093b42009-12-09 23:02:17 +00002727 return;
2728 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002729
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002730 // - If the initializer expression
2731 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2732 // "cv1 T1" is reference-compatible with "cv2 T2"
2733 // Note: functions are handled below.
2734 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002735 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002736 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002737 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002738 (InitCategory.isXValue() ||
2739 (InitCategory.isPRValue() && T2->isRecordType()) ||
2740 (InitCategory.isPRValue() && T2->isArrayType()))) {
2741 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2742 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002743 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2744 // compiler the freedom to perform a copy here or bind to the
2745 // object, while C++0x requires that we bind directly to the
2746 // object. Hence, we always bind to the object without making an
2747 // extra copy. However, in C++03 requires that we check for the
2748 // presence of a suitable copy constructor:
2749 //
2750 // The constructor that would be used to make the copy shall
2751 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002752 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002753 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002754 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002755
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002756 if (DerivedToBase)
2757 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2758 ValueKind);
2759 else if (ObjCConversion)
2760 Sequence.AddObjCObjectConversionStep(
2761 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002762
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002763 if (T1Quals != T2Quals)
2764 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002765 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002766 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002767 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002768 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002769
2770 // - has a class type (i.e., T2 is a class type), where T1 is not
2771 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002772 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2773 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002774 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002775 if (RefRelationship == Sema::Ref_Incompatible) {
2776 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2777 Kind, Initializer,
2778 /*AllowRValues=*/true,
2779 Sequence);
2780 if (ConvOvlResult)
2781 Sequence.SetOverloadFailure(
2782 InitializationSequence::FK_ReferenceInitOverloadFailed,
2783 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002784
Douglas Gregor20093b42009-12-09 23:02:17 +00002785 return;
2786 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002787
Douglas Gregor20093b42009-12-09 23:02:17 +00002788 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2789 return;
2790 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002791
2792 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00002793 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002794 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00002795 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002796
Douglas Gregor20093b42009-12-09 23:02:17 +00002797 // Determine whether we are allowed to call explicit constructors or
2798 // explicit conversion operators.
2799 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002800
2801 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2802
John McCallf85e1932011-06-15 23:02:42 +00002803 ImplicitConversionSequence ICS
2804 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00002805 /*SuppressUserConversions*/ false,
2806 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002807 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00002808 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2809 /*AllowObjCWritebackConversion=*/false);
2810
2811 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002812 // FIXME: Use the conversion function set stored in ICS to turn
2813 // this into an overloading ambiguity diagnostic. However, we need
2814 // to keep that set as an OverloadCandidateSet rather than as some
2815 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002816 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2817 Sequence.SetOverloadFailure(
2818 InitializationSequence::FK_ReferenceInitOverloadFailed,
2819 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002820 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2821 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002822 else
2823 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002824 return;
John McCallf85e1932011-06-15 23:02:42 +00002825 } else {
2826 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002827 }
2828
2829 // [...] If T1 is reference-related to T2, cv1 must be the
2830 // same cv-qualification as, or greater cv-qualification
2831 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002832 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2833 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002834 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002835 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002836 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2837 return;
2838 }
2839
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002840 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002841 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002842 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002843 InitCategory.isLValue()) {
2844 Sequence.SetFailed(
2845 InitializationSequence::FK_RValueReferenceBindingToLValue);
2846 return;
2847 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848
Douglas Gregor20093b42009-12-09 23:02:17 +00002849 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2850 return;
2851}
2852
2853/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002854/// (C++ [dcl.init.string], C99 6.7.8).
2855static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002856 const InitializedEntity &Entity,
2857 const InitializationKind &Kind,
2858 Expr *Initializer,
2859 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002860 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002861}
2862
Douglas Gregor20093b42009-12-09 23:02:17 +00002863/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2864/// enumerates the constructors of the initialized entity and performs overload
2865/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002866static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002867 const InitializedEntity &Entity,
2868 const InitializationKind &Kind,
2869 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002870 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002871 InitializationSequence &Sequence) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002872 // Build the candidate set directly in the initialization sequence
2873 // structure, so that it will persist if we fail.
2874 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2875 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876
Douglas Gregor51c56d62009-12-14 20:49:26 +00002877 // Determine whether we are allowed to call explicit constructors or
2878 // explicit conversion operators.
2879 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2880 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002881 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002882
2883 // The type we're constructing needs to be complete.
2884 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002885 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002886 return;
2887 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888
Douglas Gregor51c56d62009-12-14 20:49:26 +00002889 // The type we're converting to is a class type. Enumerate its constructors
2890 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002891 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002892 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00002893 CXXRecordDecl *DestRecordDecl
2894 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002895
Douglas Gregor51c56d62009-12-14 20:49:26 +00002896 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002897 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002898 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002899 NamedDecl *D = *Con;
2900 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002901 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002902
Douglas Gregor51c56d62009-12-14 20:49:26 +00002903 // Find the constructor (which may be a template).
2904 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002905 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002906 if (ConstructorTmpl)
2907 Constructor = cast<CXXConstructorDecl>(
2908 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002909 else {
John McCall9aa472c2010-03-19 07:35:19 +00002910 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002911
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002912 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00002913 // suppress user-defined conversions on the arguments.
2914 // FIXME: Move constructors?
2915 if (Kind.getKind() == InitializationKind::IK_Copy &&
2916 Constructor->isCopyConstructor())
2917 SuppressUserConversions = true;
2918 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919
Douglas Gregor51c56d62009-12-14 20:49:26 +00002920 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002921 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002922 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002923 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002924 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002925 Args, NumArgs, CandidateSet,
2926 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002927 else
John McCall9aa472c2010-03-19 07:35:19 +00002928 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002929 Args, NumArgs, CandidateSet,
2930 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002931 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002932 }
2933
Douglas Gregor51c56d62009-12-14 20:49:26 +00002934 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002935
2936 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002937 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002938 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002939 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002940 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002941 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002942 Result);
2943 return;
2944 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002945
2946 // C++0x [dcl.init]p6:
2947 // If a program calls for the default initialization of an object
2948 // of a const-qualified type T, T shall be a class type with a
2949 // user-provided default constructor.
2950 if (Kind.getKind() == InitializationKind::IK_Default &&
2951 Entity.getType().isConstQualified() &&
2952 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2953 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2954 return;
2955 }
2956
Douglas Gregor51c56d62009-12-14 20:49:26 +00002957 // Add the constructor initialization step. Any cv-qualification conversion is
2958 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002959 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002960 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002961 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002962 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002963}
2964
Douglas Gregor71d17402009-12-15 00:01:57 +00002965/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002966static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00002967 const InitializedEntity &Entity,
2968 const InitializationKind &Kind,
2969 InitializationSequence &Sequence) {
2970 // C++ [dcl.init]p5:
2971 //
2972 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002973 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974
Douglas Gregor71d17402009-12-15 00:01:57 +00002975 // -- if T is an array type, then each element is value-initialized;
2976 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2977 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002978
Douglas Gregor71d17402009-12-15 00:01:57 +00002979 if (const RecordType *RT = T->getAs<RecordType>()) {
2980 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2981 // -- if T is a class type (clause 9) with a user-declared
2982 // constructor (12.1), then the default constructor for T is
2983 // called (and the initialization is ill-formed if T has no
2984 // accessible default constructor);
2985 //
2986 // FIXME: we really want to refer to a single subobject of the array,
2987 // but Entity doesn't have a way to capture that (yet).
2988 if (ClassDecl->hasUserDeclaredConstructor())
2989 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002990
Douglas Gregor16006c92009-12-16 18:50:27 +00002991 // -- if T is a (possibly cv-qualified) non-union class type
2992 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002993 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00002994 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002995 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002996 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002997 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002998 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00002999 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003000 }
3001 }
3002
Douglas Gregord6542d82009-12-22 15:35:07 +00003003 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003004}
3005
Douglas Gregor99a2e602009-12-16 01:38:02 +00003006/// \brief Attempt default initialization (C++ [dcl.init]p6).
3007static void TryDefaultInitialization(Sema &S,
3008 const InitializedEntity &Entity,
3009 const InitializationKind &Kind,
3010 InitializationSequence &Sequence) {
3011 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003012
Douglas Gregor99a2e602009-12-16 01:38:02 +00003013 // C++ [dcl.init]p6:
3014 // To default-initialize an object of type T means:
3015 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003016 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3017
Douglas Gregor99a2e602009-12-16 01:38:02 +00003018 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3019 // constructor for T is called (and the initialization is ill-formed if
3020 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003021 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003022 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3023 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003024 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003025
Douglas Gregor99a2e602009-12-16 01:38:02 +00003026 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003027
Douglas Gregor99a2e602009-12-16 01:38:02 +00003028 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003029 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003030 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003031 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003032 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003033 return;
3034 }
3035
3036 // If the destination type has a lifetime property, zero-initialize it.
3037 if (DestType.getQualifiers().hasObjCLifetime()) {
3038 Sequence.AddZeroInitializationStep(Entity.getType());
3039 return;
3040 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003041}
3042
Douglas Gregor20093b42009-12-09 23:02:17 +00003043/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3044/// which enumerates all conversion functions and performs overload resolution
3045/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003047 const InitializedEntity &Entity,
3048 const InitializationKind &Kind,
3049 Expr *Initializer,
3050 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003051 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003052 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3053 QualType SourceType = Initializer->getType();
3054 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3055 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003056
Douglas Gregor4a520a22009-12-14 17:27:33 +00003057 // Build the candidate set directly in the initialization sequence
3058 // structure, so that it will persist if we fail.
3059 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3060 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003061
Douglas Gregor4a520a22009-12-14 17:27:33 +00003062 // Determine whether we are allowed to call explicit constructors or
3063 // explicit conversion operators.
3064 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003065
Douglas Gregor4a520a22009-12-14 17:27:33 +00003066 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3067 // The type we're converting to is a class type. Enumerate its constructors
3068 // to see if there is a suitable conversion.
3069 CXXRecordDecl *DestRecordDecl
3070 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003071
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003072 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003074 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003075 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003076 Con != ConEnd; ++Con) {
3077 NamedDecl *D = *Con;
3078 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003079
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003080 // Find the constructor (which may be a template).
3081 CXXConstructorDecl *Constructor = 0;
3082 FunctionTemplateDecl *ConstructorTmpl
3083 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003084 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003085 Constructor = cast<CXXConstructorDecl>(
3086 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003087 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003088 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003089
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003090 if (!Constructor->isInvalidDecl() &&
3091 Constructor->isConvertingConstructor(AllowExplicit)) {
3092 if (ConstructorTmpl)
3093 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3094 /*ExplicitArgs*/ 0,
3095 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003096 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003097 else
3098 S.AddOverloadCandidate(Constructor, FoundDecl,
3099 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003100 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003101 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003102 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003103 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003104 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003105
3106 SourceLocation DeclLoc = Initializer->getLocStart();
3107
Douglas Gregor4a520a22009-12-14 17:27:33 +00003108 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3109 // The type we're converting from is a class type, enumerate its conversion
3110 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003111
Eli Friedman33c2da92009-12-20 22:12:03 +00003112 // We can only enumerate the conversion functions for a complete type; if
3113 // the type isn't complete, simply skip this step.
3114 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3115 CXXRecordDecl *SourceRecordDecl
3116 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117
John McCalleec51cf2010-01-20 00:46:10 +00003118 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003119 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003120 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003122 I != E; ++I) {
3123 NamedDecl *D = *I;
3124 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3125 if (isa<UsingShadowDecl>(D))
3126 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003127
Eli Friedman33c2da92009-12-20 22:12:03 +00003128 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3129 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003130 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003131 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003132 else
John McCall32daa422010-03-31 01:36:47 +00003133 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003134
Eli Friedman33c2da92009-12-20 22:12:03 +00003135 if (AllowExplicit || !Conv->isExplicit()) {
3136 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003137 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003138 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003139 CandidateSet);
3140 else
John McCall9aa472c2010-03-19 07:35:19 +00003141 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003142 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003143 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003144 }
3145 }
3146 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147
3148 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003149 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003150 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003151 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003152 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003153 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003154 Result);
3155 return;
3156 }
John McCall1d318332010-01-12 00:44:57 +00003157
Douglas Gregor4a520a22009-12-14 17:27:33 +00003158 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003159 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003160
Douglas Gregor4a520a22009-12-14 17:27:33 +00003161 if (isa<CXXConstructorDecl>(Function)) {
3162 // Add the user-defined conversion step. Any cv-qualification conversion is
3163 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003164 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003165 return;
3166 }
3167
3168 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003169 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003170 if (ConvType->getAs<RecordType>()) {
3171 // If we're converting to a class type, there may be an copy if
3172 // the resulting temporary object (possible to create an object of
3173 // a base class type). That copy is not a separate conversion, so
3174 // we just make a note of the actual destination type (possibly a
3175 // base class of the type returned by the conversion function) and
3176 // let the user-defined conversion step handle the conversion.
3177 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3178 return;
3179 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003180
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003181 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003182
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003183 // If the conversion following the call to the conversion function
3184 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003185 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3186 Best->FinalConversion.Third) {
3187 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003188 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003189 ICS.Standard = Best->FinalConversion;
3190 Sequence.AddConversionSequenceStep(ICS, DestType);
3191 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003192}
3193
John McCallf85e1932011-06-15 23:02:42 +00003194/// The non-zero enum values here are indexes into diagnostic alternatives.
3195enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3196
3197/// Determines whether this expression is an acceptable ICR source.
3198static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e) {
3199 // Skip parens.
3200 e = e->IgnoreParens();
3201
3202 // Skip address-of nodes.
3203 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3204 if (op->getOpcode() == UO_AddrOf)
3205 return isInvalidICRSource(C, op->getSubExpr());
3206
3207 // Skip certain casts.
3208 } else if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
3209 switch (cast->getCastKind()) {
3210 case CK_Dependent:
3211 case CK_BitCast:
3212 case CK_LValueBitCast:
3213 case CK_LValueToRValue:
3214 case CK_NoOp:
3215 return isInvalidICRSource(C, cast->getSubExpr());
3216
3217 case CK_ArrayToPointerDecay:
3218 return IIK_nonscalar;
3219
3220 case CK_NullToPointer:
3221 return IIK_okay;
3222
3223 default:
3224 break;
3225 }
3226
3227 // If we have a declaration reference, it had better be a local variable.
3228 } else if (DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(e)) {
3229 if (VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl()))
3230 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
3231
3232 // If we have a conditional operator, check both sides.
3233 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
3234 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS()))
3235 return iik;
3236
3237 return isInvalidICRSource(C, cond->getRHS());
3238
3239 // These are never scalar.
3240 } else if (isa<ArraySubscriptExpr>(e)) {
3241 return IIK_nonscalar;
3242
3243 // Otherwise, it needs to be a null pointer constant.
3244 } else {
3245 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3246 ? IIK_okay : IIK_nonlocal);
3247 }
3248
3249 return IIK_nonlocal;
3250}
3251
3252/// Check whether the given expression is a valid operand for an
3253/// indirect copy/restore.
3254static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3255 assert(src->isRValue());
3256
3257 InvalidICRKind iik = isInvalidICRSource(S.Context, src);
3258 if (iik == IIK_okay) return;
3259
3260 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3261 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3262 << src->getSourceRange();
3263}
3264
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003265/// \brief Determine whether we have compatible array types for the
3266/// purposes of GNU by-copy array initialization.
3267static bool hasCompatibleArrayTypes(ASTContext &Context,
3268 const ArrayType *Dest,
3269 const ArrayType *Source) {
3270 // If the source and destination array types are equivalent, we're
3271 // done.
3272 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3273 return true;
3274
3275 // Make sure that the element types are the same.
3276 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3277 return false;
3278
3279 // The only mismatch we allow is when the destination is an
3280 // incomplete array type and the source is a constant array type.
3281 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3282}
3283
John McCallf85e1932011-06-15 23:02:42 +00003284static bool tryObjCWritebackConversion(Sema &S,
3285 InitializationSequence &Sequence,
3286 const InitializedEntity &Entity,
3287 Expr *Initializer) {
3288 bool ArrayDecay = false;
3289 QualType ArgType = Initializer->getType();
3290 QualType ArgPointee;
3291 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3292 ArrayDecay = true;
3293 ArgPointee = ArgArrayType->getElementType();
3294 ArgType = S.Context.getPointerType(ArgPointee);
3295 }
3296
3297 // Handle write-back conversion.
3298 QualType ConvertedArgType;
3299 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3300 ConvertedArgType))
3301 return false;
3302
3303 // We should copy unless we're passing to an argument explicitly
3304 // marked 'out'.
3305 bool ShouldCopy = true;
3306 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3307 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3308
3309 // Do we need an lvalue conversion?
3310 if (ArrayDecay || Initializer->isGLValue()) {
3311 ImplicitConversionSequence ICS;
3312 ICS.setStandard();
3313 ICS.Standard.setAsIdentityConversion();
3314
3315 QualType ResultType;
3316 if (ArrayDecay) {
3317 ICS.Standard.First = ICK_Array_To_Pointer;
3318 ResultType = S.Context.getPointerType(ArgPointee);
3319 } else {
3320 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3321 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3322 }
3323
3324 Sequence.AddConversionSequenceStep(ICS, ResultType);
3325 }
3326
3327 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3328 return true;
3329}
3330
Douglas Gregor20093b42009-12-09 23:02:17 +00003331InitializationSequence::InitializationSequence(Sema &S,
3332 const InitializedEntity &Entity,
3333 const InitializationKind &Kind,
3334 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003335 unsigned NumArgs)
3336 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003337 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338
Douglas Gregor20093b42009-12-09 23:02:17 +00003339 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003340 // The semantics of initializers are as follows. The destination type is
3341 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003342 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003343 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003344 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003345 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003346
3347 if (DestType->isDependentType() ||
3348 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3349 SequenceKind = DependentSequence;
3350 return;
3351 }
3352
Sebastian Redl7491c492011-06-05 13:59:11 +00003353 // Almost everything is a normal sequence.
3354 setSequenceKind(NormalSequence);
3355
John McCall241d5582010-12-07 22:54:16 +00003356 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003357 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3358 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3359 if (Result.isInvalid()) {
3360 SetFailed(FK_ConversionFromPropertyFailed);
3361 return;
3362 }
3363 Args[I] = Result.take();
3364 }
John McCall241d5582010-12-07 22:54:16 +00003365
Douglas Gregor20093b42009-12-09 23:02:17 +00003366 QualType SourceType;
3367 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003368 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003369 Initializer = Args[0];
3370 if (!isa<InitListExpr>(Initializer))
3371 SourceType = Initializer->getType();
3372 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373
3374 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003375 // list-initialized (8.5.4).
3376 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3377 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003378 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003380
Douglas Gregor20093b42009-12-09 23:02:17 +00003381 // - If the destination type is a reference type, see 8.5.3.
3382 if (DestType->isReferenceType()) {
3383 // C++0x [dcl.init.ref]p1:
3384 // A variable declared to be a T& or T&&, that is, "reference to type T"
3385 // (8.3.2), shall be initialized by an object, or function, of type T or
3386 // by an object that can be converted into a T.
3387 // (Therefore, multiple arguments are not permitted.)
3388 if (NumArgs != 1)
3389 SetFailed(FK_TooManyInitsForReference);
3390 else
3391 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3392 return;
3393 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003394
Douglas Gregor20093b42009-12-09 23:02:17 +00003395 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003396 if (Kind.getKind() == InitializationKind::IK_Value ||
3397 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003398 TryValueInitialization(S, Entity, Kind, *this);
3399 return;
3400 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401
Douglas Gregor99a2e602009-12-16 01:38:02 +00003402 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003403 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003404 TryDefaultInitialization(S, Entity, Kind, *this);
3405 return;
3406 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003407
John McCallce6c9b72011-02-21 07:22:22 +00003408 // - If the destination type is an array of characters, an array of
3409 // char16_t, an array of char32_t, or an array of wchar_t, and the
3410 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003411 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003412 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003413 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3414 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCallce6c9b72011-02-21 07:22:22 +00003415 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3416 return;
3417 }
3418
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003419 // Note: as an GNU C extension, we allow initialization of an
3420 // array from a compound literal that creates an array of the same
3421 // type, so long as the initializer has no side effects.
3422 if (!S.getLangOptions().CPlusPlus && Initializer &&
3423 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3424 Initializer->getType()->isArrayType()) {
3425 const ArrayType *SourceAT
3426 = Context.getAsArrayType(Initializer->getType());
3427 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3428 SetFailed(FK_ArrayTypeMismatch);
3429 else if (Initializer->HasSideEffects(S.Context))
3430 SetFailed(FK_NonConstantArrayInit);
3431 else {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003432 AddArrayInitStep(DestType);
3433 }
3434 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor20093b42009-12-09 23:02:17 +00003435 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3436 else
3437 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003438
Douglas Gregor20093b42009-12-09 23:02:17 +00003439 return;
3440 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003441
John McCallf85e1932011-06-15 23:02:42 +00003442 // Determine whether we should consider writeback conversions for
3443 // Objective-C ARC.
3444 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3445 Entity.getKind() == InitializedEntity::EK_Parameter;
3446
3447 // We're at the end of the line for C: it's either a write-back conversion
3448 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003449 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003450 // If allowed, check whether this is an Objective-C writeback conversion.
3451 if (allowObjCWritebackConversion &&
3452 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
3453 return;
3454 }
3455
3456 // Handle initialization in C
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003457 AddCAssignmentStep(DestType);
John McCallf85e1932011-06-15 23:02:42 +00003458 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003459 return;
3460 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003461
John McCallf85e1932011-06-15 23:02:42 +00003462 assert(S.getLangOptions().CPlusPlus);
3463
Douglas Gregor20093b42009-12-09 23:02:17 +00003464 // - If the destination type is a (possibly cv-qualified) class type:
3465 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003466 // - If the initialization is direct-initialization, or if it is
3467 // copy-initialization where the cv-unqualified version of the
3468 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003469 // class of the destination, constructors are considered. [...]
3470 if (Kind.getKind() == InitializationKind::IK_Direct ||
3471 (Kind.getKind() == InitializationKind::IK_Copy &&
3472 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3473 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003474 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003475 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003476 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003477 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003479 // used) to a derived class thereof are enumerated as described in
3480 // 13.3.1.4, and the best one is chosen through overload resolution
3481 // (13.3).
3482 else
3483 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3484 return;
3485 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486
Douglas Gregor99a2e602009-12-16 01:38:02 +00003487 if (NumArgs > 1) {
3488 SetFailed(FK_TooManyInitsForScalar);
3489 return;
3490 }
3491 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003492
3493 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003494 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003495 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003496 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
John McCallf85e1932011-06-15 23:02:42 +00003497 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003498 return;
3499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500
Douglas Gregor20093b42009-12-09 23:02:17 +00003501 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003502 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003503 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003505 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003506
3507 ImplicitConversionSequence ICS
3508 = S.TryImplicitConversion(Initializer, Entity.getType(),
3509 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003510 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003511 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003512 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3513 allowObjCWritebackConversion);
3514
3515 if (ICS.isStandard() &&
3516 ICS.Standard.Second == ICK_Writeback_Conversion) {
3517 // Objective-C ARC writeback conversion.
3518
3519 // We should copy unless we're passing to an argument explicitly
3520 // marked 'out'.
3521 bool ShouldCopy = true;
3522 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3523 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3524
3525 // If there was an lvalue adjustment, add it as a separate conversion.
3526 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3527 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3528 ImplicitConversionSequence LvalueICS;
3529 LvalueICS.setStandard();
3530 LvalueICS.Standard.setAsIdentityConversion();
3531 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3532 LvalueICS.Standard.First = ICS.Standard.First;
3533 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
3534 }
3535
3536 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3537 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003538 DeclAccessPair dap;
3539 if (Initializer->getType() == Context.OverloadTy &&
3540 !S.ResolveAddressOfOverloadedFunction(Initializer
3541 , DestType, false, dap))
Douglas Gregor8e960432010-11-08 03:40:48 +00003542 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3543 else
3544 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003545 } else {
3546 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003547
3548 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003549 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003550}
3551
3552InitializationSequence::~InitializationSequence() {
3553 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3554 StepEnd = Steps.end();
3555 Step != StepEnd; ++Step)
3556 Step->Destroy();
3557}
3558
3559//===----------------------------------------------------------------------===//
3560// Perform initialization
3561//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003562static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003563getAssignmentAction(const InitializedEntity &Entity) {
3564 switch(Entity.getKind()) {
3565 case InitializedEntity::EK_Variable:
3566 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003567 case InitializedEntity::EK_Exception:
3568 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003569 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003570 return Sema::AA_Initializing;
3571
3572 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003573 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003574 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3575 return Sema::AA_Sending;
3576
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003577 return Sema::AA_Passing;
3578
3579 case InitializedEntity::EK_Result:
3580 return Sema::AA_Returning;
3581
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003582 case InitializedEntity::EK_Temporary:
3583 // FIXME: Can we tell apart casting vs. converting?
3584 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003585
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003586 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003587 case InitializedEntity::EK_ArrayElement:
3588 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003589 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003590 return Sema::AA_Initializing;
3591 }
3592
3593 return Sema::AA_Converting;
3594}
3595
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003596/// \brief Whether we should binding a created object as a temporary when
3597/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003598static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003599 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003600 case InitializedEntity::EK_ArrayElement:
3601 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003602 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003603 case InitializedEntity::EK_New:
3604 case InitializedEntity::EK_Variable:
3605 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003606 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003607 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003608 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003609 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003610 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003611
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003612 case InitializedEntity::EK_Parameter:
3613 case InitializedEntity::EK_Temporary:
3614 return true;
3615 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003616
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003617 llvm_unreachable("missed an InitializedEntity kind?");
3618}
3619
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003620/// \brief Whether the given entity, when initialized with an object
3621/// created for that initialization, requires destruction.
3622static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3623 switch (Entity.getKind()) {
3624 case InitializedEntity::EK_Member:
3625 case InitializedEntity::EK_Result:
3626 case InitializedEntity::EK_New:
3627 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003628 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003629 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003630 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003631 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003632
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003633 case InitializedEntity::EK_Variable:
3634 case InitializedEntity::EK_Parameter:
3635 case InitializedEntity::EK_Temporary:
3636 case InitializedEntity::EK_ArrayElement:
3637 case InitializedEntity::EK_Exception:
3638 return true;
3639 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003640
3641 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003642}
3643
Douglas Gregor523d46a2010-04-18 07:40:54 +00003644/// \brief Make a (potentially elidable) temporary copy of the object
3645/// provided by the given initializer by calling the appropriate copy
3646/// constructor.
3647///
3648/// \param S The Sema object used for type-checking.
3649///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003650/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003651/// the type of the initializer expression or a superclass thereof.
3652///
3653/// \param Enter The entity being initialized.
3654///
3655/// \param CurInit The initializer expression.
3656///
3657/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3658/// is permitted in C++03 (but not C++0x) when binding a reference to
3659/// an rvalue.
3660///
3661/// \returns An expression that copies the initializer expression into
3662/// a temporary object, or an error expression if a copy could not be
3663/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003664static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003665 QualType T,
3666 const InitializedEntity &Entity,
3667 ExprResult CurInit,
3668 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003669 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003670 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003671 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003672 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003673 Class = cast<CXXRecordDecl>(Record->getDecl());
3674 if (!Class)
3675 return move(CurInit);
3676
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003677 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003678 // When certain criteria are met, an implementation is allowed to
3679 // omit the copy/move construction of a class object, even if the
3680 // copy/move constructor and/or destructor for the object have
3681 // side effects. [...]
3682 // - when a temporary class object that has not been bound to a
3683 // reference (12.2) would be copied/moved to a class object
3684 // with the same cv-unqualified type, the copy/move operation
3685 // can be omitted by constructing the temporary object
3686 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003687 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003688 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003689 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003690 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003691 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003692 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003693 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003694 switch (Entity.getKind()) {
3695 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003696 Loc = Entity.getReturnLoc();
3697 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003699 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003700 Loc = Entity.getThrowLoc();
3701 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003702
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003703 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003704 Loc = Entity.getDecl()->getLocation();
3705 break;
3706
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003707 case InitializedEntity::EK_ArrayElement:
3708 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003709 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003710 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003711 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003712 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003713 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003714 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003715 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003716 Loc = CurInitExpr->getLocStart();
3717 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003718 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003719
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003720 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003721 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3722 return move(CurInit);
3723
Douglas Gregorcc15f012011-01-21 19:38:21 +00003724 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003725 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003726 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003727 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003728 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003729 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003730 // C++0x [dcl.init]p16, second bullet to class types, this
3731 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003732 CXXConstructorDecl *Constructor = 0;
3733
3734 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003735 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003736 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003737 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003738 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003739 continue;
3740
3741 DeclAccessPair FoundDecl
3742 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3743 S.AddOverloadCandidate(Constructor, FoundDecl,
3744 &CurInitExpr, 1, CandidateSet);
3745 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003746 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003747
3748 // Handle constructor templates.
3749 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3750 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003751 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003752
Douglas Gregor6493cc52010-11-08 17:16:59 +00003753 Constructor = cast<CXXConstructorDecl>(
3754 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003755 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003756 continue;
3757
3758 // FIXME: Do we need to limit this to copy-constructor-like
3759 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003760 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003761 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3762 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3763 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003764 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003766 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003767 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003768 case OR_Success:
3769 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003771 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003772 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3773 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3774 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003775 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003776 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003777 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003778 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003779 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003780 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003781
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003782 case OR_Ambiguous:
3783 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003784 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003785 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003786 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003787 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003789 case OR_Deleted:
3790 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003791 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003792 << CurInitExpr->getSourceRange();
3793 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00003794 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003795 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003796 }
3797
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003798 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003799 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003800 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003801
Anders Carlsson9a68a672010-04-21 18:47:17 +00003802 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003803 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003804
3805 if (IsExtraneousCopy) {
3806 // If this is a totally extraneous copy for C++03 reference
3807 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003808 // expression. We don't generate an (elided) copy operation here
3809 // because doing so would require us to pass down a flag to avoid
3810 // infinite recursion, where each step adds another extraneous,
3811 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003812
Douglas Gregor2559a702010-04-18 07:57:34 +00003813 // Instantiate the default arguments of any extra parameters in
3814 // the selected copy constructor, as if we were going to create a
3815 // proper call to the copy constructor.
3816 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3817 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3818 if (S.RequireCompleteType(Loc, Parm->getType(),
3819 S.PDiag(diag::err_call_incomplete_argument)))
3820 break;
3821
3822 // Build the default argument expression; we don't actually care
3823 // if this succeeds or not, because this routine will complain
3824 // if there was a problem.
3825 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3826 }
3827
Douglas Gregor523d46a2010-04-18 07:40:54 +00003828 return S.Owned(CurInitExpr);
3829 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003830
Chandler Carruth25ca4212011-02-25 19:41:05 +00003831 S.MarkDeclarationReferenced(Loc, Constructor);
3832
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003833 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003834 // constructor call (we might have derived-to-base conversions, or
3835 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003836 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003837 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003838 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003839
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003840 // Actually perform the constructor call.
3841 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003842 move_arg(ConstructorArgs),
3843 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003844 CXXConstructExpr::CK_Complete,
3845 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003847 // If we're supposed to bind temporaries, do so.
3848 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3849 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3850 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003851}
Douglas Gregor20093b42009-12-09 23:02:17 +00003852
Douglas Gregora41a8c52010-04-22 00:20:18 +00003853void InitializationSequence::PrintInitLocationNote(Sema &S,
3854 const InitializedEntity &Entity) {
3855 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3856 if (Entity.getDecl()->getLocation().isInvalid())
3857 return;
3858
3859 if (Entity.getDecl()->getDeclName())
3860 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3861 << Entity.getDecl()->getDeclName();
3862 else
3863 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3864 }
3865}
3866
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003867ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003868InitializationSequence::Perform(Sema &S,
3869 const InitializedEntity &Entity,
3870 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003871 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003872 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00003873 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003874 unsigned NumArgs = Args.size();
3875 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003876 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003877 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003878
Sebastian Redl7491c492011-06-05 13:59:11 +00003879 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003880 // If the declaration is a non-dependent, incomplete array type
3881 // that has an initializer, then its type will be completed once
3882 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003883 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003884 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003885 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003886 if (const IncompleteArrayType *ArrayT
3887 = S.Context.getAsIncompleteArrayType(DeclType)) {
3888 // FIXME: We don't currently have the ability to accurately
3889 // compute the length of an initializer list without
3890 // performing full type-checking of the initializer list
3891 // (since we have to determine where braces are implicitly
3892 // introduced and such). So, we fall back to making the array
3893 // type a dependently-sized array type with no specified
3894 // bound.
3895 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3896 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003897
Douglas Gregord87b61f2009-12-10 17:56:55 +00003898 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003899 if (DeclaratorDecl *DD = Entity.getDecl()) {
3900 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3901 TypeLoc TL = TInfo->getTypeLoc();
3902 if (IncompleteArrayTypeLoc *ArrayLoc
3903 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3904 Brackets = ArrayLoc->getBracketsRange();
3905 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003906 }
3907
3908 *ResultType
3909 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3910 /*NumElts=*/0,
3911 ArrayT->getSizeModifier(),
3912 ArrayT->getIndexTypeCVRQualifiers(),
3913 Brackets);
3914 }
3915
3916 }
3917 }
3918
Eli Friedman08544622009-12-22 02:35:53 +00003919 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003920 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003921
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003922 if (Args.size() == 0)
3923 return S.Owned((Expr *)0);
3924
Douglas Gregor20093b42009-12-09 23:02:17 +00003925 unsigned NumArgs = Args.size();
3926 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3927 SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928 (Expr **)Args.release(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003929 NumArgs,
3930 SourceLocation()));
3931 }
3932
Sebastian Redl7491c492011-06-05 13:59:11 +00003933 // No steps means no initialization.
3934 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00003935 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003936
Douglas Gregord6542d82009-12-22 15:35:07 +00003937 QualType DestType = Entity.getType().getNonReferenceType();
3938 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003939 // the same as Entity.getDecl()->getType() in cases involving type merging,
3940 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003941 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003942 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003943 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003944
John McCall60d7b3a2010-08-24 06:29:42 +00003945 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003946
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003947 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00003948 // grab the only argument out the Args and place it into the "current"
3949 // initializer.
3950 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003951 case SK_ResolveAddressOfOverloadedFunction:
3952 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003953 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003954 case SK_CastDerivedToBaseLValue:
3955 case SK_BindReference:
3956 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003957 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003958 case SK_UserConversion:
3959 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003960 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003961 case SK_QualificationConversionRValue:
3962 case SK_ConversionSequence:
3963 case SK_ListInitialization:
3964 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003965 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003966 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00003967 case SK_ArrayInit:
3968 case SK_PassByIndirectCopyRestore:
3969 case SK_PassByIndirectRestore:
3970 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003971 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00003972 CurInit = Args.get()[0];
3973 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003974
3975 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00003976 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3977 CurInit = S.ConvertPropertyForRValue(CurInit.take());
3978 if (CurInit.isInvalid())
3979 return ExprError();
3980 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003981 break;
John McCallf6a16482010-12-04 03:47:34 +00003982 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003984 case SK_ConstructorInitialization:
3985 case SK_ZeroInitialization:
3986 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003987 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003988
3989 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00003990 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003991 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003992 for (step_iterator Step = step_begin(), StepEnd = step_end();
3993 Step != StepEnd; ++Step) {
3994 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003995 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003996
John Wiegley429bb272011-04-08 18:41:53 +00003997 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003998
Douglas Gregor20093b42009-12-09 23:02:17 +00003999 switch (Step->Kind) {
4000 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004002 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004003 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004004 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004005 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004006 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004007 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004008 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004009
Douglas Gregor20093b42009-12-09 23:02:17 +00004010 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004011 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004012 case SK_CastDerivedToBaseLValue: {
4013 // We have a derived-to-base cast that produces either an rvalue or an
4014 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004015
John McCallf871d0c2010-08-07 06:22:56 +00004016 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004017
Douglas Gregor20093b42009-12-09 23:02:17 +00004018 // Casts to inaccessible base classes are allowed with C-style casts.
4019 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4020 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004021 CurInit.get()->getLocStart(),
4022 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004023 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004024 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004025
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004026 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4027 QualType T = SourceType;
4028 if (const PointerType *Pointer = T->getAs<PointerType>())
4029 T = Pointer->getPointeeType();
4030 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004031 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004032 cast<CXXRecordDecl>(RecordTy->getDecl()));
4033 }
4034
John McCall5baba9d2010-08-25 10:28:54 +00004035 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004036 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004037 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004038 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004039 VK_XValue :
4040 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004041 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4042 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004043 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004044 CurInit.get(),
4045 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004046 break;
4047 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004048
Douglas Gregor20093b42009-12-09 23:02:17 +00004049 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004050 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004051 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4052 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004053 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004054 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004055 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004056 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004057 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004058 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004059
John Wiegley429bb272011-04-08 18:41:53 +00004060 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004061 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004062 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4063 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004064 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004065 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004066 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004067 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004068
Douglas Gregor20093b42009-12-09 23:02:17 +00004069 // Reference binding does not have any corresponding ASTs.
4070
4071 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004072 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004073 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004074
Douglas Gregor20093b42009-12-09 23:02:17 +00004075 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004076
Douglas Gregor20093b42009-12-09 23:02:17 +00004077 case SK_BindReferenceToTemporary:
4078 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004079 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004080 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004081
Douglas Gregor03e80032011-06-21 17:03:29 +00004082 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004083 CurInit = new (S.Context) MaterializeTemporaryExpr(
4084 Entity.getType().getNonReferenceType(),
4085 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004086 Entity.getType()->isLValueReferenceType());
Douglas Gregor20093b42009-12-09 23:02:17 +00004087 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004088
Douglas Gregor523d46a2010-04-18 07:40:54 +00004089 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004090 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004091 /*IsExtraneousCopy=*/true);
4092 break;
4093
Douglas Gregor20093b42009-12-09 23:02:17 +00004094 case SK_UserConversion: {
4095 // We have a user-defined conversion that invokes either a constructor
4096 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004097 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004098 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004099 FunctionDecl *Fn = Step->Function.Function;
4100 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004101 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004102 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004103 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004104 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004105 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004106 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004107 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004108
Douglas Gregor20093b42009-12-09 23:02:17 +00004109 // Determine the arguments required to actually perform the constructor
4110 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004111 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004112 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004113 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004114 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004115 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116
Douglas Gregor20093b42009-12-09 23:02:17 +00004117 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004118 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004119 move_arg(ConstructorArgs),
4120 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004121 CXXConstructExpr::CK_Complete,
4122 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004123 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004124 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004125
Anders Carlsson9a68a672010-04-21 18:47:17 +00004126 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004127 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004128 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004129
John McCall2de56d12010-08-25 11:45:40 +00004130 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004131 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4132 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4133 S.IsDerivedFrom(SourceType, Class))
4134 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004135
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004136 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004137 } else {
4138 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004139 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004140 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004141 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004142 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004143 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144
4145 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004146 // derived-to-base conversion? I believe the answer is "no", because
4147 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004148 ExprResult CurInitExprRes =
4149 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4150 FoundFn, Conversion);
4151 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004152 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004153 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004154
Douglas Gregor20093b42009-12-09 23:02:17 +00004155 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004156 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004157 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004158 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004159
John McCall2de56d12010-08-25 11:45:40 +00004160 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004161
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004162 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004164
4165 bool RequiresCopy = !IsCopy &&
Douglas Gregor2f599792010-04-02 18:24:57 +00004166 getKind() != InitializationSequence::ReferenceBinding;
4167 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004168 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004169 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004170 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004171 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004172 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004173 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004174 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004175 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004176 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4177 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004178 }
4179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004180
Sebastian Redl906082e2010-07-20 04:20:21 +00004181 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004182 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004183 CurInit.get()->getType(),
4184 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004185 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004186
Douglas Gregor2f599792010-04-02 18:24:57 +00004187 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004188 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4189 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004190
Douglas Gregor20093b42009-12-09 23:02:17 +00004191 break;
4192 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004193
Douglas Gregor20093b42009-12-09 23:02:17 +00004194 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004195 case SK_QualificationConversionXValue:
4196 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004197 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004198 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004199 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004200 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004201 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004202 VK_XValue :
4203 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004204 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004205 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004206 }
4207
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004208 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004209 Sema::CheckedConversionKind CCK
4210 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4211 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4212 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4213 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004214 ExprResult CurInitExprRes =
4215 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004216 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004217 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004218 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004219 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004220 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004221 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004222
Douglas Gregord87b61f2009-12-10 17:56:55 +00004223 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004224 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004225 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00004226 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00004227 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004228
4229 CurInit.release();
4230 CurInit = S.Owned(InitList);
4231 break;
4232 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004233
4234 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004235 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004236 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004237 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004238
Douglas Gregor51c56d62009-12-14 20:49:26 +00004239 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004240 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004241 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4242 ? Kind.getEqualLoc()
4243 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004244
4245 if (Kind.getKind() == InitializationKind::IK_Default) {
4246 // Force even a trivial, implicit default constructor to be
4247 // semantically checked. We do this explicitly because we don't build
4248 // the definition for completely trivial constructors.
4249 CXXRecordDecl *ClassDecl = Constructor->getParent();
4250 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004251 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004252 ClassDecl->hasTrivialDefaultConstructor() &&
4253 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004254 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4255 }
4256
Douglas Gregor51c56d62009-12-14 20:49:26 +00004257 // Determine the arguments required to actually perform the constructor
4258 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004259 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004260 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004261 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004262
4263
Douglas Gregor91be6f52010-03-02 17:18:33 +00004264 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004265 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004266 (Kind.getKind() == InitializationKind::IK_Direct ||
4267 Kind.getKind() == InitializationKind::IK_Value)) {
4268 // An explicitly-constructed temporary, e.g., X(1, 2).
4269 unsigned NumExprs = ConstructorArgs.size();
4270 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004271 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004272 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004273
Douglas Gregorab6677e2010-09-08 00:15:04 +00004274 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4275 if (!TSInfo)
4276 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004277
Douglas Gregor91be6f52010-03-02 17:18:33 +00004278 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4279 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004280 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004281 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004282 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004283 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004284 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004285 } else {
4286 CXXConstructExpr::ConstructionKind ConstructKind =
4287 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004288
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004289 if (Entity.getKind() == InitializedEntity::EK_Base) {
4290 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004291 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004292 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004293 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004294 ConstructKind = CXXConstructExpr::CK_Delegating;
4295 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004296
Chandler Carruth428edaf2010-10-25 08:47:36 +00004297 // Only get the parenthesis range if it is a direct construction.
4298 SourceRange parenRange =
4299 Kind.getKind() == InitializationKind::IK_Direct ?
4300 Kind.getParenRange() : SourceRange();
4301
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004302 // If the entity allows NRVO, mark the construction as elidable
4303 // unconditionally.
4304 if (Entity.allowsNRVO())
4305 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4306 Constructor, /*Elidable=*/true,
4307 move_arg(ConstructorArgs),
4308 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004309 ConstructKind,
4310 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004311 else
4312 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004313 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004314 move_arg(ConstructorArgs),
4315 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004316 ConstructKind,
4317 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004318 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004319 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004320 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004321
4322 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004323 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004324 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004325 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004326
Douglas Gregor2f599792010-04-02 18:24:57 +00004327 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004328 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004329
Douglas Gregor51c56d62009-12-14 20:49:26 +00004330 break;
4331 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004332
Douglas Gregor71d17402009-12-15 00:01:57 +00004333 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004334 step_iterator NextStep = Step;
4335 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004336 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004337 NextStep->Kind == SK_ConstructorInitialization) {
4338 // The need for zero-initialization is recorded directly into
4339 // the call to the object's constructor within the next step.
4340 ConstructorInitRequiresZeroInit = true;
4341 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4342 S.getLangOptions().CPlusPlus &&
4343 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004344 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4345 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004346 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004347 Kind.getRange().getBegin());
4348
4349 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4350 TSInfo->getType().getNonLValueExprType(S.Context),
4351 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004352 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004353 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004354 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004355 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004356 break;
4357 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004358
4359 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004360 QualType SourceType = CurInit.get()->getType();
4361 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004362 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004363 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4364 if (Result.isInvalid())
4365 return ExprError();
4366 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004367
4368 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004369 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004370 if (ConvTy != Sema::Compatible &&
4371 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004372 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004373 == Sema::Compatible)
4374 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004375 if (CurInitExprRes.isInvalid())
4376 return ExprError();
4377 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004378
Douglas Gregora41a8c52010-04-22 00:20:18 +00004379 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004380 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4381 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004382 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004383 getAssignmentAction(Entity),
4384 &Complained)) {
4385 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004386 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004387 } else if (Complained)
4388 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004389 break;
4390 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004391
4392 case SK_StringInit: {
4393 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004394 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004395 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004396 break;
4397 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004398
4399 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004400 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004401 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004402 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004403 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004404
4405 case SK_ArrayInit:
4406 // Okay: we checked everything before creating this step. Note that
4407 // this is a GNU extension.
4408 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004409 << Step->Type << CurInit.get()->getType()
4410 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004411
4412 // If the destination type is an incomplete array type, update the
4413 // type accordingly.
4414 if (ResultType) {
4415 if (const IncompleteArrayType *IncompleteDest
4416 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4417 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004418 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004419 *ResultType = S.Context.getConstantArrayType(
4420 IncompleteDest->getElementType(),
4421 ConstantSource->getSize(),
4422 ArrayType::Normal, 0);
4423 }
4424 }
4425 }
John McCallf85e1932011-06-15 23:02:42 +00004426 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004427
John McCallf85e1932011-06-15 23:02:42 +00004428 case SK_PassByIndirectCopyRestore:
4429 case SK_PassByIndirectRestore:
4430 checkIndirectCopyRestoreSource(S, CurInit.get());
4431 CurInit = S.Owned(new (S.Context)
4432 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4433 Step->Kind == SK_PassByIndirectCopyRestore));
4434 break;
4435
4436 case SK_ProduceObjCObject:
4437 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4438 CK_ObjCProduceObject,
4439 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004440 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004441 }
4442 }
John McCall15d7d122010-11-11 03:21:53 +00004443
4444 // Diagnose non-fatal problems with the completed initialization.
4445 if (Entity.getKind() == InitializedEntity::EK_Member &&
4446 cast<FieldDecl>(Entity.getDecl())->isBitField())
4447 S.CheckBitFieldInitialization(Kind.getLocation(),
4448 cast<FieldDecl>(Entity.getDecl()),
4449 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004450
Douglas Gregor20093b42009-12-09 23:02:17 +00004451 return move(CurInit);
4452}
4453
4454//===----------------------------------------------------------------------===//
4455// Diagnose initialization failures
4456//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004458 const InitializedEntity &Entity,
4459 const InitializationKind &Kind,
4460 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004461 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004462 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004463
Douglas Gregord6542d82009-12-22 15:35:07 +00004464 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004465 switch (Failure) {
4466 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004467 // FIXME: Customize for the initialized entity?
4468 if (NumArgs == 0)
4469 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4470 << DestType.getNonReferenceType();
4471 else // FIXME: diagnostic below could be better!
4472 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4473 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004474 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475
Douglas Gregor20093b42009-12-09 23:02:17 +00004476 case FK_ArrayNeedsInitList:
4477 case FK_ArrayNeedsInitListOrStringLiteral:
4478 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4479 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4480 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004481
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004482 case FK_ArrayTypeMismatch:
4483 case FK_NonConstantArrayInit:
4484 S.Diag(Kind.getLocation(),
4485 (Failure == FK_ArrayTypeMismatch
4486 ? diag::err_array_init_different_type
4487 : diag::err_array_init_non_constant_array))
4488 << DestType.getNonReferenceType()
4489 << Args[0]->getType()
4490 << Args[0]->getSourceRange();
4491 break;
4492
John McCall6bb80172010-03-30 21:47:33 +00004493 case FK_AddressOfOverloadFailed: {
4494 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004495 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004496 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004497 true,
4498 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004499 break;
John McCall6bb80172010-03-30 21:47:33 +00004500 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004501
Douglas Gregor20093b42009-12-09 23:02:17 +00004502 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004503 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004504 switch (FailedOverloadResult) {
4505 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004506 if (Failure == FK_UserConversionOverloadFailed)
4507 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4508 << Args[0]->getType() << DestType
4509 << Args[0]->getSourceRange();
4510 else
4511 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4512 << DestType << Args[0]->getType()
4513 << Args[0]->getSourceRange();
4514
John McCall120d63c2010-08-24 20:38:10 +00004515 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004516 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004517
Douglas Gregor20093b42009-12-09 23:02:17 +00004518 case OR_No_Viable_Function:
4519 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4520 << Args[0]->getType() << DestType.getNonReferenceType()
4521 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004522 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004523 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004524
Douglas Gregor20093b42009-12-09 23:02:17 +00004525 case OR_Deleted: {
4526 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4527 << Args[0]->getType() << DestType.getNonReferenceType()
4528 << Args[0]->getSourceRange();
4529 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004530 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004531 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4532 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004533 if (Ovl == OR_Deleted) {
4534 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004535 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004536 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004537 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004538 }
4539 break;
4540 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004541
Douglas Gregor20093b42009-12-09 23:02:17 +00004542 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004543 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004544 break;
4545 }
4546 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004547
Douglas Gregor20093b42009-12-09 23:02:17 +00004548 case FK_NonConstLValueReferenceBindingToTemporary:
4549 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004550 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004551 Failure == FK_NonConstLValueReferenceBindingToTemporary
4552 ? diag::err_lvalue_reference_bind_to_temporary
4553 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004554 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004555 << DestType.getNonReferenceType()
4556 << Args[0]->getType()
4557 << Args[0]->getSourceRange();
4558 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004559
Douglas Gregor20093b42009-12-09 23:02:17 +00004560 case FK_RValueReferenceBindingToLValue:
4561 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004562 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004563 << Args[0]->getSourceRange();
4564 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565
Douglas Gregor20093b42009-12-09 23:02:17 +00004566 case FK_ReferenceInitDropsQualifiers:
4567 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4568 << DestType.getNonReferenceType()
4569 << Args[0]->getType()
4570 << Args[0]->getSourceRange();
4571 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004572
Douglas Gregor20093b42009-12-09 23:02:17 +00004573 case FK_ReferenceInitFailed:
4574 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4575 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004576 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004577 << Args[0]->getType()
4578 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004579 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4580 Args[0]->getType()->isObjCObjectPointerType())
4581 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004582 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004583
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004584 case FK_ConversionFailed: {
4585 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004586 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4587 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004588 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004589 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004590 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004591 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004592 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4593 Args[0]->getType()->isObjCObjectPointerType())
4594 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004595 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004596 }
John Wiegley429bb272011-04-08 18:41:53 +00004597
4598 case FK_ConversionFromPropertyFailed:
4599 // No-op. This error has already been reported.
4600 break;
4601
Douglas Gregord87b61f2009-12-10 17:56:55 +00004602 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004603 SourceRange R;
4604
4605 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004606 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004607 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004608 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004609 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004610
Douglas Gregor19311e72010-09-08 21:40:08 +00004611 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4612 if (Kind.isCStyleOrFunctionalCast())
4613 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4614 << R;
4615 else
4616 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4617 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004618 break;
4619 }
4620
4621 case FK_ReferenceBindingToInitList:
4622 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4623 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4624 break;
4625
4626 case FK_InitListBadDestinationType:
4627 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4628 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4629 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004630
Douglas Gregor51c56d62009-12-14 20:49:26 +00004631 case FK_ConstructorOverloadFailed: {
4632 SourceRange ArgsRange;
4633 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004635 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004636
Douglas Gregor51c56d62009-12-14 20:49:26 +00004637 // FIXME: Using "DestType" for the entity we're printing is probably
4638 // bad.
4639 switch (FailedOverloadResult) {
4640 case OR_Ambiguous:
4641 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4642 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004643 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4644 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004645 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004646
Douglas Gregor51c56d62009-12-14 20:49:26 +00004647 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004648 if (Kind.getKind() == InitializationKind::IK_Default &&
4649 (Entity.getKind() == InitializedEntity::EK_Base ||
4650 Entity.getKind() == InitializedEntity::EK_Member) &&
4651 isa<CXXConstructorDecl>(S.CurContext)) {
4652 // This is implicit default initialization of a member or
4653 // base within a constructor. If no viable function was
4654 // found, notify the user that she needs to explicitly
4655 // initialize this base/member.
4656 CXXConstructorDecl *Constructor
4657 = cast<CXXConstructorDecl>(S.CurContext);
4658 if (Entity.getKind() == InitializedEntity::EK_Base) {
4659 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4660 << Constructor->isImplicit()
4661 << S.Context.getTypeDeclType(Constructor->getParent())
4662 << /*base=*/0
4663 << Entity.getType();
4664
4665 RecordDecl *BaseDecl
4666 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4667 ->getDecl();
4668 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4669 << S.Context.getTagDeclType(BaseDecl);
4670 } else {
4671 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4672 << Constructor->isImplicit()
4673 << S.Context.getTypeDeclType(Constructor->getParent())
4674 << /*member=*/1
4675 << Entity.getName();
4676 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4677
4678 if (const RecordType *Record
4679 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004680 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004681 diag::note_previous_decl)
4682 << S.Context.getTagDeclType(Record->getDecl());
4683 }
4684 break;
4685 }
4686
Douglas Gregor51c56d62009-12-14 20:49:26 +00004687 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4688 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004689 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004690 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004691
Douglas Gregor51c56d62009-12-14 20:49:26 +00004692 case OR_Deleted: {
4693 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4694 << true << DestType << ArgsRange;
4695 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004696 OverloadingResult Ovl
4697 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004698 if (Ovl == OR_Deleted) {
4699 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004700 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004701 } else {
4702 llvm_unreachable("Inconsistent overload resolution?");
4703 }
4704 break;
4705 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004706
Douglas Gregor51c56d62009-12-14 20:49:26 +00004707 case OR_Success:
4708 llvm_unreachable("Conversion did not fail!");
4709 break;
4710 }
4711 break;
4712 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004713
Douglas Gregor99a2e602009-12-16 01:38:02 +00004714 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004715 if (Entity.getKind() == InitializedEntity::EK_Member &&
4716 isa<CXXConstructorDecl>(S.CurContext)) {
4717 // This is implicit default-initialization of a const member in
4718 // a constructor. Complain that it needs to be explicitly
4719 // initialized.
4720 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4721 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4722 << Constructor->isImplicit()
4723 << S.Context.getTypeDeclType(Constructor->getParent())
4724 << /*const=*/1
4725 << Entity.getName();
4726 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4727 << Entity.getName();
4728 } else {
4729 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4730 << DestType << (bool)DestType->getAs<RecordType>();
4731 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004732 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004733
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004734 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004735 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004736 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004737 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004739
Douglas Gregora41a8c52010-04-22 00:20:18 +00004740 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004741 return true;
4742}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004743
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004744void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4745 switch (SequenceKind) {
4746 case FailedSequence: {
4747 OS << "Failed sequence: ";
4748 switch (Failure) {
4749 case FK_TooManyInitsForReference:
4750 OS << "too many initializers for reference";
4751 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004752
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004753 case FK_ArrayNeedsInitList:
4754 OS << "array requires initializer list";
4755 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004756
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004757 case FK_ArrayNeedsInitListOrStringLiteral:
4758 OS << "array requires initializer list or string literal";
4759 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004760
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004761 case FK_ArrayTypeMismatch:
4762 OS << "array type mismatch";
4763 break;
4764
4765 case FK_NonConstantArrayInit:
4766 OS << "non-constant array initializer";
4767 break;
4768
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004769 case FK_AddressOfOverloadFailed:
4770 OS << "address of overloaded function failed";
4771 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004772
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004773 case FK_ReferenceInitOverloadFailed:
4774 OS << "overload resolution for reference initialization failed";
4775 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004776
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004777 case FK_NonConstLValueReferenceBindingToTemporary:
4778 OS << "non-const lvalue reference bound to temporary";
4779 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004780
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004781 case FK_NonConstLValueReferenceBindingToUnrelated:
4782 OS << "non-const lvalue reference bound to unrelated type";
4783 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004784
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004785 case FK_RValueReferenceBindingToLValue:
4786 OS << "rvalue reference bound to an lvalue";
4787 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004788
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004789 case FK_ReferenceInitDropsQualifiers:
4790 OS << "reference initialization drops qualifiers";
4791 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004792
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004793 case FK_ReferenceInitFailed:
4794 OS << "reference initialization failed";
4795 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004796
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004797 case FK_ConversionFailed:
4798 OS << "conversion failed";
4799 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004800
John Wiegley429bb272011-04-08 18:41:53 +00004801 case FK_ConversionFromPropertyFailed:
4802 OS << "conversion from property failed";
4803 break;
4804
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004805 case FK_TooManyInitsForScalar:
4806 OS << "too many initializers for scalar";
4807 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004808
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004809 case FK_ReferenceBindingToInitList:
4810 OS << "referencing binding to initializer list";
4811 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004812
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004813 case FK_InitListBadDestinationType:
4814 OS << "initializer list for non-aggregate, non-scalar type";
4815 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004816
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004817 case FK_UserConversionOverloadFailed:
4818 OS << "overloading failed for user-defined conversion";
4819 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004820
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004821 case FK_ConstructorOverloadFailed:
4822 OS << "constructor overloading failed";
4823 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004824
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004825 case FK_DefaultInitOfConst:
4826 OS << "default initialization of a const variable";
4827 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004828
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004829 case FK_Incomplete:
4830 OS << "initialization of incomplete type";
4831 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004832 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004833 OS << '\n';
4834 return;
4835 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004836
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004837 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00004838 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004839 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004840
Sebastian Redl7491c492011-06-05 13:59:11 +00004841 case NormalSequence:
4842 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004843 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004844
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004845 case ReferenceBinding:
4846 OS << "Reference binding: ";
4847 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004848 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004849
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004850 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4851 if (S != step_begin()) {
4852 OS << " -> ";
4853 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004854
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004855 switch (S->Kind) {
4856 case SK_ResolveAddressOfOverloadedFunction:
4857 OS << "resolve address of overloaded function";
4858 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004859
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004860 case SK_CastDerivedToBaseRValue:
4861 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4862 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004863
Sebastian Redl906082e2010-07-20 04:20:21 +00004864 case SK_CastDerivedToBaseXValue:
4865 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4866 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004867
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004868 case SK_CastDerivedToBaseLValue:
4869 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4870 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004871
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004872 case SK_BindReference:
4873 OS << "bind reference to lvalue";
4874 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004875
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004876 case SK_BindReferenceToTemporary:
4877 OS << "bind reference to a temporary";
4878 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004879
Douglas Gregor523d46a2010-04-18 07:40:54 +00004880 case SK_ExtraneousCopyToTemporary:
4881 OS << "extraneous C++03 copy to temporary";
4882 break;
4883
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004884 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004885 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004886 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004887
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004888 case SK_QualificationConversionRValue:
4889 OS << "qualification conversion (rvalue)";
4890
Sebastian Redl906082e2010-07-20 04:20:21 +00004891 case SK_QualificationConversionXValue:
4892 OS << "qualification conversion (xvalue)";
4893
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004894 case SK_QualificationConversionLValue:
4895 OS << "qualification conversion (lvalue)";
4896 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004897
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004898 case SK_ConversionSequence:
4899 OS << "implicit conversion sequence (";
4900 S->ICS->DebugPrint(); // FIXME: use OS
4901 OS << ")";
4902 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004903
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004904 case SK_ListInitialization:
4905 OS << "list initialization";
4906 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004907
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004908 case SK_ConstructorInitialization:
4909 OS << "constructor initialization";
4910 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004911
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004912 case SK_ZeroInitialization:
4913 OS << "zero initialization";
4914 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004915
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004916 case SK_CAssignment:
4917 OS << "C assignment";
4918 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004919
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004920 case SK_StringInit:
4921 OS << "string initialization";
4922 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004923
4924 case SK_ObjCObjectConversion:
4925 OS << "Objective-C object conversion";
4926 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004927
4928 case SK_ArrayInit:
4929 OS << "array initialization";
4930 break;
John McCallf85e1932011-06-15 23:02:42 +00004931
4932 case SK_PassByIndirectCopyRestore:
4933 OS << "pass by indirect copy and restore";
4934 break;
4935
4936 case SK_PassByIndirectRestore:
4937 OS << "pass by indirect restore";
4938 break;
4939
4940 case SK_ProduceObjCObject:
4941 OS << "Objective-C object retension";
4942 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004943 }
4944 }
4945}
4946
4947void InitializationSequence::dump() const {
4948 dump(llvm::errs());
4949}
4950
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004951//===----------------------------------------------------------------------===//
4952// Initialization helper functions
4953//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00004954bool
4955Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
4956 ExprResult Init) {
4957 if (Init.isInvalid())
4958 return false;
4959
4960 Expr *InitE = Init.get();
4961 assert(InitE && "No initialization expression");
4962
4963 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
4964 SourceLocation());
4965 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00004966 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00004967}
4968
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004969ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004970Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4971 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004972 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004973 if (Init.isInvalid())
4974 return ExprError();
4975
John McCall15d7d122010-11-11 03:21:53 +00004976 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004977 assert(InitE && "No initialization expression?");
4978
4979 if (EqualLoc.isInvalid())
4980 EqualLoc = InitE->getLocStart();
4981
4982 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4983 EqualLoc);
4984 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4985 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004986 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004987}