blob: c406ad9840531dd0d61a76cc4c3f9c0591f014b3 [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//
Rafael Espindola12ce0a02011-07-14 22:58:04 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000013//
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"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000101 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedman8718a6a2009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Eli Friedman8718a6a2009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137}
138
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregor9e80f722009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000170namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 bool hadError;
174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000180 unsigned &StructuredIndex,
181 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000182 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000183 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000199 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000200 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000201 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000204 void CheckReferenceType(const InitializedEntity &Entity,
205 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000206 unsigned &Index,
207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000210 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000213 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000214 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000215 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000216 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000218 unsigned &StructuredIndex,
219 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000220 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000221 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000222 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000223 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000224 InitListExpr *StructuredList,
225 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000226 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000227 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000228 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000229 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000230 RecordDecl::field_iterator *NextField,
231 llvm::APSInt *NextElementIndex,
232 unsigned &Index,
233 InitListExpr *StructuredList,
234 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000235 bool FinishSubobjectInit,
236 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000237 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
238 QualType CurrentObjectType,
239 InitListExpr *StructuredList,
240 unsigned StructuredIndex,
241 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000242 void UpdateStructuredListElement(InitListExpr *StructuredList,
243 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000244 Expr *expr);
245 int numArrayElements(QualType DeclType);
246 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000247
Douglas Gregord6d37de2009-12-22 00:05:34 +0000248 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
249 const InitializedEntity &ParentEntity,
250 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000251 void FillInValueInitializations(const InitializedEntity &Entity,
252 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000253public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000254 InitListChecker(Sema &S, const InitializedEntity &Entity,
255 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000256 bool HadError() { return hadError; }
257
258 // @brief Retrieves the fully-structured initializer list used for
259 // semantic analysis and code generation.
260 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
261};
Chris Lattner8b419b92009-02-24 22:48:58 +0000262} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000263
Douglas Gregord6d37de2009-12-22 00:05:34 +0000264void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
265 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000266 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000267 bool &RequiresSecondPass) {
268 SourceLocation Loc = ILE->getSourceRange().getBegin();
269 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000270 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000271 = InitializedEntity::InitializeMember(Field, &ParentEntity);
272 if (Init >= NumInits || !ILE->getInit(Init)) {
273 // FIXME: We probably don't need to handle references
274 // specially here, since value-initialization of references is
275 // handled in InitializationSequence.
276 if (Field->getType()->isReferenceType()) {
277 // C++ [dcl.init.aggr]p9:
278 // If an incomplete or empty initializer-list leaves a
279 // member of reference type uninitialized, the program is
280 // ill-formed.
281 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
282 << Field->getType()
283 << ILE->getSyntacticForm()->getSourceRange();
284 SemaRef.Diag(Field->getLocation(),
285 diag::note_uninit_reference_member);
286 hadError = true;
287 return;
288 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000289
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
291 true);
292 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
293 if (!InitSeq) {
294 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
295 hadError = true;
296 return;
297 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000298
John McCall60d7b3a2010-08-24 06:29:42 +0000299 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000300 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000301 if (MemberInit.isInvalid()) {
302 hadError = true;
303 return;
304 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000305
Douglas Gregord6d37de2009-12-22 00:05:34 +0000306 if (hadError) {
307 // Do nothing
308 } else if (Init < NumInits) {
309 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000310 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000311 // Value-initialization requires a constructor call, so
312 // extend the initializer list to include the constructor
313 // call and make a note that we'll need to take another pass
314 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000315 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000316 RequiresSecondPass = true;
317 }
318 } else if (InitListExpr *InnerILE
319 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000320 FillInValueInitializations(MemberEntity, InnerILE,
321 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322}
323
Douglas Gregor4c678342009-01-28 21:54:33 +0000324/// Recursively replaces NULL values within the given initializer list
325/// with expressions that perform value-initialization of the
326/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
329 InitListExpr *ILE,
330 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000331 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000332 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000333 SourceLocation Loc = ILE->getSourceRange().getBegin();
334 if (ILE->getSyntacticForm())
335 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremenek6217b802009-07-29 21:53:49 +0000337 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000338 if (RType->getDecl()->isUnion() &&
339 ILE->getInitializedFieldInUnion())
340 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
341 Entity, ILE, RequiresSecondPass);
342 else {
343 unsigned Init = 0;
344 for (RecordDecl::field_iterator
345 Field = RType->getDecl()->field_begin(),
346 FieldEnd = RType->getDecl()->field_end();
347 Field != FieldEnd; ++Field) {
348 if (Field->isUnnamedBitfield())
349 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000350
Douglas Gregord6d37de2009-12-22 00:05:34 +0000351 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000352 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000353
354 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
355 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000357
Douglas Gregord6d37de2009-12-22 00:05:34 +0000358 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000359
Douglas Gregord6d37de2009-12-22 00:05:34 +0000360 // Only look at the first initialization of a union.
361 if (RType->getDecl()->isUnion())
362 break;
363 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000364 }
365
366 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000367 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000368
369 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000371 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 unsigned NumInits = ILE->getNumInits();
373 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000374 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000375 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000376 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
377 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000378 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000379 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000380 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000383 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000384 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000385 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000386 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000387
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000388
Douglas Gregor87fd7032009-02-02 17:43:21 +0000389 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000390 if (hadError)
391 return;
392
Anders Carlssond3d824d2010-01-23 04:34:47 +0000393 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
394 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 ElementEntity.setElementIndex(Init);
396
Douglas Gregor87fd7032009-02-02 17:43:21 +0000397 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
399 true);
400 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
401 if (!InitSeq) {
402 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 hadError = true;
404 return;
405 }
406
John McCall60d7b3a2010-08-24 06:29:42 +0000407 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000408 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000409 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000410 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000411 return;
412 }
413
414 if (hadError) {
415 // Do nothing
416 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000417 // For arrays, just set the expression used for value-initialization
418 // of the "holes" in the array.
419 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
420 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
421 else
422 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000423 } else {
424 // For arrays, just set the expression used for value-initialization
425 // of the rest of elements and exit.
426 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
427 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
428 return;
429 }
430
Sebastian Redl7491c492011-06-05 13:59:11 +0000431 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000432 // Value-initialization requires a constructor call, so
433 // extend the initializer list to include the constructor
434 // call and make a note that we'll need to take another pass
435 // through the initializer list.
436 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
437 RequiresSecondPass = true;
438 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000439 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000440 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000441 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
442 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000443 }
444}
445
Chris Lattner68355a52009-01-29 05:10:57 +0000446
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000447InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
448 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000449 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000450 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000451
Eli Friedmanb85f7072008-05-19 19:16:24 +0000452 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000453 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000454 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000455 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000456 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000457 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000458 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000459
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000460 if (!hadError) {
461 bool RequiresSecondPass = false;
462 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000463 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000464 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000465 RequiresSecondPass);
466 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000467}
468
469int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000470 // FIXME: use a proper constant
471 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000472 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000473 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000474 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
475 }
476 return maxElements;
477}
478
479int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000480 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000482 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000483 Field = structDecl->field_begin(),
484 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000485 Field != FieldEnd; ++Field) {
486 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
487 ++InitializableMembers;
488 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000489 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000490 return std::min(InitializableMembers, 1);
491 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000492}
493
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000494void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000495 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000496 QualType T, unsigned &Index,
497 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000498 unsigned &StructuredIndex,
499 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000500 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Steve Naroff0cca7492008-05-01 22:18:59 +0000502 if (T->isArrayType())
503 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000504 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000505 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000506 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000507 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000508 else
509 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000510
Eli Friedman402256f2008-05-25 13:49:22 +0000511 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000512 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000513 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000515 hadError = true;
516 return;
517 }
518
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 // Build a structured initializer list corresponding to this subobject.
520 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000521 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
522 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000523 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
524 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000525 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000526
Douglas Gregor4c678342009-01-28 21:54:33 +0000527 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000528 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000529 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000530 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000531 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000532 StructuredSubobjectInitIndex,
533 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000534 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000535 StructuredSubobjectInitList->setType(T);
536
Douglas Gregored8a93d2009-03-01 17:12:46 +0000537 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000538 // range corresponds with the end of the last initializer it used.
539 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000540 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000541 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
542 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000545 // Warn about missing braces.
546 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000547 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
548 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000549 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000551 "{")
552 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000554 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000555 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000556}
557
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000558void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000559 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000560 unsigned &Index,
561 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000562 unsigned &StructuredIndex,
563 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000564 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000565 SyntacticToSemantic[IList] = StructuredList;
566 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000568 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000569 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
570 IList->setType(ExprTy);
571 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000572 if (hadError)
573 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000574
Eli Friedman638e1442008-05-25 13:22:35 +0000575 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000576 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000577 if (StructuredIndex == 1 &&
578 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000579 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000580 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000581 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000582 hadError = true;
583 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000584 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000585 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000586 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000587 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000588 // Don't complain for incomplete types, since we'll get an error
589 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000590 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000591 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000592 CurrentObjectType->isArrayType()? 0 :
593 CurrentObjectType->isVectorType()? 1 :
594 CurrentObjectType->isScalarType()? 2 :
595 CurrentObjectType->isUnionType()? 3 :
596 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000597
598 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000599 if (SemaRef.getLangOptions().CPlusPlus) {
600 DK = diag::err_excess_initializers;
601 hadError = true;
602 }
Nate Begeman08634522009-07-07 21:53:06 +0000603 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
604 DK = diag::err_excess_initializers;
605 hadError = true;
606 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000607
Chris Lattner08202542009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000609 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000610 }
611 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000612
Eli Friedman759f2522009-05-16 11:45:48 +0000613 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000614 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000615 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000616 << FixItHint::CreateRemoval(IList->getLocStart())
617 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000618}
619
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000620void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000621 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000622 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000623 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000624 unsigned &Index,
625 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000626 unsigned &StructuredIndex,
627 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000628 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000629 CheckScalarType(Entity, IList, DeclType, Index,
630 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000631 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000632 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000633 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000634 } else if (DeclType->isAggregateType()) {
635 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000636 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000637 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 StructuredList, StructuredIndex,
640 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000641 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000642 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000643 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000644 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000645 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000646 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000648 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000650 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
651 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000652 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000653 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000654 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000655 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000656 } else if (DeclType->isRecordType()) {
657 // C++ [dcl.init]p14:
658 // [...] If the class is an aggregate (8.5.1), and the initializer
659 // is a brace-enclosed list, see 8.5.1.
660 //
661 // Note: 8.5.1 is handled below; here, we diagnose the case where
662 // we have an initializer list and a destination type that is not
663 // an aggregate.
664 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000666 << DeclType << IList->getSourceRange();
667 hadError = true;
668 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000669 CheckReferenceType(Entity, IList, DeclType, Index,
670 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000671 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000672 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
673 << DeclType;
674 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000675 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000676 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
677 << DeclType;
678 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000679 }
680}
681
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000682void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000683 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000684 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000685 unsigned &Index,
686 InitListExpr *StructuredList,
687 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000688 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000689 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
690 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000692 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000693 = getStructuredSubobjectInit(IList, Index, ElemType,
694 StructuredList, StructuredIndex,
695 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000696 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000697 newStructuredList, newStructuredIndex);
698 ++StructuredIndex;
699 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000700 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000701 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000702 return CheckScalarType(Entity, IList, ElemType, Index,
703 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000704 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000705 return CheckReferenceType(Entity, IList, ElemType, Index,
706 StructuredList, StructuredIndex);
707 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000708
John McCallfef8b342011-02-21 07:57:55 +0000709 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
710 // arrayType can be incomplete if we're initializing a flexible
711 // array member. There's nothing we can do with the completed
712 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000713
John McCallfef8b342011-02-21 07:57:55 +0000714 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
715 CheckStringInit(Str, ElemType, arrayType, SemaRef);
716 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000717 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000718 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000719 }
John McCallfef8b342011-02-21 07:57:55 +0000720
721 // Fall through for subaggregate initialization.
722
723 } else if (SemaRef.getLangOptions().CPlusPlus) {
724 // C++ [dcl.init.aggr]p12:
725 // All implicit type conversions (clause 4) are considered when
Rafael Espindola12ce0a02011-07-14 22:58:04 +0000726 // initializing the aggregate member with an ini- tializer from
John McCallfef8b342011-02-21 07:57:55 +0000727 // an initializer-list. If the initializer can initialize a
728 // member, the member is initialized. [...]
729
730 // FIXME: Better EqualLoc?
731 InitializationKind Kind =
732 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
733 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
734
735 if (Seq) {
736 ExprResult Result =
737 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
738 if (Result.isInvalid())
739 hadError = true;
740
741 UpdateStructuredListElement(StructuredList, StructuredIndex,
742 Result.takeAs<Expr>());
743 ++Index;
744 return;
745 }
746
747 // Fall through for subaggregate initialization
748 } else {
749 // C99 6.7.8p13:
750 //
751 // The initializer for a structure or union object that has
752 // automatic storage duration shall be either an initializer
753 // list as described below, or a single expression that has
754 // compatible structure or union type. In the latter case, the
755 // initial value of the object, including unnamed members, is
756 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000757 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000758 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley429bb272011-04-08 18:41:53 +0000759 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCallfef8b342011-02-21 07:57:55 +0000760 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000761 if (ExprRes.isInvalid())
762 hadError = true;
763 else {
764 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
765 if (ExprRes.isInvalid())
766 hadError = true;
767 }
768 UpdateStructuredListElement(StructuredList, StructuredIndex,
769 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000770 ++Index;
771 return;
772 }
John Wiegley429bb272011-04-08 18:41:53 +0000773 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000774 // Fall through for subaggregate initialization
775 }
776
777 // C++ [dcl.init.aggr]p12:
778 //
779 // [...] Otherwise, if the member is itself a non-empty
780 // subaggregate, brace elision is assumed and the initializer is
781 // considered for the initialization of the first member of
782 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000783 if (!SemaRef.getLangOptions().OpenCL &&
784 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000785 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
786 StructuredIndex);
787 ++StructuredIndex;
788 } else {
789 // We cannot initialize this element, so let
790 // PerformCopyInitialization produce the appropriate diagnostic.
791 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000792 SemaRef.Owned(expr),
793 /*TopLevelOfInitList=*/true);
John McCallfef8b342011-02-21 07:57:55 +0000794 hadError = true;
795 ++Index;
796 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000797 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000798}
799
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000800void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000801 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000802 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000803 InitListExpr *StructuredList,
804 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000805 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000806 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000807 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000808 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000809 ++Index;
810 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000811 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000812 }
John McCallb934c2d2010-11-11 00:46:36 +0000813
814 Expr *expr = IList->getInit(Index);
815 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
816 SemaRef.Diag(SubIList->getLocStart(),
817 diag::warn_many_braces_around_scalar_init)
818 << SubIList->getSourceRange();
819
820 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
821 StructuredIndex);
822 return;
823 } else if (isa<DesignatedInitExpr>(expr)) {
824 SemaRef.Diag(expr->getSourceRange().getBegin(),
825 diag::err_designator_for_scalar_init)
826 << DeclType << expr->getSourceRange();
827 hadError = true;
828 ++Index;
829 ++StructuredIndex;
830 return;
831 }
832
833 ExprResult Result =
834 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000835 SemaRef.Owned(expr),
836 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000837
838 Expr *ResultExpr = 0;
839
840 if (Result.isInvalid())
841 hadError = true; // types weren't compatible.
842 else {
843 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000844
John McCallb934c2d2010-11-11 00:46:36 +0000845 if (ResultExpr != expr) {
846 // The type was promoted, update initializer list.
847 IList->setInit(Index, ResultExpr);
848 }
849 }
850 if (hadError)
851 ++StructuredIndex;
852 else
853 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
854 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000855}
856
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000857void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
858 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000859 unsigned &Index,
860 InitListExpr *StructuredList,
861 unsigned &StructuredIndex) {
862 if (Index < IList->getNumInits()) {
863 Expr *expr = IList->getInit(Index);
864 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000865 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000866 << DeclType << IList->getSourceRange();
867 hadError = true;
868 ++Index;
869 ++StructuredIndex;
870 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000871 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000872
John McCall60d7b3a2010-08-24 06:29:42 +0000873 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000874 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000875 SemaRef.Owned(expr),
876 /*TopLevelOfInitList=*/true);
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000877
878 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000879 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000880
881 expr = Result.takeAs<Expr>();
882 IList->setInit(Index, expr);
883
Douglas Gregor930d8b52009-01-30 22:09:00 +0000884 if (hadError)
885 ++StructuredIndex;
886 else
887 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
888 ++Index;
889 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000890 // FIXME: It would be wonderful if we could point at the actual member. In
891 // general, it would be useful to pass location information down the stack,
892 // so that we know the location (or decl) of the "current object" being
893 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000894 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000895 diag::err_init_reference_member_uninitialized)
896 << DeclType
897 << IList->getSourceRange();
898 hadError = true;
899 ++Index;
900 ++StructuredIndex;
901 return;
902 }
903}
904
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000905void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000906 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000907 unsigned &Index,
908 InitListExpr *StructuredList,
909 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000910 if (Index >= IList->getNumInits())
911 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000912
John McCall20e047a2010-10-30 00:11:39 +0000913 const VectorType *VT = DeclType->getAs<VectorType>();
914 unsigned maxElements = VT->getNumElements();
915 unsigned numEltsInit = 0;
916 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000917
John McCall20e047a2010-10-30 00:11:39 +0000918 if (!SemaRef.getLangOptions().OpenCL) {
919 // If the initializing element is a vector, try to copy-initialize
920 // instead of breaking it apart (which is doomed to failure anyway).
921 Expr *Init = IList->getInit(Index);
922 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
923 ExprResult Result =
924 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000925 SemaRef.Owned(Init),
926 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +0000927
928 Expr *ResultExpr = 0;
929 if (Result.isInvalid())
930 hadError = true; // types weren't compatible.
931 else {
932 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933
John McCall20e047a2010-10-30 00:11:39 +0000934 if (ResultExpr != Init) {
935 // The type was promoted, update initializer list.
936 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000937 }
938 }
John McCall20e047a2010-10-30 00:11:39 +0000939 if (hadError)
940 ++StructuredIndex;
941 else
942 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
943 ++Index;
944 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
John McCall20e047a2010-10-30 00:11:39 +0000947 InitializedEntity ElementEntity =
948 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949
John McCall20e047a2010-10-30 00:11:39 +0000950 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
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 CheckSubElementType(ElementEntity, IList, elementType, Index,
957 StructuredList, StructuredIndex);
958 }
959 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000960 }
John McCall20e047a2010-10-30 00:11:39 +0000961
962 InitializedEntity ElementEntity =
963 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000964
John McCall20e047a2010-10-30 00:11:39 +0000965 // OpenCL initializers allows vectors to be constructed from vectors.
966 for (unsigned i = 0; i < maxElements; ++i) {
967 // Don't attempt to go past the end of the init list
968 if (Index >= IList->getNumInits())
969 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000970
John McCall20e047a2010-10-30 00:11:39 +0000971 ElementEntity.setElementIndex(Index);
972
973 QualType IType = IList->getInit(Index)->getType();
974 if (!IType->isVectorType()) {
975 CheckSubElementType(ElementEntity, IList, elementType, Index,
976 StructuredList, StructuredIndex);
977 ++numEltsInit;
978 } else {
979 QualType VecType;
980 const VectorType *IVT = IType->getAs<VectorType>();
981 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982
John McCall20e047a2010-10-30 00:11:39 +0000983 if (IType->isExtVectorType())
984 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
985 else
986 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000987 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000988 CheckSubElementType(ElementEntity, IList, VecType, Index,
989 StructuredList, StructuredIndex);
990 numEltsInit += numIElts;
991 }
992 }
993
994 // OpenCL requires all elements to be initialized.
995 if (numEltsInit != maxElements)
996 if (SemaRef.getLangOptions().OpenCL)
997 SemaRef.Diag(IList->getSourceRange().getBegin(),
998 diag::err_vector_incorrect_num_initializers)
999 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001000}
1001
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001002void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001003 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001004 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001005 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001006 unsigned &Index,
1007 InitListExpr *StructuredList,
1008 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001009 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1010
Steve Naroff0cca7492008-05-01 22:18:59 +00001011 // Check for the special-case of initializing an array with a string.
1012 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001013 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001014 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +00001015 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001016 // We place the string literal directly into the resulting
1017 // initializer list. This is the only place where the structure
1018 // of the structured initializer list doesn't match exactly,
1019 // because doing so would involve allocating one character
1020 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001021 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001022 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001023 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001024 return;
1025 }
1026 }
John McCallce6c9b72011-02-21 07:22:22 +00001027 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001028 // Check for VLAs; in standard C it would be possible to check this
1029 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1030 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001031 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001032 diag::err_variable_object_no_init)
1033 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001034 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001035 ++Index;
1036 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001037 return;
1038 }
1039
Douglas Gregor05c13a32009-01-22 00:58:24 +00001040 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001041 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1042 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001043 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001044 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001045 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001046 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001047 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001048 maxElementsKnown = true;
1049 }
1050
John McCallce6c9b72011-02-21 07:22:22 +00001051 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001052 while (Index < IList->getNumInits()) {
1053 Expr *Init = IList->getInit(Index);
1054 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001055 // If we're not the subobject that matches up with the '{' for
1056 // the designator, we shouldn't be handling the
1057 // designator. Return immediately.
1058 if (!SubobjectIsDesignatorContext)
1059 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001060
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001061 // Handle this designated initializer. elementIndex will be
1062 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001063 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001064 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001065 StructuredList, StructuredIndex, true,
1066 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001067 hadError = true;
1068 continue;
1069 }
1070
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001071 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001072 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001073 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001074 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001075 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001076
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001077 // If the array is of incomplete type, keep track of the number of
1078 // elements in the initializer.
1079 if (!maxElementsKnown && elementIndex > maxElements)
1080 maxElements = elementIndex;
1081
Douglas Gregor05c13a32009-01-22 00:58:24 +00001082 continue;
1083 }
1084
1085 // If we know the maximum number of elements, and we've already
1086 // hit it, stop consuming elements in the initializer list.
1087 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001088 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001089
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001090 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001091 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001092 Entity);
1093 // Check this element.
1094 CheckSubElementType(ElementEntity, IList, elementType, Index,
1095 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001096 ++elementIndex;
1097
1098 // If the array is of incomplete type, keep track of the number of
1099 // elements in the initializer.
1100 if (!maxElementsKnown && elementIndex > maxElements)
1101 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001102 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001103 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001104 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001105 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001106 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001107 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001108 // Sizing an array implicitly to zero is not allowed by ISO C,
1109 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001110 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001111 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001112 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001113
Mike Stump1eb44332009-09-09 15:08:12 +00001114 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001115 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001116 }
1117}
1118
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001119void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001120 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001121 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001122 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001123 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001124 unsigned &Index,
1125 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001126 unsigned &StructuredIndex,
1127 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001128 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Eli Friedmanb85f7072008-05-19 19:16:24 +00001130 // If the record is invalid, some of it's members are invalid. To avoid
1131 // confusion, we forgo checking the intializer for the entire record.
1132 if (structDecl->isInvalidDecl()) {
1133 hadError = true;
1134 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001135 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001136
1137 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1138 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001139 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001140 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001141 Field != FieldEnd; ++Field) {
1142 if (Field->getDeclName()) {
1143 StructuredList->setInitializedFieldInUnion(*Field);
1144 break;
1145 }
1146 }
1147 return;
1148 }
1149
Douglas Gregor05c13a32009-01-22 00:58:24 +00001150 // If structDecl is a forward declaration, this loop won't do
1151 // anything except look at designated initializers; That's okay,
1152 // because an error should get printed out elsewhere. It might be
1153 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001154 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001155 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001156 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001157 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001158 while (Index < IList->getNumInits()) {
1159 Expr *Init = IList->getInit(Index);
1160
1161 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001162 // If we're not the subobject that matches up with the '{' for
1163 // the designator, we shouldn't be handling the
1164 // designator. Return immediately.
1165 if (!SubobjectIsDesignatorContext)
1166 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001167
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001168 // Handle this designated initializer. Field will be updated to
1169 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001170 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001171 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001172 StructuredList, StructuredIndex,
1173 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 hadError = true;
1175
Douglas Gregordfb5e592009-02-12 19:00:39 +00001176 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001177
1178 // Disable check for missing fields when designators are used.
1179 // This matches gcc behaviour.
1180 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001181 continue;
1182 }
1183
1184 if (Field == FieldEnd) {
1185 // We've run out of fields. We're done.
1186 break;
1187 }
1188
Douglas Gregordfb5e592009-02-12 19:00:39 +00001189 // We've already initialized a member of a union. We're done.
1190 if (InitializedSomething && DeclType->isUnionType())
1191 break;
1192
Douglas Gregor44b43212008-12-11 16:49:14 +00001193 // If we've hit the flexible array member at the end, we're done.
1194 if (Field->getType()->isIncompleteArrayType())
1195 break;
1196
Douglas Gregor0bb76892009-01-29 16:53:55 +00001197 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001198 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001199 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001200 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001201 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001202
Douglas Gregor54001c12011-06-29 21:51:31 +00001203 // Make sure we can use this declaration.
1204 if (SemaRef.DiagnoseUseOfDecl(*Field,
1205 IList->getInit(Index)->getLocStart())) {
1206 ++Index;
1207 ++Field;
1208 hadError = true;
1209 continue;
1210 }
1211
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001212 InitializedEntity MemberEntity =
1213 InitializedEntity::InitializeMember(*Field, &Entity);
1214 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1215 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001216 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001217
1218 if (DeclType->isUnionType()) {
1219 // Initialize the first field within the union.
1220 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001221 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001222
1223 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001224 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001225
John McCall80639de2010-03-11 19:32:38 +00001226 // Emit warnings for missing struct field initializers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001227 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001228 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1229 // It is possible we have one or more unnamed bitfields remaining.
1230 // Find first (if any) named field and emit warning.
1231 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1232 it != end; ++it) {
1233 if (!it->isUnnamedBitfield()) {
1234 SemaRef.Diag(IList->getSourceRange().getEnd(),
1235 diag::warn_missing_field_initializers) << it->getName();
1236 break;
1237 }
1238 }
1239 }
1240
Mike Stump1eb44332009-09-09 15:08:12 +00001241 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001242 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001243 return;
1244
1245 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001246 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001247 (!isa<InitListExpr>(IList->getInit(Index)) ||
1248 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001249 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001250 diag::err_flexible_array_init_nonempty)
1251 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001252 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001253 << *Field;
1254 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001255 ++Index;
1256 return;
1257 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001258 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001259 diag::ext_flexible_array_init)
1260 << IList->getInit(Index)->getSourceRange().getBegin();
1261 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1262 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001263 }
1264
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001265 InitializedEntity MemberEntity =
1266 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001268 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001269 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001270 StructuredList, StructuredIndex);
1271 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001272 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001273 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001274}
Steve Naroff0cca7492008-05-01 22:18:59 +00001275
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001276/// \brief Expand a field designator that refers to a member of an
1277/// anonymous struct or union into a series of field designators that
1278/// refers to the field within the appropriate subobject.
1279///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001280static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001281 DesignatedInitExpr *DIE,
1282 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001283 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001284 typedef DesignatedInitExpr::Designator Designator;
1285
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001286 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001287 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001288 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1289 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1290 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001291 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001292 DIE->getDesignator(DesigIdx)->getDotLoc(),
1293 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1294 else
1295 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1296 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001297 assert(isa<FieldDecl>(*PI));
1298 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001299 }
1300
1301 // Expand the current designator into the set of replacement
1302 // designators, so we have a full subobject path down to where the
1303 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001304 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001305 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001306}
Mike Stump1eb44332009-09-09 15:08:12 +00001307
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001308/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001309/// corresponds to FieldName.
1310static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1311 IdentifierInfo *FieldName) {
1312 assert(AnonField->isAnonymousStructOrUnion());
1313 Decl *NextDecl = AnonField->getNextDeclInContext();
1314 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1315 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1316 return IF;
1317 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001318 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001319 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001320}
1321
Douglas Gregor05c13a32009-01-22 00:58:24 +00001322/// @brief Check the well-formedness of a C99 designated initializer.
1323///
1324/// Determines whether the designated initializer @p DIE, which
1325/// resides at the given @p Index within the initializer list @p
1326/// IList, is well-formed for a current object of type @p DeclType
1327/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001328/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001329/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001330///
1331/// @param IList The initializer list in which this designated
1332/// initializer occurs.
1333///
Douglas Gregor71199712009-04-15 04:56:10 +00001334/// @param DIE The designated initializer expression.
1335///
1336/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001337///
1338/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1339/// into which the designation in @p DIE should refer.
1340///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001341/// @param NextField If non-NULL and the first designator in @p DIE is
1342/// a field, this will be set to the field declaration corresponding
1343/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001344///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001345/// @param NextElementIndex If non-NULL and the first designator in @p
1346/// DIE is an array designator or GNU array-range designator, this
1347/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001348///
1349/// @param Index Index into @p IList where the designated initializer
1350/// @p DIE occurs.
1351///
Douglas Gregor4c678342009-01-28 21:54:33 +00001352/// @param StructuredList The initializer list expression that
1353/// describes all of the subobject initializers in the order they'll
1354/// actually be initialized.
1355///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001356/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001357bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001358InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001359 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001360 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001361 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001362 QualType &CurrentObjectType,
1363 RecordDecl::field_iterator *NextField,
1364 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001365 unsigned &Index,
1366 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001367 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001368 bool FinishSubobjectInit,
1369 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001370 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001371 // Check the actual initialization for the designated object type.
1372 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001373
1374 // Temporarily remove the designator expression from the
1375 // initializer list that the child calls see, so that we don't try
1376 // to re-process the designator.
1377 unsigned OldIndex = Index;
1378 IList->setInit(OldIndex, DIE->getInit());
1379
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001380 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001381 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001382
1383 // Restore the designated initializer expression in the syntactic
1384 // form of the initializer list.
1385 if (IList->getInit(OldIndex) != DIE->getInit())
1386 DIE->setInit(IList->getInit(OldIndex));
1387 IList->setInit(OldIndex, DIE);
1388
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001389 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001390 }
1391
Douglas Gregor71199712009-04-15 04:56:10 +00001392 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001393 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001394 "Need a non-designated initializer list to start from");
1395
Douglas Gregor71199712009-04-15 04:56:10 +00001396 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001397 // Determine the structural initializer list that corresponds to the
1398 // current subobject.
1399 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001400 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001401 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001402 SourceRange(D->getStartLocation(),
1403 DIE->getSourceRange().getEnd()));
1404 assert(StructuredList && "Expected a structured initializer list");
1405
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 if (D->isFieldDesignator()) {
1407 // C99 6.7.8p7:
1408 //
1409 // If a designator has the form
1410 //
1411 // . identifier
1412 //
1413 // then the current object (defined below) shall have
1414 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001415 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001416 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001417 if (!RT) {
1418 SourceLocation Loc = D->getDotLoc();
1419 if (Loc.isInvalid())
1420 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001421 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1422 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001423 ++Index;
1424 return true;
1425 }
1426
Douglas Gregor4c678342009-01-28 21:54:33 +00001427 // Note: we perform a linear search of the fields here, despite
1428 // the fact that we have a faster lookup method, because we always
1429 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001430 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001431 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001432 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001433 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001434 Field = RT->getDecl()->field_begin(),
1435 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001436 for (; Field != FieldEnd; ++Field) {
1437 if (Field->isUnnamedBitfield())
1438 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001439
Francois Picheta0e27f02010-12-22 03:46:10 +00001440 // If we find a field representing an anonymous field, look in the
1441 // IndirectFieldDecl that follow for the designated initializer.
1442 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1443 if (IndirectFieldDecl *IF =
1444 FindIndirectFieldDesignator(*Field, FieldName)) {
1445 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1446 D = DIE->getDesignator(DesigIdx);
1447 break;
1448 }
1449 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001450 if (KnownField && KnownField == *Field)
1451 break;
1452 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001453 break;
1454
1455 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001456 }
1457
Douglas Gregor4c678342009-01-28 21:54:33 +00001458 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001459 // There was no normal field in the struct with the designated
1460 // name. Perform another lookup for this name, which may find
1461 // something that we can't designate (e.g., a member function),
1462 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001463 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001464 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001465 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001466 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001467 // Name lookup didn't find anything. Determine whether this
1468 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001470 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001471 TypoCorrection Corrected = SemaRef.CorrectTypo(
1472 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1473 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1474 RT->getDecl(), false, Sema::CTC_NoKeywords);
1475 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001476 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001477 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001478 std::string CorrectedStr(
1479 Corrected.getAsString(SemaRef.getLangOptions()));
1480 std::string CorrectedQuotedStr(
1481 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001482 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001483 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001484 << FieldName << CurrentObjectType << CorrectedQuotedStr
1485 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001486 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001487 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001488 } else {
1489 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1490 << FieldName << CurrentObjectType;
1491 ++Index;
1492 return true;
1493 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001494 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001495
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001496 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001497 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001498 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001499 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001500 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001501 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001502 ++Index;
1503 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001504 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001505
Francois Picheta0e27f02010-12-22 03:46:10 +00001506 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001507 // The replacement field comes from typo correction; find it
1508 // in the list of fields.
1509 FieldIndex = 0;
1510 Field = RT->getDecl()->field_begin();
1511 for (; Field != FieldEnd; ++Field) {
1512 if (Field->isUnnamedBitfield())
1513 continue;
1514
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001515 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001516 Field->getIdentifier() == ReplacementField->getIdentifier())
1517 break;
1518
1519 ++FieldIndex;
1520 }
1521 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001522 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001523
1524 // All of the fields of a union are located at the same place in
1525 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001526 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001527 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001528 StructuredList->setInitializedFieldInUnion(*Field);
1529 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001530
Douglas Gregor54001c12011-06-29 21:51:31 +00001531 // Make sure we can use this declaration.
1532 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1533 ++Index;
1534 return true;
1535 }
1536
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001537 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001538 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Douglas Gregor4c678342009-01-28 21:54:33 +00001540 // Make sure that our non-designated initializer list has space
1541 // for a subobject corresponding to this field.
1542 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001543 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001544
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001545 // This designator names a flexible array member.
1546 if (Field->getType()->isIncompleteArrayType()) {
1547 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001548 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001549 // We can't designate an object within the flexible array
1550 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001551 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001552 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001553 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001554 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001555 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001556 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001557 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001558 << *Field;
1559 Invalid = true;
1560 }
1561
Chris Lattner9046c222010-10-10 17:49:49 +00001562 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1563 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001564 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001565 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001566 diag::err_flexible_array_init_needs_braces)
1567 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001568 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001569 << *Field;
1570 Invalid = true;
1571 }
1572
1573 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001574 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001575 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001576 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001577 diag::err_flexible_array_init_nonempty)
1578 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001579 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001580 << *Field;
1581 Invalid = true;
1582 }
1583
1584 if (Invalid) {
1585 ++Index;
1586 return true;
1587 }
1588
1589 // Initialize the array.
1590 bool prevHadError = hadError;
1591 unsigned newStructuredIndex = FieldIndex;
1592 unsigned OldIndex = Index;
1593 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001594
1595 InitializedEntity MemberEntity =
1596 InitializedEntity::InitializeMember(*Field, &Entity);
1597 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001598 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001599
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001600 IList->setInit(OldIndex, DIE);
1601 if (hadError && !prevHadError) {
1602 ++Field;
1603 ++FieldIndex;
1604 if (NextField)
1605 *NextField = Field;
1606 StructuredIndex = FieldIndex;
1607 return true;
1608 }
1609 } else {
1610 // Recurse to check later designated subobjects.
1611 QualType FieldType = (*Field)->getType();
1612 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001613
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001614 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001615 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001616 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1617 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001618 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001619 true, false))
1620 return true;
1621 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001622
1623 // Find the position of the next field to be initialized in this
1624 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001625 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001626 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001627
1628 // If this the first designator, our caller will continue checking
1629 // the rest of this struct/class/union subobject.
1630 if (IsFirstDesignator) {
1631 if (NextField)
1632 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001633 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001634 return false;
1635 }
1636
Douglas Gregor34e79462009-01-28 23:36:17 +00001637 if (!FinishSubobjectInit)
1638 return false;
1639
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001640 // We've already initialized something in the union; we're done.
1641 if (RT->getDecl()->isUnion())
1642 return hadError;
1643
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001644 // Check the remaining fields within this class/struct/union subobject.
1645 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001646
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001647 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001648 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001649 return hadError && !prevHadError;
1650 }
1651
1652 // C99 6.7.8p6:
1653 //
1654 // If a designator has the form
1655 //
1656 // [ constant-expression ]
1657 //
1658 // then the current object (defined below) shall have array
1659 // type and the expression shall be an integer constant
1660 // expression. If the array is of unknown size, any
1661 // nonnegative value is valid.
1662 //
1663 // Additionally, cope with the GNU extension that permits
1664 // designators of the form
1665 //
1666 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001667 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001668 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001669 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001670 << CurrentObjectType;
1671 ++Index;
1672 return true;
1673 }
1674
1675 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001676 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1677 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001678 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001679 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001680 DesignatedEndIndex = DesignatedStartIndex;
1681 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001682 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001683
Mike Stump1eb44332009-09-09 15:08:12 +00001684 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001685 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001686 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001687 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001688 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001689
Chris Lattnere0fd8322011-02-19 22:28:58 +00001690 // Codegen can't handle evaluating array range designators that have side
1691 // effects, because we replicate the AST value for each initialized element.
1692 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1693 // elements with something that has a side effect, so codegen can emit an
1694 // "error unsupported" error instead of miscompiling the app.
1695 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1696 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregora9c87802009-01-29 19:42:23 +00001697 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001698 }
1699
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001700 if (isa<ConstantArrayType>(AT)) {
1701 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001702 DesignatedStartIndex
1703 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001704 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001705 DesignatedEndIndex
1706 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001707 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1708 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001709 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001710 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001711 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001712 << IndexExpr->getSourceRange();
1713 ++Index;
1714 return true;
1715 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001716 } else {
1717 // Make sure the bit-widths and signedness match.
1718 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001719 DesignatedEndIndex
1720 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001721 else if (DesignatedStartIndex.getBitWidth() <
1722 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001723 DesignatedStartIndex
1724 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001725 DesignatedStartIndex.setIsUnsigned(true);
1726 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Douglas Gregor4c678342009-01-28 21:54:33 +00001729 // Make sure that our non-designated initializer list has space
1730 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001731 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001732 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001733 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001734
Douglas Gregor34e79462009-01-28 23:36:17 +00001735 // Repeatedly perform subobject initializations in the range
1736 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001737
Douglas Gregor34e79462009-01-28 23:36:17 +00001738 // Move to the next designator
1739 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1740 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001741
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001742 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001743 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001744
Douglas Gregor34e79462009-01-28 23:36:17 +00001745 while (DesignatedStartIndex <= DesignatedEndIndex) {
1746 // Recurse to check later designated subobjects.
1747 QualType ElementType = AT->getElementType();
1748 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001749
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001750 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001751 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1752 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001753 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001754 (DesignatedStartIndex == DesignatedEndIndex),
1755 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001756 return true;
1757
1758 // Move to the next index in the array that we'll be initializing.
1759 ++DesignatedStartIndex;
1760 ElementIndex = DesignatedStartIndex.getZExtValue();
1761 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001762
1763 // If this the first designator, our caller will continue checking
1764 // the rest of this array subobject.
1765 if (IsFirstDesignator) {
1766 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001767 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001768 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001769 return false;
1770 }
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Douglas Gregor34e79462009-01-28 23:36:17 +00001772 if (!FinishSubobjectInit)
1773 return false;
1774
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001775 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001776 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001778 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001780 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001781}
1782
Douglas Gregor4c678342009-01-28 21:54:33 +00001783// Get the structured initializer list for a subobject of type
1784// @p CurrentObjectType.
1785InitListExpr *
1786InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1787 QualType CurrentObjectType,
1788 InitListExpr *StructuredList,
1789 unsigned StructuredIndex,
1790 SourceRange InitRange) {
1791 Expr *ExistingInit = 0;
1792 if (!StructuredList)
1793 ExistingInit = SyntacticToSemantic[IList];
1794 else if (StructuredIndex < StructuredList->getNumInits())
1795 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1798 return Result;
1799
1800 if (ExistingInit) {
1801 // We are creating an initializer list that initializes the
1802 // subobjects of the current object, but there was already an
1803 // initialization that completely initialized the current
1804 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001805 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001806 // struct X { int a, b; };
1807 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001808 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001809 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1810 // designated initializer re-initializes the whole
1811 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001812 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001813 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001814 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001815 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001816 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001817 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001818 << ExistingInit->getSourceRange();
1819 }
1820
Mike Stump1eb44332009-09-09 15:08:12 +00001821 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001822 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1823 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001824 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001825
Douglas Gregor63982352010-07-13 18:40:04 +00001826 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001827
Douglas Gregorfa219202009-03-20 23:58:33 +00001828 // Pre-allocate storage for the structured initializer list.
1829 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001830 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001831 bool GotNumInits = false;
1832 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00001833 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001834 GotNumInits = true;
1835 } else if (Index < IList->getNumInits()) {
1836 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00001837 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001838 GotNumInits = true;
1839 }
Douglas Gregor08457732009-03-21 18:13:52 +00001840 }
1841
Mike Stump1eb44332009-09-09 15:08:12 +00001842 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001843 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1844 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1845 NumElements = CAType->getSize().getZExtValue();
1846 // Simple heuristic so that we don't allocate a very large
1847 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001848 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001849 NumElements = 0;
1850 }
John McCall183700f2009-09-21 23:43:11 +00001851 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001852 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001853 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001854 RecordDecl *RDecl = RType->getDecl();
1855 if (RDecl->isUnion())
1856 NumElements = 1;
1857 else
Mike Stump1eb44332009-09-09 15:08:12 +00001858 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001859 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001860 }
1861
Douglas Gregor08457732009-03-21 18:13:52 +00001862 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001863 NumElements = IList->getNumInits();
1864
Ted Kremenek709210f2010-04-13 23:39:13 +00001865 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001866
Douglas Gregor4c678342009-01-28 21:54:33 +00001867 // Link this new initializer list into the structured initializer
1868 // lists.
1869 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001870 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001871 else {
1872 Result->setSyntacticForm(IList);
1873 SyntacticToSemantic[IList] = Result;
1874 }
1875
1876 return Result;
1877}
1878
1879/// Update the initializer at index @p StructuredIndex within the
1880/// structured initializer list to the value @p expr.
1881void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1882 unsigned &StructuredIndex,
1883 Expr *expr) {
1884 // No structured initializer list to update
1885 if (!StructuredList)
1886 return;
1887
Ted Kremenek709210f2010-04-13 23:39:13 +00001888 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1889 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001890 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001891 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001892 diag::warn_initializer_overrides)
1893 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001894 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001895 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001896 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001897 << PrevInit->getSourceRange();
1898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Douglas Gregor4c678342009-01-28 21:54:33 +00001900 ++StructuredIndex;
1901}
1902
Douglas Gregor05c13a32009-01-22 00:58:24 +00001903/// Check that the given Index expression is a valid array designator
1904/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001905/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001906/// and produces a reasonable diagnostic if there is a
1907/// failure. Returns true if there was an error, false otherwise. If
1908/// everything went okay, Value will receive the value of the constant
1909/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001910static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001911CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001912 SourceLocation Loc = Index->getSourceRange().getBegin();
1913
1914 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001915 if (S.VerifyIntegerConstantExpression(Index, &Value))
1916 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001917
Chris Lattner3bf68932009-04-25 21:59:05 +00001918 if (Value.isSigned() && Value.isNegative())
1919 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001920 << Value.toString(10) << Index->getSourceRange();
1921
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001922 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001923 return false;
1924}
1925
John McCall60d7b3a2010-08-24 06:29:42 +00001926ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001927 SourceLocation Loc,
1928 bool GNUSyntax,
1929 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001930 typedef DesignatedInitExpr::Designator ASTDesignator;
1931
1932 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001933 SmallVector<ASTDesignator, 32> Designators;
1934 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001935
1936 // Build designators and check array designator expressions.
1937 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1938 const Designator &D = Desig.getDesignator(Idx);
1939 switch (D.getKind()) {
1940 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001941 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001942 D.getFieldLoc()));
1943 break;
1944
1945 case Designator::ArrayDesignator: {
1946 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1947 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001948 if (!Index->isTypeDependent() &&
1949 !Index->isValueDependent() &&
1950 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001951 Invalid = true;
1952 else {
1953 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001954 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001955 D.getRBracketLoc()));
1956 InitExpressions.push_back(Index);
1957 }
1958 break;
1959 }
1960
1961 case Designator::ArrayRangeDesignator: {
1962 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1963 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1964 llvm::APSInt StartValue;
1965 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001966 bool StartDependent = StartIndex->isTypeDependent() ||
1967 StartIndex->isValueDependent();
1968 bool EndDependent = EndIndex->isTypeDependent() ||
1969 EndIndex->isValueDependent();
1970 if ((!StartDependent &&
1971 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1972 (!EndDependent &&
1973 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001974 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001975 else {
1976 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001977 if (StartDependent || EndDependent) {
1978 // Nothing to compute.
1979 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001980 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001981 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001982 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001983
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001984 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001985 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001986 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001987 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1988 Invalid = true;
1989 } else {
1990 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001991 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001992 D.getEllipsisLoc(),
1993 D.getRBracketLoc()));
1994 InitExpressions.push_back(StartIndex);
1995 InitExpressions.push_back(EndIndex);
1996 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001997 }
1998 break;
1999 }
2000 }
2001 }
2002
2003 if (Invalid || Init.isInvalid())
2004 return ExprError();
2005
2006 // Clear out the expressions within the designation.
2007 Desig.ClearExprs(*this);
2008
2009 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002010 = DesignatedInitExpr::Create(Context,
2011 Designators.data(), Designators.size(),
2012 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002013 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002014
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002015 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002016 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2017 << DIE->getSourceRange();
2018 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002019 Diag(DIE->getLocStart(), diag::ext_designated_init)
2020 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002021
Douglas Gregor05c13a32009-01-22 00:58:24 +00002022 return Owned(DIE);
2023}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002024
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002025bool Sema::CheckInitList(const InitializedEntity &Entity,
2026 InitListExpr *&InitList, QualType &DeclType) {
2027 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002028 if (!CheckInitList.HadError())
2029 InitList = CheckInitList.getFullyStructuredList();
2030
2031 return CheckInitList.HadError();
2032}
Douglas Gregor87fd7032009-02-02 17:43:21 +00002033
Douglas Gregor20093b42009-12-09 23:02:17 +00002034//===----------------------------------------------------------------------===//
2035// Initialization entity
2036//===----------------------------------------------------------------------===//
2037
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002038InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002039 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002040 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002041{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002042 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2043 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002044 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002045 } else {
2046 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002047 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002048 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002049}
2050
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002051InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002052 CXXBaseSpecifier *Base,
2053 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002054{
2055 InitializedEntity Result;
2056 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002057 Result.Base = reinterpret_cast<uintptr_t>(Base);
2058 if (IsInheritedVirtualBase)
2059 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002060
Douglas Gregord6542d82009-12-22 15:35:07 +00002061 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002062 return Result;
2063}
2064
Douglas Gregor99a2e602009-12-16 01:38:02 +00002065DeclarationName InitializedEntity::getName() const {
2066 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002067 case EK_Parameter: {
2068 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2069 return (D ? D->getDeclName() : DeclarationName());
2070 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002071
2072 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002073 case EK_Member:
2074 return VariableOrMember->getDeclName();
2075
2076 case EK_Result:
2077 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002078 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002079 case EK_Temporary:
2080 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002081 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002082 case EK_ArrayElement:
2083 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002084 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002085 return DeclarationName();
2086 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087
Douglas Gregor99a2e602009-12-16 01:38:02 +00002088 // Silence GCC warning
2089 return DeclarationName();
2090}
2091
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002092DeclaratorDecl *InitializedEntity::getDecl() const {
2093 switch (getKind()) {
2094 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002095 case EK_Member:
2096 return VariableOrMember;
2097
John McCallf85e1932011-06-15 23:02:42 +00002098 case EK_Parameter:
2099 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2100
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002101 case EK_Result:
2102 case EK_Exception:
2103 case EK_New:
2104 case EK_Temporary:
2105 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002106 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002107 case EK_ArrayElement:
2108 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002109 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002110 return 0;
2111 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002112
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002113 // Silence GCC warning
2114 return 0;
2115}
2116
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002117bool InitializedEntity::allowsNRVO() const {
2118 switch (getKind()) {
2119 case EK_Result:
2120 case EK_Exception:
2121 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002122
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002123 case EK_Variable:
2124 case EK_Parameter:
2125 case EK_Member:
2126 case EK_New:
2127 case EK_Temporary:
2128 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002129 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002130 case EK_ArrayElement:
2131 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002132 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002133 break;
2134 }
2135
2136 return false;
2137}
2138
Douglas Gregor20093b42009-12-09 23:02:17 +00002139//===----------------------------------------------------------------------===//
2140// Initialization sequence
2141//===----------------------------------------------------------------------===//
2142
2143void InitializationSequence::Step::Destroy() {
2144 switch (Kind) {
2145 case SK_ResolveAddressOfOverloadedFunction:
2146 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002147 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002148 case SK_CastDerivedToBaseLValue:
2149 case SK_BindReference:
2150 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002151 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002152 case SK_UserConversion:
2153 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002154 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002155 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002156 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002157 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002158 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002159 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002160 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002161 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002162 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002163 case SK_PassByIndirectCopyRestore:
2164 case SK_PassByIndirectRestore:
2165 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002166 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002167
Douglas Gregor20093b42009-12-09 23:02:17 +00002168 case SK_ConversionSequence:
2169 delete ICS;
2170 }
2171}
2172
Douglas Gregorb70cf442010-03-26 20:14:36 +00002173bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002174 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002175}
2176
2177bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002178 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002179 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002180
Douglas Gregorb70cf442010-03-26 20:14:36 +00002181 switch (getFailureKind()) {
2182 case FK_TooManyInitsForReference:
2183 case FK_ArrayNeedsInitList:
2184 case FK_ArrayNeedsInitListOrStringLiteral:
2185 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2186 case FK_NonConstLValueReferenceBindingToTemporary:
2187 case FK_NonConstLValueReferenceBindingToUnrelated:
2188 case FK_RValueReferenceBindingToLValue:
2189 case FK_ReferenceInitDropsQualifiers:
2190 case FK_ReferenceInitFailed:
2191 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002192 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002193 case FK_TooManyInitsForScalar:
2194 case FK_ReferenceBindingToInitList:
2195 case FK_InitListBadDestinationType:
2196 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002197 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002198 case FK_ArrayTypeMismatch:
2199 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002200 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002201
Douglas Gregorb70cf442010-03-26 20:14:36 +00002202 case FK_ReferenceInitOverloadFailed:
2203 case FK_UserConversionOverloadFailed:
2204 case FK_ConstructorOverloadFailed:
2205 return FailedOverloadResult == OR_Ambiguous;
2206 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002207
Douglas Gregorb70cf442010-03-26 20:14:36 +00002208 return false;
2209}
2210
Douglas Gregord6e44a32010-04-16 22:09:46 +00002211bool InitializationSequence::isConstructorInitialization() const {
2212 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2213}
2214
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002215bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2216 const Expr *Initializer,
2217 bool *isInitializerConstant,
2218 APValue *ConstantValue) const {
2219 if (Steps.empty() || Initializer->isValueDependent())
2220 return false;
2221
2222 const Step &LastStep = Steps.back();
2223 if (LastStep.Kind != SK_ConversionSequence)
2224 return false;
2225
2226 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2227 const StandardConversionSequence *SCS = NULL;
2228 switch (ICS.getKind()) {
2229 case ImplicitConversionSequence::StandardConversion:
2230 SCS = &ICS.Standard;
2231 break;
2232 case ImplicitConversionSequence::UserDefinedConversion:
2233 SCS = &ICS.UserDefined.After;
2234 break;
2235 case ImplicitConversionSequence::AmbiguousConversion:
2236 case ImplicitConversionSequence::EllipsisConversion:
2237 case ImplicitConversionSequence::BadConversion:
2238 return false;
2239 }
2240
2241 // Check if SCS represents a narrowing conversion, according to C++0x
2242 // [dcl.init.list]p7:
2243 //
2244 // A narrowing conversion is an implicit conversion ...
2245 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2246 QualType FromType = SCS->getToType(0);
2247 QualType ToType = SCS->getToType(1);
2248 switch (PossibleNarrowing) {
2249 // * from a floating-point type to an integer type, or
2250 //
2251 // * from an integer type or unscoped enumeration type to a floating-point
2252 // type, except where the source is a constant expression and the actual
2253 // value after conversion will fit into the target type and will produce
2254 // the original value when converted back to the original type, or
2255 case ICK_Floating_Integral:
2256 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2257 *isInitializerConstant = false;
2258 return true;
2259 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2260 llvm::APSInt IntConstantValue;
2261 if (Initializer &&
2262 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2263 // Convert the integer to the floating type.
2264 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2265 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2266 llvm::APFloat::rmNearestTiesToEven);
2267 // And back.
2268 llvm::APSInt ConvertedValue = IntConstantValue;
2269 bool ignored;
2270 Result.convertToInteger(ConvertedValue,
2271 llvm::APFloat::rmTowardZero, &ignored);
2272 // If the resulting value is different, this was a narrowing conversion.
2273 if (IntConstantValue != ConvertedValue) {
2274 *isInitializerConstant = true;
2275 *ConstantValue = APValue(IntConstantValue);
2276 return true;
2277 }
2278 } else {
2279 // Variables are always narrowings.
2280 *isInitializerConstant = false;
2281 return true;
2282 }
2283 }
2284 return false;
2285
2286 // * from long double to double or float, or from double to float, except
2287 // where the source is a constant expression and the actual value after
2288 // conversion is within the range of values that can be represented (even
2289 // if it cannot be represented exactly), or
2290 case ICK_Floating_Conversion:
2291 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2292 // FromType is larger than ToType.
2293 Expr::EvalResult InitializerValue;
2294 // FIXME: Check whether Initializer is a constant expression according
2295 // to C++0x [expr.const], rather than just whether it can be folded.
2296 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2297 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2298 // Constant! (Except for FIXME above.)
2299 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2300 // Convert the source value into the target type.
2301 bool ignored;
2302 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2303 Ctx.getFloatTypeSemantics(ToType),
2304 llvm::APFloat::rmNearestTiesToEven, &ignored);
2305 // If there was no overflow, the source value is within the range of
2306 // values that can be represented.
2307 if (ConvertStatus & llvm::APFloat::opOverflow) {
2308 *isInitializerConstant = true;
2309 *ConstantValue = InitializerValue.Val;
2310 return true;
2311 }
2312 } else {
2313 *isInitializerConstant = false;
2314 return true;
2315 }
2316 }
2317 return false;
2318
2319 // * from an integer type or unscoped enumeration type to an integer type
2320 // that cannot represent all the values of the original type, except where
2321 // the source is a constant expression and the actual value after
2322 // conversion will fit into the target type and will produce the original
2323 // value when converted back to the original type.
2324 case ICK_Integral_Conversion: {
2325 assert(FromType->isIntegralOrUnscopedEnumerationType());
2326 assert(ToType->isIntegralOrUnscopedEnumerationType());
2327 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2328 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2329 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2330 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2331
2332 if (FromWidth > ToWidth ||
2333 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2334 // Not all values of FromType can be represented in ToType.
2335 llvm::APSInt InitializerValue;
2336 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2337 *isInitializerConstant = true;
2338 *ConstantValue = APValue(InitializerValue);
2339
2340 // Add a bit to the InitializerValue so we don't have to worry about
2341 // signed vs. unsigned comparisons.
2342 InitializerValue = InitializerValue.extend(
2343 InitializerValue.getBitWidth() + 1);
2344 // Convert the initializer to and from the target width and signed-ness.
2345 llvm::APSInt ConvertedValue = InitializerValue;
2346 ConvertedValue = ConvertedValue.trunc(ToWidth);
2347 ConvertedValue.setIsSigned(ToSigned);
2348 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2349 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2350 // If the result is different, this was a narrowing conversion.
2351 return ConvertedValue != InitializerValue;
2352 } else {
2353 // Variables are always narrowings.
2354 *isInitializerConstant = false;
2355 return true;
2356 }
2357 }
2358 return false;
2359 }
2360
2361 default:
2362 // Other kinds of conversions are not narrowings.
2363 return false;
2364 }
2365}
2366
Douglas Gregor20093b42009-12-09 23:02:17 +00002367void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002368 FunctionDecl *Function,
2369 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002370 Step S;
2371 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2372 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002373 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002374 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002375 Steps.push_back(S);
2376}
2377
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002378void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002379 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002380 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002381 switch (VK) {
2382 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2383 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2384 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002385 default: llvm_unreachable("No such category");
2386 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002387 S.Type = BaseType;
2388 Steps.push_back(S);
2389}
2390
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002391void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002392 bool BindingTemporary) {
2393 Step S;
2394 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2395 S.Type = T;
2396 Steps.push_back(S);
2397}
2398
Douglas Gregor523d46a2010-04-18 07:40:54 +00002399void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2400 Step S;
2401 S.Kind = SK_ExtraneousCopyToTemporary;
2402 S.Type = T;
2403 Steps.push_back(S);
2404}
2405
Eli Friedman03981012009-12-11 02:42:07 +00002406void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002407 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002408 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002409 Step S;
2410 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002411 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002412 S.Function.Function = Function;
2413 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002414 Steps.push_back(S);
2415}
2416
2417void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002418 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002419 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002420 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002421 switch (VK) {
2422 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002423 S.Kind = SK_QualificationConversionRValue;
2424 break;
John McCall5baba9d2010-08-25 10:28:54 +00002425 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002426 S.Kind = SK_QualificationConversionXValue;
2427 break;
John McCall5baba9d2010-08-25 10:28:54 +00002428 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002429 S.Kind = SK_QualificationConversionLValue;
2430 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002431 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002432 S.Type = Ty;
2433 Steps.push_back(S);
2434}
2435
2436void InitializationSequence::AddConversionSequenceStep(
2437 const ImplicitConversionSequence &ICS,
2438 QualType T) {
2439 Step S;
2440 S.Kind = SK_ConversionSequence;
2441 S.Type = T;
2442 S.ICS = new ImplicitConversionSequence(ICS);
2443 Steps.push_back(S);
2444}
2445
Douglas Gregord87b61f2009-12-10 17:56:55 +00002446void InitializationSequence::AddListInitializationStep(QualType T) {
2447 Step S;
2448 S.Kind = SK_ListInitialization;
2449 S.Type = T;
2450 Steps.push_back(S);
2451}
2452
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002453void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002454InitializationSequence::AddConstructorInitializationStep(
2455 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002456 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002457 QualType T) {
2458 Step S;
2459 S.Kind = SK_ConstructorInitialization;
2460 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002461 S.Function.Function = Constructor;
2462 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002463 Steps.push_back(S);
2464}
2465
Douglas Gregor71d17402009-12-15 00:01:57 +00002466void InitializationSequence::AddZeroInitializationStep(QualType T) {
2467 Step S;
2468 S.Kind = SK_ZeroInitialization;
2469 S.Type = T;
2470 Steps.push_back(S);
2471}
2472
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002473void InitializationSequence::AddCAssignmentStep(QualType T) {
2474 Step S;
2475 S.Kind = SK_CAssignment;
2476 S.Type = T;
2477 Steps.push_back(S);
2478}
2479
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002480void InitializationSequence::AddStringInitStep(QualType T) {
2481 Step S;
2482 S.Kind = SK_StringInit;
2483 S.Type = T;
2484 Steps.push_back(S);
2485}
2486
Douglas Gregor569c3162010-08-07 11:51:51 +00002487void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2488 Step S;
2489 S.Kind = SK_ObjCObjectConversion;
2490 S.Type = T;
2491 Steps.push_back(S);
2492}
2493
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002494void InitializationSequence::AddArrayInitStep(QualType T) {
2495 Step S;
2496 S.Kind = SK_ArrayInit;
2497 S.Type = T;
2498 Steps.push_back(S);
2499}
2500
John McCallf85e1932011-06-15 23:02:42 +00002501void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2502 bool shouldCopy) {
2503 Step s;
2504 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2505 : SK_PassByIndirectRestore);
2506 s.Type = type;
2507 Steps.push_back(s);
2508}
2509
2510void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2511 Step S;
2512 S.Kind = SK_ProduceObjCObject;
2513 S.Type = T;
2514 Steps.push_back(S);
2515}
2516
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002517void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002518 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002519 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002520 this->Failure = Failure;
2521 this->FailedOverloadResult = Result;
2522}
2523
2524//===----------------------------------------------------------------------===//
2525// Attempt initialization
2526//===----------------------------------------------------------------------===//
2527
John McCallf85e1932011-06-15 23:02:42 +00002528static void MaybeProduceObjCObject(Sema &S,
2529 InitializationSequence &Sequence,
2530 const InitializedEntity &Entity) {
2531 if (!S.getLangOptions().ObjCAutoRefCount) return;
2532
2533 /// When initializing a parameter, produce the value if it's marked
2534 /// __attribute__((ns_consumed)).
2535 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2536 if (!Entity.isParameterConsumed())
2537 return;
2538
2539 assert(Entity.getType()->isObjCRetainableType() &&
2540 "consuming an object of unretainable type?");
2541 Sequence.AddProduceObjCObjectStep(Entity.getType());
2542
2543 /// When initializing a return value, if the return type is a
2544 /// retainable type, then returns need to immediately retain the
2545 /// object. If an autorelease is required, it will be done at the
2546 /// last instant.
2547 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2548 if (!Entity.getType()->isObjCRetainableType())
2549 return;
2550
2551 Sequence.AddProduceObjCObjectStep(Entity.getType());
2552 }
2553}
2554
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002555/// \brief Attempt list initialization (C++0x [dcl.init.list])
2556static void TryListInitialization(Sema &S,
2557 const InitializedEntity &Entity,
2558 const InitializationKind &Kind,
2559 InitListExpr *InitList,
2560 InitializationSequence &Sequence) {
2561 // FIXME: We only perform rudimentary checking of list
2562 // initializations at this point, then assume that any list
2563 // initialization of an array, aggregate, or scalar will be
2564 // well-formed. When we actually "perform" list initialization, we'll
2565 // do all of the necessary checking. C++0x initializer lists will
2566 // force us to perform more checking here.
2567
2568 QualType DestType = Entity.getType();
2569
2570 // C++ [dcl.init]p13:
2571 // If T is a scalar type, then a declaration of the form
2572 //
2573 // T x = { a };
2574 //
2575 // is equivalent to
2576 //
2577 // T x = a;
2578 if (DestType->isScalarType()) {
2579 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2580 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2581 return;
2582 }
2583
2584 // Assume scalar initialization from a single value works.
2585 } else if (DestType->isAggregateType()) {
2586 // Assume aggregate initialization works.
2587 } else if (DestType->isVectorType()) {
2588 // Assume vector initialization works.
2589 } else if (DestType->isReferenceType()) {
2590 // FIXME: C++0x defines behavior for this.
2591 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2592 return;
2593 } else if (DestType->isRecordType()) {
2594 // FIXME: C++0x defines behavior for this
2595 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2596 }
2597
2598 // Add a general "list initialization" step.
2599 Sequence.AddListInitializationStep(DestType);
2600}
Douglas Gregor20093b42009-12-09 23:02:17 +00002601
2602/// \brief Try a reference initialization that involves calling a conversion
2603/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002604static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2605 const InitializedEntity &Entity,
2606 const InitializationKind &Kind,
2607 Expr *Initializer,
2608 bool AllowRValues,
2609 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002610 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002611 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2612 QualType T1 = cv1T1.getUnqualifiedType();
2613 QualType cv2T2 = Initializer->getType();
2614 QualType T2 = cv2T2.getUnqualifiedType();
2615
2616 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002617 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002618 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002619 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002620 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002621 ObjCConversion,
2622 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002623 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002624 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002625 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002626 (void)ObjCLifetimeConversion;
2627
Douglas Gregor20093b42009-12-09 23:02:17 +00002628 // Build the candidate set directly in the initialization sequence
2629 // structure, so that it will persist if we fail.
2630 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2631 CandidateSet.clear();
2632
2633 // Determine whether we are allowed to call explicit constructors or
2634 // explicit conversion operators.
2635 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002636
Douglas Gregor20093b42009-12-09 23:02:17 +00002637 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002638 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2639 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002640 // The type we're converting to is a class type. Enumerate its constructors
2641 // to see if there is a suitable conversion.
2642 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002643
Douglas Gregor20093b42009-12-09 23:02:17 +00002644 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002645 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002646 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002647 NamedDecl *D = *Con;
2648 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2649
Douglas Gregor20093b42009-12-09 23:02:17 +00002650 // Find the constructor (which may be a template).
2651 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002652 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002653 if (ConstructorTmpl)
2654 Constructor = cast<CXXConstructorDecl>(
2655 ConstructorTmpl->getTemplatedDecl());
2656 else
John McCall9aa472c2010-03-19 07:35:19 +00002657 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002658
Douglas Gregor20093b42009-12-09 23:02:17 +00002659 if (!Constructor->isInvalidDecl() &&
2660 Constructor->isConvertingConstructor(AllowExplicit)) {
2661 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002662 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002663 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002664 &Initializer, 1, CandidateSet,
2665 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002666 else
John McCall9aa472c2010-03-19 07:35:19 +00002667 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002668 &Initializer, 1, CandidateSet,
2669 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002670 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002671 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002672 }
John McCall572fc622010-08-17 07:23:57 +00002673 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2674 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002675
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002676 const RecordType *T2RecordType = 0;
2677 if ((T2RecordType = T2->getAs<RecordType>()) &&
2678 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002679 // The type we're converting from is a class type, enumerate its conversion
2680 // functions.
2681 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2682
John McCalleec51cf2010-01-20 00:46:10 +00002683 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002684 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002685 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2686 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002687 NamedDecl *D = *I;
2688 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2689 if (isa<UsingShadowDecl>(D))
2690 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002691
Douglas Gregor20093b42009-12-09 23:02:17 +00002692 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2693 CXXConversionDecl *Conv;
2694 if (ConvTemplate)
2695 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2696 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002697 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002698
Douglas Gregor20093b42009-12-09 23:02:17 +00002699 // If the conversion function doesn't return a reference type,
2700 // it can't be considered for this conversion unless we're allowed to
2701 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702 // FIXME: Do we need to make sure that we only consider conversion
2703 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002704 // break recursion.
2705 if ((AllowExplicit || !Conv->isExplicit()) &&
2706 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2707 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002708 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002709 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002710 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002711 else
John McCall9aa472c2010-03-19 07:35:19 +00002712 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002713 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002714 }
2715 }
2716 }
John McCall572fc622010-08-17 07:23:57 +00002717 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2718 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002719
Douglas Gregor20093b42009-12-09 23:02:17 +00002720 SourceLocation DeclLoc = Initializer->getLocStart();
2721
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002722 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002723 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002724 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002725 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002726 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002727
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002729
Chandler Carruth25ca4212011-02-25 19:41:05 +00002730 // This is the overload that will actually be used for the initialization, so
2731 // mark it as used.
2732 S.MarkDeclarationReferenced(DeclLoc, Function);
2733
Eli Friedman03981012009-12-11 02:42:07 +00002734 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002735 if (isa<CXXConversionDecl>(Function))
2736 T2 = Function->getResultType();
2737 else
2738 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002739
2740 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002741 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002742 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002743
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002744 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002745 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002746 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002747 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002748 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002749 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002750 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002751
Douglas Gregor20093b42009-12-09 23:02:17 +00002752 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002753 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002754 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002755 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002756 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002757 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002758 NewDerivedToBase, NewObjCConversion,
2759 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002760 if (NewRefRelationship == Sema::Ref_Incompatible) {
2761 // If the type we've converted to is not reference-related to the
2762 // type we're looking for, then there is another conversion step
2763 // we need to perform to produce a temporary of the right type
2764 // that we'll be binding to.
2765 ImplicitConversionSequence ICS;
2766 ICS.setStandard();
2767 ICS.Standard = Best->FinalConversion;
2768 T2 = ICS.Standard.getToType(2);
2769 Sequence.AddConversionSequenceStep(ICS, T2);
2770 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002771 Sequence.AddDerivedToBaseCastStep(
2772 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002773 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002774 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002775 else if (NewObjCConversion)
2776 Sequence.AddObjCObjectConversionStep(
2777 S.Context.getQualifiedType(T1,
2778 T2.getNonReferenceType().getQualifiers()));
2779
Douglas Gregor20093b42009-12-09 23:02:17 +00002780 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002781 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002782
Douglas Gregor20093b42009-12-09 23:02:17 +00002783 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2784 return OR_Success;
2785}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002786
2787/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2788static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002789 const InitializedEntity &Entity,
2790 const InitializationKind &Kind,
2791 Expr *Initializer,
2792 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002793 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002794 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002795 Qualifiers T1Quals;
2796 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002797 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002798 Qualifiers T2Quals;
2799 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002800 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002801
Douglas Gregor20093b42009-12-09 23:02:17 +00002802 // If the initializer is the address of an overloaded function, try
2803 // to resolve the overloaded function. If all goes well, T2 is the
2804 // type of the resulting function.
2805 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002806 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002807 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002808 T1,
2809 false,
2810 Found)) {
2811 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2812 cv2T2 = Fn->getType();
2813 T2 = cv2T2.getUnqualifiedType();
2814 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002815 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2816 return;
2817 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002818 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002819
Douglas Gregor20093b42009-12-09 23:02:17 +00002820 // Compute some basic properties of the types and the initializer.
2821 bool isLValueRef = DestType->isLValueReferenceType();
2822 bool isRValueRef = !isLValueRef;
2823 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002824 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002825 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002826 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002827 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002828 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002829 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002830
Douglas Gregor20093b42009-12-09 23:02:17 +00002831 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002832 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002833 // "cv2 T2" as follows:
2834 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002835 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002836 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002837 // Note the analogous bullet points for rvlaue refs to functions. Because
2838 // there are no function rvalues in C++, rvalue refs to functions are treated
2839 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002840 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002841 bool T1Function = T1->isFunctionType();
2842 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002843 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002844 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002845 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002846 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002847 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002848 // reference-compatible with "cv2 T2," or
2849 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002850 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002851 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002852 // can occur. However, we do pay attention to whether it is a bit-field
2853 // to decide whether we're actually binding to a temporary created from
2854 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002855 if (DerivedToBase)
2856 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002857 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002858 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002859 else if (ObjCConversion)
2860 Sequence.AddObjCObjectConversionStep(
2861 S.Context.getQualifiedType(T1, T2Quals));
2862
Chandler Carruth5535c382010-01-12 20:32:25 +00002863 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002864 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002865 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002866 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002867 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002868 return;
2869 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002870
2871 // - has a class type (i.e., T2 is a class type), where T1 is not
2872 // reference-related to T2, and can be implicitly converted to an
2873 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2874 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002875 // applicable conversion functions (13.3.1.6) and choosing the best
2876 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002877 // If we have an rvalue ref to function type here, the rhs must be
2878 // an rvalue.
2879 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2880 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002881 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002882 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002883 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002884 Sequence);
2885 if (ConvOvlResult == OR_Success)
2886 return;
John McCall1d318332010-01-12 00:44:57 +00002887 if (ConvOvlResult != OR_No_Viable_Function) {
2888 Sequence.SetOverloadFailure(
2889 InitializationSequence::FK_ReferenceInitOverloadFailed,
2890 ConvOvlResult);
2891 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002892 }
2893 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002894
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002895 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002896 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002897 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002898 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002899 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2900 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2901 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002902 Sequence.SetOverloadFailure(
2903 InitializationSequence::FK_ReferenceInitOverloadFailed,
2904 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002905 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002906 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002907 ? (RefRelationship == Sema::Ref_Related
2908 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2909 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2910 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002911
Douglas Gregor20093b42009-12-09 23:02:17 +00002912 return;
2913 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002914
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002915 // - If the initializer expression
2916 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2917 // "cv1 T1" is reference-compatible with "cv2 T2"
2918 // Note: functions are handled below.
2919 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002920 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002921 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002922 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002923 (InitCategory.isXValue() ||
2924 (InitCategory.isPRValue() && T2->isRecordType()) ||
2925 (InitCategory.isPRValue() && T2->isArrayType()))) {
2926 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2927 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002928 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2929 // compiler the freedom to perform a copy here or bind to the
2930 // object, while C++0x requires that we bind directly to the
2931 // object. Hence, we always bind to the object without making an
2932 // extra copy. However, in C++03 requires that we check for the
2933 // presence of a suitable copy constructor:
2934 //
2935 // The constructor that would be used to make the copy shall
2936 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002937 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002938 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002939 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002940
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002941 if (DerivedToBase)
2942 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2943 ValueKind);
2944 else if (ObjCConversion)
2945 Sequence.AddObjCObjectConversionStep(
2946 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002947
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002948 if (T1Quals != T2Quals)
2949 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002950 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002951 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002952 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002953 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002954
2955 // - has a class type (i.e., T2 is a class type), where T1 is not
2956 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002957 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2958 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002959 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002960 if (RefRelationship == Sema::Ref_Incompatible) {
2961 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2962 Kind, Initializer,
2963 /*AllowRValues=*/true,
2964 Sequence);
2965 if (ConvOvlResult)
2966 Sequence.SetOverloadFailure(
2967 InitializationSequence::FK_ReferenceInitOverloadFailed,
2968 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002969
Douglas Gregor20093b42009-12-09 23:02:17 +00002970 return;
2971 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002972
Douglas Gregor20093b42009-12-09 23:02:17 +00002973 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2974 return;
2975 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002976
2977 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00002978 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002979 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00002980 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002981
Douglas Gregor20093b42009-12-09 23:02:17 +00002982 // Determine whether we are allowed to call explicit constructors or
2983 // explicit conversion operators.
2984 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002985
2986 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2987
John McCallf85e1932011-06-15 23:02:42 +00002988 ImplicitConversionSequence ICS
2989 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00002990 /*SuppressUserConversions*/ false,
2991 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002992 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00002993 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2994 /*AllowObjCWritebackConversion=*/false);
2995
2996 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002997 // FIXME: Use the conversion function set stored in ICS to turn
2998 // this into an overloading ambiguity diagnostic. However, we need
2999 // to keep that set as an OverloadCandidateSet rather than as some
3000 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003001 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3002 Sequence.SetOverloadFailure(
3003 InitializationSequence::FK_ReferenceInitOverloadFailed,
3004 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003005 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3006 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003007 else
3008 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003009 return;
John McCallf85e1932011-06-15 23:02:42 +00003010 } else {
3011 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003012 }
3013
3014 // [...] If T1 is reference-related to T2, cv1 must be the
3015 // same cv-qualification as, or greater cv-qualification
3016 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003017 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3018 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003020 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003021 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3022 return;
3023 }
3024
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003025 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003026 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003027 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003028 InitCategory.isLValue()) {
3029 Sequence.SetFailed(
3030 InitializationSequence::FK_RValueReferenceBindingToLValue);
3031 return;
3032 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003033
Douglas Gregor20093b42009-12-09 23:02:17 +00003034 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3035 return;
3036}
3037
3038/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039/// (C++ [dcl.init.string], C99 6.7.8).
3040static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003041 const InitializedEntity &Entity,
3042 const InitializationKind &Kind,
3043 Expr *Initializer,
3044 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003045 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003046}
3047
Douglas Gregor20093b42009-12-09 23:02:17 +00003048/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3049/// enumerates the constructors of the initialized entity and performs overload
3050/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003051static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003052 const InitializedEntity &Entity,
3053 const InitializationKind &Kind,
3054 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003055 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003056 InitializationSequence &Sequence) {
Douglas Gregor51c56d62009-12-14 20:49:26 +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 Gregor51c56d62009-12-14 20:49:26 +00003062 // Determine whether we are allowed to call explicit constructors or
3063 // explicit conversion operators.
3064 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3065 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003066 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003067
3068 // The type we're constructing needs to be complete.
3069 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003070 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003071 return;
3072 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073
Douglas Gregor51c56d62009-12-14 20:49:26 +00003074 // The type we're converting to is a class type. Enumerate its constructors
3075 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003076 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003077 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003078 CXXRecordDecl *DestRecordDecl
3079 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003080
Douglas Gregor51c56d62009-12-14 20:49:26 +00003081 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003082 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003083 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003084 NamedDecl *D = *Con;
3085 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003086 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003087
Douglas Gregor51c56d62009-12-14 20:49:26 +00003088 // Find the constructor (which may be a template).
3089 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003090 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003091 if (ConstructorTmpl)
3092 Constructor = cast<CXXConstructorDecl>(
3093 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003094 else {
John McCall9aa472c2010-03-19 07:35:19 +00003095 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003096
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003097 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003098 // suppress user-defined conversions on the arguments.
3099 // FIXME: Move constructors?
3100 if (Kind.getKind() == InitializationKind::IK_Copy &&
3101 Constructor->isCopyConstructor())
3102 SuppressUserConversions = true;
3103 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003104
Douglas Gregor51c56d62009-12-14 20:49:26 +00003105 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003106 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003107 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003108 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003109 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003110 Args, NumArgs, CandidateSet,
3111 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003112 else
John McCall9aa472c2010-03-19 07:35:19 +00003113 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003114 Args, NumArgs, CandidateSet,
3115 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003116 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003117 }
3118
Douglas Gregor51c56d62009-12-14 20:49:26 +00003119 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120
3121 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003122 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003123 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003124 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003125 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003126 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003127 Result);
3128 return;
3129 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003130
3131 // C++0x [dcl.init]p6:
3132 // If a program calls for the default initialization of an object
3133 // of a const-qualified type T, T shall be a class type with a
3134 // user-provided default constructor.
3135 if (Kind.getKind() == InitializationKind::IK_Default &&
3136 Entity.getType().isConstQualified() &&
3137 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3138 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3139 return;
3140 }
3141
Douglas Gregor51c56d62009-12-14 20:49:26 +00003142 // Add the constructor initialization step. Any cv-qualification conversion is
3143 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003144 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003145 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003146 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003147 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003148}
3149
Douglas Gregor71d17402009-12-15 00:01:57 +00003150/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003151static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003152 const InitializedEntity &Entity,
3153 const InitializationKind &Kind,
3154 InitializationSequence &Sequence) {
3155 // C++ [dcl.init]p5:
3156 //
3157 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003158 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003159
Douglas Gregor71d17402009-12-15 00:01:57 +00003160 // -- if T is an array type, then each element is value-initialized;
3161 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3162 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003163
Douglas Gregor71d17402009-12-15 00:01:57 +00003164 if (const RecordType *RT = T->getAs<RecordType>()) {
3165 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3166 // -- if T is a class type (clause 9) with a user-declared
3167 // constructor (12.1), then the default constructor for T is
3168 // called (and the initialization is ill-formed if T has no
3169 // accessible default constructor);
3170 //
3171 // FIXME: we really want to refer to a single subobject of the array,
3172 // but Entity doesn't have a way to capture that (yet).
3173 if (ClassDecl->hasUserDeclaredConstructor())
3174 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175
Douglas Gregor16006c92009-12-16 18:50:27 +00003176 // -- if T is a (possibly cv-qualified) non-union class type
3177 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003178 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003179 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003180 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003181 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003182 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003184 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003185 }
3186 }
3187
Douglas Gregord6542d82009-12-22 15:35:07 +00003188 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003189}
3190
Douglas Gregor99a2e602009-12-16 01:38:02 +00003191/// \brief Attempt default initialization (C++ [dcl.init]p6).
3192static void TryDefaultInitialization(Sema &S,
3193 const InitializedEntity &Entity,
3194 const InitializationKind &Kind,
3195 InitializationSequence &Sequence) {
3196 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003197
Douglas Gregor99a2e602009-12-16 01:38:02 +00003198 // C++ [dcl.init]p6:
3199 // To default-initialize an object of type T means:
3200 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003201 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3202
Douglas Gregor99a2e602009-12-16 01:38:02 +00003203 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3204 // constructor for T is called (and the initialization is ill-formed if
3205 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003206 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003207 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3208 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003210
Douglas Gregor99a2e602009-12-16 01:38:02 +00003211 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003212
Douglas Gregor99a2e602009-12-16 01:38:02 +00003213 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003215 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003216 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003217 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003218 return;
3219 }
3220
3221 // If the destination type has a lifetime property, zero-initialize it.
3222 if (DestType.getQualifiers().hasObjCLifetime()) {
3223 Sequence.AddZeroInitializationStep(Entity.getType());
3224 return;
3225 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003226}
3227
Douglas Gregor20093b42009-12-09 23:02:17 +00003228/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3229/// which enumerates all conversion functions and performs overload resolution
3230/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003231static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003232 const InitializedEntity &Entity,
3233 const InitializationKind &Kind,
3234 Expr *Initializer,
3235 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003236 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003237 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3238 QualType SourceType = Initializer->getType();
3239 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3240 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241
Douglas Gregor4a520a22009-12-14 17:27:33 +00003242 // Build the candidate set directly in the initialization sequence
3243 // structure, so that it will persist if we fail.
3244 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3245 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003246
Douglas Gregor4a520a22009-12-14 17:27:33 +00003247 // Determine whether we are allowed to call explicit constructors or
3248 // explicit conversion operators.
3249 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003250
Douglas Gregor4a520a22009-12-14 17:27:33 +00003251 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3252 // The type we're converting to is a class type. Enumerate its constructors
3253 // to see if there is a suitable conversion.
3254 CXXRecordDecl *DestRecordDecl
3255 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003257 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003259 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003260 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003261 Con != ConEnd; ++Con) {
3262 NamedDecl *D = *Con;
3263 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003265 // Find the constructor (which may be a template).
3266 CXXConstructorDecl *Constructor = 0;
3267 FunctionTemplateDecl *ConstructorTmpl
3268 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003269 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003270 Constructor = cast<CXXConstructorDecl>(
3271 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003272 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003273 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003274
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003275 if (!Constructor->isInvalidDecl() &&
3276 Constructor->isConvertingConstructor(AllowExplicit)) {
3277 if (ConstructorTmpl)
3278 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3279 /*ExplicitArgs*/ 0,
3280 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003281 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003282 else
3283 S.AddOverloadCandidate(Constructor, FoundDecl,
3284 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003285 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003286 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003288 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003289 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003290
3291 SourceLocation DeclLoc = Initializer->getLocStart();
3292
Douglas Gregor4a520a22009-12-14 17:27:33 +00003293 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3294 // The type we're converting from is a class type, enumerate its conversion
3295 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003296
Eli Friedman33c2da92009-12-20 22:12:03 +00003297 // We can only enumerate the conversion functions for a complete type; if
3298 // the type isn't complete, simply skip this step.
3299 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3300 CXXRecordDecl *SourceRecordDecl
3301 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003302
John McCalleec51cf2010-01-20 00:46:10 +00003303 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003304 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003305 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003306 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003307 I != E; ++I) {
3308 NamedDecl *D = *I;
3309 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3310 if (isa<UsingShadowDecl>(D))
3311 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003312
Eli Friedman33c2da92009-12-20 22:12:03 +00003313 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3314 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003315 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003316 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003317 else
John McCall32daa422010-03-31 01:36:47 +00003318 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003319
Eli Friedman33c2da92009-12-20 22:12:03 +00003320 if (AllowExplicit || !Conv->isExplicit()) {
3321 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003322 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003323 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003324 CandidateSet);
3325 else
John McCall9aa472c2010-03-19 07:35:19 +00003326 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003327 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003328 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003329 }
3330 }
3331 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003332
3333 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003334 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003335 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003336 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003337 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003338 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003339 Result);
3340 return;
3341 }
John McCall1d318332010-01-12 00:44:57 +00003342
Douglas Gregor4a520a22009-12-14 17:27:33 +00003343 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003344 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003345
Douglas Gregor4a520a22009-12-14 17:27:33 +00003346 if (isa<CXXConstructorDecl>(Function)) {
3347 // Add the user-defined conversion step. Any cv-qualification conversion is
3348 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003349 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003350 return;
3351 }
3352
3353 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003354 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003355 if (ConvType->getAs<RecordType>()) {
3356 // If we're converting to a class type, there may be an copy if
3357 // the resulting temporary object (possible to create an object of
3358 // a base class type). That copy is not a separate conversion, so
3359 // we just make a note of the actual destination type (possibly a
3360 // base class of the type returned by the conversion function) and
3361 // let the user-defined conversion step handle the conversion.
3362 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3363 return;
3364 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003365
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003366 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003367
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003368 // If the conversion following the call to the conversion function
3369 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003370 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3371 Best->FinalConversion.Third) {
3372 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003373 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003374 ICS.Standard = Best->FinalConversion;
3375 Sequence.AddConversionSequenceStep(ICS, DestType);
3376 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003377}
3378
John McCallf85e1932011-06-15 23:02:42 +00003379/// The non-zero enum values here are indexes into diagnostic alternatives.
3380enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3381
3382/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003383static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3384 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003385 // Skip parens.
3386 e = e->IgnoreParens();
3387
3388 // Skip address-of nodes.
3389 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3390 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003391 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003392
3393 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003394 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3395 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003396 case CK_Dependent:
3397 case CK_BitCast:
3398 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003399 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003400 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003401
3402 case CK_ArrayToPointerDecay:
3403 return IIK_nonscalar;
3404
3405 case CK_NullToPointer:
3406 return IIK_okay;
3407
3408 default:
3409 break;
3410 }
3411
3412 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003413 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3414 if (!isAddressOf) return IIK_nonlocal;
3415
3416 VarDecl *var;
3417 if (isa<DeclRefExpr>(e)) {
3418 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3419 if (!var) return IIK_nonlocal;
3420 } else {
3421 var = cast<BlockDeclRefExpr>(e)->getDecl();
3422 }
3423
3424 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003425
3426 // If we have a conditional operator, check both sides.
3427 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003428 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003429 return iik;
3430
John McCallc03fa492011-06-27 23:59:58 +00003431 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003432
3433 // These are never scalar.
3434 } else if (isa<ArraySubscriptExpr>(e)) {
3435 return IIK_nonscalar;
3436
3437 // Otherwise, it needs to be a null pointer constant.
3438 } else {
3439 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3440 ? IIK_okay : IIK_nonlocal);
3441 }
3442
3443 return IIK_nonlocal;
3444}
3445
3446/// Check whether the given expression is a valid operand for an
3447/// indirect copy/restore.
3448static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3449 assert(src->isRValue());
3450
John McCallc03fa492011-06-27 23:59:58 +00003451 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003452 if (iik == IIK_okay) return;
3453
3454 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3455 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3456 << src->getSourceRange();
3457}
3458
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003459/// \brief Determine whether we have compatible array types for the
3460/// purposes of GNU by-copy array initialization.
3461static bool hasCompatibleArrayTypes(ASTContext &Context,
3462 const ArrayType *Dest,
3463 const ArrayType *Source) {
3464 // If the source and destination array types are equivalent, we're
3465 // done.
3466 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3467 return true;
3468
3469 // Make sure that the element types are the same.
3470 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3471 return false;
3472
3473 // The only mismatch we allow is when the destination is an
3474 // incomplete array type and the source is a constant array type.
3475 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3476}
3477
John McCallf85e1932011-06-15 23:02:42 +00003478static bool tryObjCWritebackConversion(Sema &S,
3479 InitializationSequence &Sequence,
3480 const InitializedEntity &Entity,
3481 Expr *Initializer) {
3482 bool ArrayDecay = false;
3483 QualType ArgType = Initializer->getType();
3484 QualType ArgPointee;
3485 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3486 ArrayDecay = true;
3487 ArgPointee = ArgArrayType->getElementType();
3488 ArgType = S.Context.getPointerType(ArgPointee);
3489 }
3490
3491 // Handle write-back conversion.
3492 QualType ConvertedArgType;
3493 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3494 ConvertedArgType))
3495 return false;
3496
3497 // We should copy unless we're passing to an argument explicitly
3498 // marked 'out'.
3499 bool ShouldCopy = true;
3500 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3501 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3502
3503 // Do we need an lvalue conversion?
3504 if (ArrayDecay || Initializer->isGLValue()) {
3505 ImplicitConversionSequence ICS;
3506 ICS.setStandard();
3507 ICS.Standard.setAsIdentityConversion();
3508
3509 QualType ResultType;
3510 if (ArrayDecay) {
3511 ICS.Standard.First = ICK_Array_To_Pointer;
3512 ResultType = S.Context.getPointerType(ArgPointee);
3513 } else {
3514 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3515 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3516 }
3517
3518 Sequence.AddConversionSequenceStep(ICS, ResultType);
3519 }
3520
3521 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3522 return true;
3523}
3524
Douglas Gregor20093b42009-12-09 23:02:17 +00003525InitializationSequence::InitializationSequence(Sema &S,
3526 const InitializedEntity &Entity,
3527 const InitializationKind &Kind,
3528 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003529 unsigned NumArgs)
3530 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003531 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003532
Douglas Gregor20093b42009-12-09 23:02:17 +00003533 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534 // The semantics of initializers are as follows. The destination type is
3535 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003536 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003537 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003538 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003539 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003540
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003541 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003542 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3543 SequenceKind = DependentSequence;
3544 return;
3545 }
3546
Sebastian Redl7491c492011-06-05 13:59:11 +00003547 // Almost everything is a normal sequence.
3548 setSequenceKind(NormalSequence);
3549
John McCall241d5582010-12-07 22:54:16 +00003550 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003551 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3552 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3553 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003554 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003555 return;
3556 }
3557 Args[I] = Result.take();
3558 }
John McCall241d5582010-12-07 22:54:16 +00003559
Douglas Gregor20093b42009-12-09 23:02:17 +00003560 QualType SourceType;
3561 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003562 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003563 Initializer = Args[0];
3564 if (!isa<InitListExpr>(Initializer))
3565 SourceType = Initializer->getType();
3566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003567
3568 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003569 // list-initialized (8.5.4).
3570 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003571 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003572 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003573 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003574
Douglas Gregor20093b42009-12-09 23:02:17 +00003575 // - If the destination type is a reference type, see 8.5.3.
3576 if (DestType->isReferenceType()) {
3577 // C++0x [dcl.init.ref]p1:
3578 // A variable declared to be a T& or T&&, that is, "reference to type T"
3579 // (8.3.2), shall be initialized by an object, or function, of type T or
3580 // by an object that can be converted into a T.
3581 // (Therefore, multiple arguments are not permitted.)
3582 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003583 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003584 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003585 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003586 return;
3587 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003588
Douglas Gregor20093b42009-12-09 23:02:17 +00003589 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003590 if (Kind.getKind() == InitializationKind::IK_Value ||
3591 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003592 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003593 return;
3594 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003595
Douglas Gregor99a2e602009-12-16 01:38:02 +00003596 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003597 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003598 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003599 return;
3600 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003601
John McCallce6c9b72011-02-21 07:22:22 +00003602 // - If the destination type is an array of characters, an array of
3603 // char16_t, an array of char32_t, or an array of wchar_t, and the
3604 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003605 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003606 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003607 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3608 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003609 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003610 return;
3611 }
3612
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003613 // Note: as an GNU C extension, we allow initialization of an
3614 // array from a compound literal that creates an array of the same
3615 // type, so long as the initializer has no side effects.
3616 if (!S.getLangOptions().CPlusPlus && Initializer &&
3617 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3618 Initializer->getType()->isArrayType()) {
3619 const ArrayType *SourceAT
3620 = Context.getAsArrayType(Initializer->getType());
3621 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003622 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003623 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003624 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003625 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003626 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003627 }
3628 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003629 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003630 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003631 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003632
Douglas Gregor20093b42009-12-09 23:02:17 +00003633 return;
3634 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003635
John McCallf85e1932011-06-15 23:02:42 +00003636 // Determine whether we should consider writeback conversions for
3637 // Objective-C ARC.
3638 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3639 Entity.getKind() == InitializedEntity::EK_Parameter;
3640
3641 // We're at the end of the line for C: it's either a write-back conversion
3642 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003643 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003644 // If allowed, check whether this is an Objective-C writeback conversion.
3645 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003646 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003647 return;
3648 }
3649
3650 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003651 AddCAssignmentStep(DestType);
3652 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003653 return;
3654 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655
John McCallf85e1932011-06-15 23:02:42 +00003656 assert(S.getLangOptions().CPlusPlus);
3657
Douglas Gregor20093b42009-12-09 23:02:17 +00003658 // - If the destination type is a (possibly cv-qualified) class type:
3659 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003660 // - If the initialization is direct-initialization, or if it is
3661 // copy-initialization where the cv-unqualified version of the
3662 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003663 // class of the destination, constructors are considered. [...]
3664 if (Kind.getKind() == InitializationKind::IK_Direct ||
3665 (Kind.getKind() == InitializationKind::IK_Copy &&
3666 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3667 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003668 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003669 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003671 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003672 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003673 // used) to a derived class thereof are enumerated as described in
3674 // 13.3.1.4, and the best one is chosen through overload resolution
3675 // (13.3).
3676 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003677 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003678 return;
3679 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003680
Douglas Gregor99a2e602009-12-16 01:38:02 +00003681 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003682 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003683 return;
3684 }
3685 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003686
3687 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003688 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003689 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003690 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3691 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003692 return;
3693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694
Douglas Gregor20093b42009-12-09 23:02:17 +00003695 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003696 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003697 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003699 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003700
3701 ImplicitConversionSequence ICS
3702 = S.TryImplicitConversion(Initializer, Entity.getType(),
3703 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003704 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003705 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003706 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3707 allowObjCWritebackConversion);
3708
3709 if (ICS.isStandard() &&
3710 ICS.Standard.Second == ICK_Writeback_Conversion) {
3711 // Objective-C ARC writeback conversion.
3712
3713 // We should copy unless we're passing to an argument explicitly
3714 // marked 'out'.
3715 bool ShouldCopy = true;
3716 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3717 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3718
3719 // If there was an lvalue adjustment, add it as a separate conversion.
3720 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3721 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3722 ImplicitConversionSequence LvalueICS;
3723 LvalueICS.setStandard();
3724 LvalueICS.Standard.setAsIdentityConversion();
3725 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3726 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003727 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003728 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003729
3730 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003731 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003732 DeclAccessPair dap;
3733 if (Initializer->getType() == Context.OverloadTy &&
3734 !S.ResolveAddressOfOverloadedFunction(Initializer
3735 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003736 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003737 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003738 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003739 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003740 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003741
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003742 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003743 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003744}
3745
3746InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003747 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003748 StepEnd = Steps.end();
3749 Step != StepEnd; ++Step)
3750 Step->Destroy();
3751}
3752
3753//===----------------------------------------------------------------------===//
3754// Perform initialization
3755//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003756static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003757getAssignmentAction(const InitializedEntity &Entity) {
3758 switch(Entity.getKind()) {
3759 case InitializedEntity::EK_Variable:
3760 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003761 case InitializedEntity::EK_Exception:
3762 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003763 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003764 return Sema::AA_Initializing;
3765
3766 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003767 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003768 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3769 return Sema::AA_Sending;
3770
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003771 return Sema::AA_Passing;
3772
3773 case InitializedEntity::EK_Result:
3774 return Sema::AA_Returning;
3775
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003776 case InitializedEntity::EK_Temporary:
3777 // FIXME: Can we tell apart casting vs. converting?
3778 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003779
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003780 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003781 case InitializedEntity::EK_ArrayElement:
3782 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003783 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003784 return Sema::AA_Initializing;
3785 }
3786
3787 return Sema::AA_Converting;
3788}
3789
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003790/// \brief Whether we should binding a created object as a temporary when
3791/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003792static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003793 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003794 case InitializedEntity::EK_ArrayElement:
3795 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003796 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003797 case InitializedEntity::EK_New:
3798 case InitializedEntity::EK_Variable:
3799 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003800 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003801 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003802 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003803 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003804 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003805
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003806 case InitializedEntity::EK_Parameter:
3807 case InitializedEntity::EK_Temporary:
3808 return true;
3809 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003810
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003811 llvm_unreachable("missed an InitializedEntity kind?");
3812}
3813
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003814/// \brief Whether the given entity, when initialized with an object
3815/// created for that initialization, requires destruction.
3816static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3817 switch (Entity.getKind()) {
3818 case InitializedEntity::EK_Member:
3819 case InitializedEntity::EK_Result:
3820 case InitializedEntity::EK_New:
3821 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003822 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003823 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003824 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003825 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003827 case InitializedEntity::EK_Variable:
3828 case InitializedEntity::EK_Parameter:
3829 case InitializedEntity::EK_Temporary:
3830 case InitializedEntity::EK_ArrayElement:
3831 case InitializedEntity::EK_Exception:
3832 return true;
3833 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003834
3835 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003836}
3837
Douglas Gregor523d46a2010-04-18 07:40:54 +00003838/// \brief Make a (potentially elidable) temporary copy of the object
3839/// provided by the given initializer by calling the appropriate copy
3840/// constructor.
3841///
3842/// \param S The Sema object used for type-checking.
3843///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003844/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003845/// the type of the initializer expression or a superclass thereof.
3846///
3847/// \param Enter The entity being initialized.
3848///
3849/// \param CurInit The initializer expression.
3850///
3851/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3852/// is permitted in C++03 (but not C++0x) when binding a reference to
3853/// an rvalue.
3854///
3855/// \returns An expression that copies the initializer expression into
3856/// a temporary object, or an error expression if a copy could not be
3857/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003858static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003859 QualType T,
3860 const InitializedEntity &Entity,
3861 ExprResult CurInit,
3862 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003863 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003864 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003865 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003866 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003867 Class = cast<CXXRecordDecl>(Record->getDecl());
3868 if (!Class)
3869 return move(CurInit);
3870
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003871 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003872 // When certain criteria are met, an implementation is allowed to
3873 // omit the copy/move construction of a class object, even if the
3874 // copy/move constructor and/or destructor for the object have
3875 // side effects. [...]
3876 // - when a temporary class object that has not been bound to a
3877 // reference (12.2) would be copied/moved to a class object
3878 // with the same cv-unqualified type, the copy/move operation
3879 // can be omitted by constructing the temporary object
3880 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003881 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003882 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003883 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003884 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003885 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003886 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003887 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003888 switch (Entity.getKind()) {
3889 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003890 Loc = Entity.getReturnLoc();
3891 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003892
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003893 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003894 Loc = Entity.getThrowLoc();
3895 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003897 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003898 Loc = Entity.getDecl()->getLocation();
3899 break;
3900
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003901 case InitializedEntity::EK_ArrayElement:
3902 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003903 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003904 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003905 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003906 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003907 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003908 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003909 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003910 Loc = CurInitExpr->getLocStart();
3911 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003912 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003913
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003914 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003915 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3916 return move(CurInit);
3917
Douglas Gregorcc15f012011-01-21 19:38:21 +00003918 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003919 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003920 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003921 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003922 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003923 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003924 // C++0x [dcl.init]p16, second bullet to class types, this
3925 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003926 CXXConstructorDecl *Constructor = 0;
3927
3928 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003929 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003930 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003931 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003932 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003933 continue;
3934
3935 DeclAccessPair FoundDecl
3936 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3937 S.AddOverloadCandidate(Constructor, FoundDecl,
3938 &CurInitExpr, 1, CandidateSet);
3939 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003940 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003941
3942 // Handle constructor templates.
3943 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3944 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003945 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003946
Douglas Gregor6493cc52010-11-08 17:16:59 +00003947 Constructor = cast<CXXConstructorDecl>(
3948 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003949 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003950 continue;
3951
3952 // FIXME: Do we need to limit this to copy-constructor-like
3953 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003954 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003955 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3956 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3957 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003958 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003959
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003960 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003961 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003962 case OR_Success:
3963 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003964
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003965 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003966 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3967 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3968 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003969 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003970 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003971 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003972 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003973 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003974 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003975
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003976 case OR_Ambiguous:
3977 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003978 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003979 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003980 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003981 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003982
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003983 case OR_Deleted:
3984 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003985 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003986 << CurInitExpr->getSourceRange();
3987 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00003988 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003989 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003990 }
3991
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003992 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003993 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003994 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003995
Anders Carlsson9a68a672010-04-21 18:47:17 +00003996 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003997 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003998
3999 if (IsExtraneousCopy) {
4000 // If this is a totally extraneous copy for C++03 reference
4001 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004002 // expression. We don't generate an (elided) copy operation here
4003 // because doing so would require us to pass down a flag to avoid
4004 // infinite recursion, where each step adds another extraneous,
4005 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004006
Douglas Gregor2559a702010-04-18 07:57:34 +00004007 // Instantiate the default arguments of any extra parameters in
4008 // the selected copy constructor, as if we were going to create a
4009 // proper call to the copy constructor.
4010 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4011 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4012 if (S.RequireCompleteType(Loc, Parm->getType(),
4013 S.PDiag(diag::err_call_incomplete_argument)))
4014 break;
4015
4016 // Build the default argument expression; we don't actually care
4017 // if this succeeds or not, because this routine will complain
4018 // if there was a problem.
4019 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4020 }
4021
Douglas Gregor523d46a2010-04-18 07:40:54 +00004022 return S.Owned(CurInitExpr);
4023 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004024
Chandler Carruth25ca4212011-02-25 19:41:05 +00004025 S.MarkDeclarationReferenced(Loc, Constructor);
4026
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004027 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004028 // constructor call (we might have derived-to-base conversions, or
4029 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004030 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004031 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004032 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004033
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004034 // Actually perform the constructor call.
4035 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004036 move_arg(ConstructorArgs),
4037 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004038 CXXConstructExpr::CK_Complete,
4039 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004040
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004041 // If we're supposed to bind temporaries, do so.
4042 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4043 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4044 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004045}
Douglas Gregor20093b42009-12-09 23:02:17 +00004046
Douglas Gregora41a8c52010-04-22 00:20:18 +00004047void InitializationSequence::PrintInitLocationNote(Sema &S,
4048 const InitializedEntity &Entity) {
4049 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4050 if (Entity.getDecl()->getLocation().isInvalid())
4051 return;
4052
4053 if (Entity.getDecl()->getDeclName())
4054 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4055 << Entity.getDecl()->getDeclName();
4056 else
4057 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4058 }
4059}
4060
Sebastian Redl3b802322011-07-14 19:07:55 +00004061static bool isReferenceBinding(const InitializationSequence::Step &s) {
4062 return s.Kind == InitializationSequence::SK_BindReference ||
4063 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4064}
4065
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004066ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004067InitializationSequence::Perform(Sema &S,
4068 const InitializedEntity &Entity,
4069 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004070 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004071 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004072 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004073 unsigned NumArgs = Args.size();
4074 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004075 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004076 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004077
Sebastian Redl7491c492011-06-05 13:59:11 +00004078 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004079 // If the declaration is a non-dependent, incomplete array type
4080 // that has an initializer, then its type will be completed once
4081 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004082 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004083 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004084 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004085 if (const IncompleteArrayType *ArrayT
4086 = S.Context.getAsIncompleteArrayType(DeclType)) {
4087 // FIXME: We don't currently have the ability to accurately
4088 // compute the length of an initializer list without
4089 // performing full type-checking of the initializer list
4090 // (since we have to determine where braces are implicitly
4091 // introduced and such). So, we fall back to making the array
4092 // type a dependently-sized array type with no specified
4093 // bound.
4094 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4095 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004096
Douglas Gregord87b61f2009-12-10 17:56:55 +00004097 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004098 if (DeclaratorDecl *DD = Entity.getDecl()) {
4099 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4100 TypeLoc TL = TInfo->getTypeLoc();
4101 if (IncompleteArrayTypeLoc *ArrayLoc
4102 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4103 Brackets = ArrayLoc->getBracketsRange();
4104 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004105 }
4106
4107 *ResultType
4108 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4109 /*NumElts=*/0,
4110 ArrayT->getSizeModifier(),
4111 ArrayT->getIndexTypeCVRQualifiers(),
4112 Brackets);
4113 }
4114
4115 }
4116 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004117 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4118 Kind.isExplicitCast());
4119 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004120 }
4121
Sebastian Redl7491c492011-06-05 13:59:11 +00004122 // No steps means no initialization.
4123 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004124 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004125
Douglas Gregord6542d82009-12-22 15:35:07 +00004126 QualType DestType = Entity.getType().getNonReferenceType();
4127 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004128 // the same as Entity.getDecl()->getType() in cases involving type merging,
4129 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004130 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004131 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004132 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004133
John McCall60d7b3a2010-08-24 06:29:42 +00004134 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004135
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004136 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004137 // grab the only argument out the Args and place it into the "current"
4138 // initializer.
4139 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004140 case SK_ResolveAddressOfOverloadedFunction:
4141 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004142 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004143 case SK_CastDerivedToBaseLValue:
4144 case SK_BindReference:
4145 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004146 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004147 case SK_UserConversion:
4148 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004149 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004150 case SK_QualificationConversionRValue:
4151 case SK_ConversionSequence:
4152 case SK_ListInitialization:
4153 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004154 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004155 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004156 case SK_ArrayInit:
4157 case SK_PassByIndirectCopyRestore:
4158 case SK_PassByIndirectRestore:
4159 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004160 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004161 CurInit = Args.get()[0];
4162 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004163
4164 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004165 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4166 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4167 if (CurInit.isInvalid())
4168 return ExprError();
4169 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004170 break;
John McCallf6a16482010-12-04 03:47:34 +00004171 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004172
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004173 case SK_ConstructorInitialization:
4174 case SK_ZeroInitialization:
4175 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004176 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004177
4178 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004179 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004180 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004181 for (step_iterator Step = step_begin(), StepEnd = step_end();
4182 Step != StepEnd; ++Step) {
4183 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004184 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004185
John Wiegley429bb272011-04-08 18:41:53 +00004186 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004187
Douglas Gregor20093b42009-12-09 23:02:17 +00004188 switch (Step->Kind) {
4189 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004190 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004191 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004192 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004193 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004194 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004195 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004196 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004197 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004198
Douglas Gregor20093b42009-12-09 23:02:17 +00004199 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004200 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004201 case SK_CastDerivedToBaseLValue: {
4202 // We have a derived-to-base cast that produces either an rvalue or an
4203 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004204
John McCallf871d0c2010-08-07 06:22:56 +00004205 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004206
Douglas Gregor20093b42009-12-09 23:02:17 +00004207 // Casts to inaccessible base classes are allowed with C-style casts.
4208 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4209 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004210 CurInit.get()->getLocStart(),
4211 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004212 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004213 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004214
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004215 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4216 QualType T = SourceType;
4217 if (const PointerType *Pointer = T->getAs<PointerType>())
4218 T = Pointer->getPointeeType();
4219 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004220 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004221 cast<CXXRecordDecl>(RecordTy->getDecl()));
4222 }
4223
John McCall5baba9d2010-08-25 10:28:54 +00004224 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004225 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004226 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004227 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004228 VK_XValue :
4229 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004230 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4231 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004232 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004233 CurInit.get(),
4234 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004235 break;
4236 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004237
Douglas Gregor20093b42009-12-09 23:02:17 +00004238 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004239 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004240 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4241 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004242 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004243 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004244 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004245 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004246 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004247 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004248
John Wiegley429bb272011-04-08 18:41:53 +00004249 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004250 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004251 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4252 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004253 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004254 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004255 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004256 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004257
Douglas Gregor20093b42009-12-09 23:02:17 +00004258 // Reference binding does not have any corresponding ASTs.
4259
4260 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004261 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004262 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004263
Douglas Gregor20093b42009-12-09 23:02:17 +00004264 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004265
Douglas Gregor20093b42009-12-09 23:02:17 +00004266 case SK_BindReferenceToTemporary:
4267 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004268 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004269 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004270
Douglas Gregor03e80032011-06-21 17:03:29 +00004271 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004272 CurInit = new (S.Context) MaterializeTemporaryExpr(
4273 Entity.getType().getNonReferenceType(),
4274 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004275 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004276
4277 // If we're binding to an Objective-C object that has lifetime, we
4278 // need cleanups.
4279 if (S.getLangOptions().ObjCAutoRefCount &&
4280 CurInit.get()->getType()->isObjCLifetimeType())
4281 S.ExprNeedsCleanups = true;
4282
Douglas Gregor20093b42009-12-09 23:02:17 +00004283 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004284
Douglas Gregor523d46a2010-04-18 07:40:54 +00004285 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004286 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004287 /*IsExtraneousCopy=*/true);
4288 break;
4289
Douglas Gregor20093b42009-12-09 23:02:17 +00004290 case SK_UserConversion: {
4291 // We have a user-defined conversion that invokes either a constructor
4292 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004293 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004294 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004295 FunctionDecl *Fn = Step->Function.Function;
4296 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004297 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004298 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004299 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004300 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004301 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004302 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004303 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004304
Douglas Gregor20093b42009-12-09 23:02:17 +00004305 // Determine the arguments required to actually perform the constructor
4306 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004307 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004308 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004309 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004310 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004311 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004312
Douglas Gregor20093b42009-12-09 23:02:17 +00004313 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004315 move_arg(ConstructorArgs),
4316 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004317 CXXConstructExpr::CK_Complete,
4318 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004319 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004320 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004321
Anders Carlsson9a68a672010-04-21 18:47:17 +00004322 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004323 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004324 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004325
John McCall2de56d12010-08-25 11:45:40 +00004326 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004327 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4328 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4329 S.IsDerivedFrom(SourceType, Class))
4330 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004331
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004332 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004333 } else {
4334 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004335 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004336 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004337 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004338 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004339 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004340
4341 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004342 // derived-to-base conversion? I believe the answer is "no", because
4343 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004344 ExprResult CurInitExprRes =
4345 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4346 FoundFn, Conversion);
4347 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004348 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004349 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004350
Douglas Gregor20093b42009-12-09 23:02:17 +00004351 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004352 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004353 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004354 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004355
John McCall2de56d12010-08-25 11:45:40 +00004356 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004357
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004358 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004359 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004360
Sebastian Redl3b802322011-07-14 19:07:55 +00004361 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004362 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004363 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004364 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004365 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004366 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004367 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004368 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004369 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004370 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004371 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4372 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004373 }
4374 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004375
Sebastian Redl906082e2010-07-20 04:20:21 +00004376 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004377 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004378 CurInit.get()->getType(),
4379 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004380 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004381
Douglas Gregor2f599792010-04-02 18:24:57 +00004382 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004383 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4384 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004385
Douglas Gregor20093b42009-12-09 23:02:17 +00004386 break;
4387 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004388
Douglas Gregor20093b42009-12-09 23:02:17 +00004389 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004390 case SK_QualificationConversionXValue:
4391 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004392 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004393 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004394 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004395 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004396 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004397 VK_XValue :
4398 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004399 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004400 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004401 }
4402
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004403 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004404 Sema::CheckedConversionKind CCK
4405 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4406 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4407 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4408 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004409 ExprResult CurInitExprRes =
4410 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004411 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004412 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004413 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004414 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004415 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004416 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004417
Douglas Gregord87b61f2009-12-10 17:56:55 +00004418 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004419 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004420 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00004421 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00004422 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004423
4424 CurInit.release();
4425 CurInit = S.Owned(InitList);
4426 break;
4427 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004428
4429 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004430 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004431 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004432 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004433
Douglas Gregor51c56d62009-12-14 20:49:26 +00004434 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004435 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004436 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4437 ? Kind.getEqualLoc()
4438 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004439
4440 if (Kind.getKind() == InitializationKind::IK_Default) {
4441 // Force even a trivial, implicit default constructor to be
4442 // semantically checked. We do this explicitly because we don't build
4443 // the definition for completely trivial constructors.
4444 CXXRecordDecl *ClassDecl = Constructor->getParent();
4445 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004446 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004447 ClassDecl->hasTrivialDefaultConstructor() &&
4448 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004449 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4450 }
4451
Douglas Gregor51c56d62009-12-14 20:49:26 +00004452 // Determine the arguments required to actually perform the constructor
4453 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004454 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004455 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004456 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457
4458
Douglas Gregor91be6f52010-03-02 17:18:33 +00004459 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004460 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004461 (Kind.getKind() == InitializationKind::IK_Direct ||
4462 Kind.getKind() == InitializationKind::IK_Value)) {
4463 // An explicitly-constructed temporary, e.g., X(1, 2).
4464 unsigned NumExprs = ConstructorArgs.size();
4465 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004466 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004467 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004468
Douglas Gregorab6677e2010-09-08 00:15:04 +00004469 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4470 if (!TSInfo)
4471 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004472
Douglas Gregor91be6f52010-03-02 17:18:33 +00004473 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4474 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004475 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004476 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004477 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004478 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004479 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004480 } else {
4481 CXXConstructExpr::ConstructionKind ConstructKind =
4482 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004483
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004484 if (Entity.getKind() == InitializedEntity::EK_Base) {
4485 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004486 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004487 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004488 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004489 ConstructKind = CXXConstructExpr::CK_Delegating;
4490 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004491
Chandler Carruth428edaf2010-10-25 08:47:36 +00004492 // Only get the parenthesis range if it is a direct construction.
4493 SourceRange parenRange =
4494 Kind.getKind() == InitializationKind::IK_Direct ?
4495 Kind.getParenRange() : SourceRange();
4496
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004497 // If the entity allows NRVO, mark the construction as elidable
4498 // unconditionally.
4499 if (Entity.allowsNRVO())
4500 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4501 Constructor, /*Elidable=*/true,
4502 move_arg(ConstructorArgs),
4503 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004504 ConstructKind,
4505 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004506 else
4507 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004509 move_arg(ConstructorArgs),
4510 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004511 ConstructKind,
4512 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004513 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004514 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004515 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004516
4517 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004518 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004519 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004520 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004521
Douglas Gregor2f599792010-04-02 18:24:57 +00004522 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004523 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004524
Douglas Gregor51c56d62009-12-14 20:49:26 +00004525 break;
4526 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004527
Douglas Gregor71d17402009-12-15 00:01:57 +00004528 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004529 step_iterator NextStep = Step;
4530 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004531 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004532 NextStep->Kind == SK_ConstructorInitialization) {
4533 // The need for zero-initialization is recorded directly into
4534 // the call to the object's constructor within the next step.
4535 ConstructorInitRequiresZeroInit = true;
4536 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4537 S.getLangOptions().CPlusPlus &&
4538 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004539 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4540 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004541 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004542 Kind.getRange().getBegin());
4543
4544 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4545 TSInfo->getType().getNonLValueExprType(S.Context),
4546 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004547 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004548 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004549 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004550 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004551 break;
4552 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004553
4554 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004555 QualType SourceType = CurInit.get()->getType();
4556 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004557 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004558 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4559 if (Result.isInvalid())
4560 return ExprError();
4561 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004562
4563 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004564 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004565 if (ConvTy != Sema::Compatible &&
4566 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004567 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004568 == Sema::Compatible)
4569 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004570 if (CurInitExprRes.isInvalid())
4571 return ExprError();
4572 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004573
Douglas Gregora41a8c52010-04-22 00:20:18 +00004574 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004575 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4576 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004577 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004578 getAssignmentAction(Entity),
4579 &Complained)) {
4580 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004581 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004582 } else if (Complained)
4583 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004584 break;
4585 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004586
4587 case SK_StringInit: {
4588 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004589 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004590 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004591 break;
4592 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004593
4594 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004595 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004596 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004597 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004598 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004599
4600 case SK_ArrayInit:
4601 // Okay: we checked everything before creating this step. Note that
4602 // this is a GNU extension.
4603 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004604 << Step->Type << CurInit.get()->getType()
4605 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004606
4607 // If the destination type is an incomplete array type, update the
4608 // type accordingly.
4609 if (ResultType) {
4610 if (const IncompleteArrayType *IncompleteDest
4611 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4612 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004613 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004614 *ResultType = S.Context.getConstantArrayType(
4615 IncompleteDest->getElementType(),
4616 ConstantSource->getSize(),
4617 ArrayType::Normal, 0);
4618 }
4619 }
4620 }
John McCallf85e1932011-06-15 23:02:42 +00004621 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004622
John McCallf85e1932011-06-15 23:02:42 +00004623 case SK_PassByIndirectCopyRestore:
4624 case SK_PassByIndirectRestore:
4625 checkIndirectCopyRestoreSource(S, CurInit.get());
4626 CurInit = S.Owned(new (S.Context)
4627 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4628 Step->Kind == SK_PassByIndirectCopyRestore));
4629 break;
4630
4631 case SK_ProduceObjCObject:
4632 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4633 CK_ObjCProduceObject,
4634 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004635 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004636 }
4637 }
John McCall15d7d122010-11-11 03:21:53 +00004638
4639 // Diagnose non-fatal problems with the completed initialization.
4640 if (Entity.getKind() == InitializedEntity::EK_Member &&
4641 cast<FieldDecl>(Entity.getDecl())->isBitField())
4642 S.CheckBitFieldInitialization(Kind.getLocation(),
4643 cast<FieldDecl>(Entity.getDecl()),
4644 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004645
Douglas Gregor20093b42009-12-09 23:02:17 +00004646 return move(CurInit);
4647}
4648
4649//===----------------------------------------------------------------------===//
4650// Diagnose initialization failures
4651//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004652bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004653 const InitializedEntity &Entity,
4654 const InitializationKind &Kind,
4655 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004656 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004657 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658
Douglas Gregord6542d82009-12-22 15:35:07 +00004659 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004660 switch (Failure) {
4661 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004662 // FIXME: Customize for the initialized entity?
4663 if (NumArgs == 0)
4664 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4665 << DestType.getNonReferenceType();
4666 else // FIXME: diagnostic below could be better!
4667 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4668 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004669 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004670
Douglas Gregor20093b42009-12-09 23:02:17 +00004671 case FK_ArrayNeedsInitList:
4672 case FK_ArrayNeedsInitListOrStringLiteral:
4673 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4674 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4675 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004676
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004677 case FK_ArrayTypeMismatch:
4678 case FK_NonConstantArrayInit:
4679 S.Diag(Kind.getLocation(),
4680 (Failure == FK_ArrayTypeMismatch
4681 ? diag::err_array_init_different_type
4682 : diag::err_array_init_non_constant_array))
4683 << DestType.getNonReferenceType()
4684 << Args[0]->getType()
4685 << Args[0]->getSourceRange();
4686 break;
4687
John McCall6bb80172010-03-30 21:47:33 +00004688 case FK_AddressOfOverloadFailed: {
4689 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004690 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004691 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004692 true,
4693 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004694 break;
John McCall6bb80172010-03-30 21:47:33 +00004695 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004696
Douglas Gregor20093b42009-12-09 23:02:17 +00004697 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004698 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004699 switch (FailedOverloadResult) {
4700 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004701 if (Failure == FK_UserConversionOverloadFailed)
4702 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4703 << Args[0]->getType() << DestType
4704 << Args[0]->getSourceRange();
4705 else
4706 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4707 << DestType << Args[0]->getType()
4708 << Args[0]->getSourceRange();
4709
John McCall120d63c2010-08-24 20:38:10 +00004710 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004711 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004712
Douglas Gregor20093b42009-12-09 23:02:17 +00004713 case OR_No_Viable_Function:
4714 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4715 << Args[0]->getType() << DestType.getNonReferenceType()
4716 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004717 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004718 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004719
Douglas Gregor20093b42009-12-09 23:02:17 +00004720 case OR_Deleted: {
4721 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4722 << Args[0]->getType() << DestType.getNonReferenceType()
4723 << Args[0]->getSourceRange();
4724 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004725 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004726 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4727 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004728 if (Ovl == OR_Deleted) {
4729 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004730 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004731 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004732 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004733 }
4734 break;
4735 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004736
Douglas Gregor20093b42009-12-09 23:02:17 +00004737 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004738 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004739 break;
4740 }
4741 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004742
Douglas Gregor20093b42009-12-09 23:02:17 +00004743 case FK_NonConstLValueReferenceBindingToTemporary:
4744 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004745 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004746 Failure == FK_NonConstLValueReferenceBindingToTemporary
4747 ? diag::err_lvalue_reference_bind_to_temporary
4748 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004749 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004750 << DestType.getNonReferenceType()
4751 << Args[0]->getType()
4752 << Args[0]->getSourceRange();
4753 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004754
Douglas Gregor20093b42009-12-09 23:02:17 +00004755 case FK_RValueReferenceBindingToLValue:
4756 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004757 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004758 << Args[0]->getSourceRange();
4759 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004760
Douglas Gregor20093b42009-12-09 23:02:17 +00004761 case FK_ReferenceInitDropsQualifiers:
4762 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4763 << DestType.getNonReferenceType()
4764 << Args[0]->getType()
4765 << Args[0]->getSourceRange();
4766 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004767
Douglas Gregor20093b42009-12-09 23:02:17 +00004768 case FK_ReferenceInitFailed:
4769 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4770 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004771 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004772 << Args[0]->getType()
4773 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004774 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4775 Args[0]->getType()->isObjCObjectPointerType())
4776 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004777 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004778
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004779 case FK_ConversionFailed: {
4780 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004781 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4782 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004783 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004784 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004785 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004786 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004787 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4788 Args[0]->getType()->isObjCObjectPointerType())
4789 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004790 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004791 }
John Wiegley429bb272011-04-08 18:41:53 +00004792
4793 case FK_ConversionFromPropertyFailed:
4794 // No-op. This error has already been reported.
4795 break;
4796
Douglas Gregord87b61f2009-12-10 17:56:55 +00004797 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004798 SourceRange R;
4799
4800 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004801 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004802 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004803 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004804 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004805
Douglas Gregor19311e72010-09-08 21:40:08 +00004806 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4807 if (Kind.isCStyleOrFunctionalCast())
4808 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4809 << R;
4810 else
4811 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4812 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004813 break;
4814 }
4815
4816 case FK_ReferenceBindingToInitList:
4817 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4818 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4819 break;
4820
4821 case FK_InitListBadDestinationType:
4822 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4823 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4824 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004825
Douglas Gregor51c56d62009-12-14 20:49:26 +00004826 case FK_ConstructorOverloadFailed: {
4827 SourceRange ArgsRange;
4828 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004829 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004830 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004831
Douglas Gregor51c56d62009-12-14 20:49:26 +00004832 // FIXME: Using "DestType" for the entity we're printing is probably
4833 // bad.
4834 switch (FailedOverloadResult) {
4835 case OR_Ambiguous:
4836 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4837 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004838 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4839 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004840 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004841
Douglas Gregor51c56d62009-12-14 20:49:26 +00004842 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004843 if (Kind.getKind() == InitializationKind::IK_Default &&
4844 (Entity.getKind() == InitializedEntity::EK_Base ||
4845 Entity.getKind() == InitializedEntity::EK_Member) &&
4846 isa<CXXConstructorDecl>(S.CurContext)) {
4847 // This is implicit default initialization of a member or
4848 // base within a constructor. If no viable function was
4849 // found, notify the user that she needs to explicitly
4850 // initialize this base/member.
4851 CXXConstructorDecl *Constructor
4852 = cast<CXXConstructorDecl>(S.CurContext);
4853 if (Entity.getKind() == InitializedEntity::EK_Base) {
4854 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4855 << Constructor->isImplicit()
4856 << S.Context.getTypeDeclType(Constructor->getParent())
4857 << /*base=*/0
4858 << Entity.getType();
4859
4860 RecordDecl *BaseDecl
4861 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4862 ->getDecl();
4863 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4864 << S.Context.getTagDeclType(BaseDecl);
4865 } else {
4866 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4867 << Constructor->isImplicit()
4868 << S.Context.getTypeDeclType(Constructor->getParent())
4869 << /*member=*/1
4870 << Entity.getName();
4871 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4872
4873 if (const RecordType *Record
4874 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004875 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004876 diag::note_previous_decl)
4877 << S.Context.getTagDeclType(Record->getDecl());
4878 }
4879 break;
4880 }
4881
Douglas Gregor51c56d62009-12-14 20:49:26 +00004882 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4883 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004884 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004885 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004886
Douglas Gregor51c56d62009-12-14 20:49:26 +00004887 case OR_Deleted: {
4888 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4889 << true << DestType << ArgsRange;
4890 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004891 OverloadingResult Ovl
4892 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004893 if (Ovl == OR_Deleted) {
4894 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004895 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004896 } else {
4897 llvm_unreachable("Inconsistent overload resolution?");
4898 }
4899 break;
4900 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004901
Douglas Gregor51c56d62009-12-14 20:49:26 +00004902 case OR_Success:
4903 llvm_unreachable("Conversion did not fail!");
4904 break;
4905 }
4906 break;
4907 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004908
Douglas Gregor99a2e602009-12-16 01:38:02 +00004909 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004910 if (Entity.getKind() == InitializedEntity::EK_Member &&
4911 isa<CXXConstructorDecl>(S.CurContext)) {
4912 // This is implicit default-initialization of a const member in
4913 // a constructor. Complain that it needs to be explicitly
4914 // initialized.
4915 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4916 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4917 << Constructor->isImplicit()
4918 << S.Context.getTypeDeclType(Constructor->getParent())
4919 << /*const=*/1
4920 << Entity.getName();
4921 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4922 << Entity.getName();
4923 } else {
4924 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4925 << DestType << (bool)DestType->getAs<RecordType>();
4926 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004927 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004928
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004929 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004930 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004931 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004932 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004933 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004934
Douglas Gregora41a8c52010-04-22 00:20:18 +00004935 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004936 return true;
4937}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004938
Chris Lattner5f9e2722011-07-23 10:55:15 +00004939void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004940 switch (SequenceKind) {
4941 case FailedSequence: {
4942 OS << "Failed sequence: ";
4943 switch (Failure) {
4944 case FK_TooManyInitsForReference:
4945 OS << "too many initializers for reference";
4946 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004947
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004948 case FK_ArrayNeedsInitList:
4949 OS << "array requires initializer list";
4950 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004951
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004952 case FK_ArrayNeedsInitListOrStringLiteral:
4953 OS << "array requires initializer list or string literal";
4954 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004955
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004956 case FK_ArrayTypeMismatch:
4957 OS << "array type mismatch";
4958 break;
4959
4960 case FK_NonConstantArrayInit:
4961 OS << "non-constant array initializer";
4962 break;
4963
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004964 case FK_AddressOfOverloadFailed:
4965 OS << "address of overloaded function failed";
4966 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004967
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004968 case FK_ReferenceInitOverloadFailed:
4969 OS << "overload resolution for reference initialization failed";
4970 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004971
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004972 case FK_NonConstLValueReferenceBindingToTemporary:
4973 OS << "non-const lvalue reference bound to temporary";
4974 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004975
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004976 case FK_NonConstLValueReferenceBindingToUnrelated:
4977 OS << "non-const lvalue reference bound to unrelated type";
4978 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004979
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004980 case FK_RValueReferenceBindingToLValue:
4981 OS << "rvalue reference bound to an lvalue";
4982 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004983
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004984 case FK_ReferenceInitDropsQualifiers:
4985 OS << "reference initialization drops qualifiers";
4986 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004987
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004988 case FK_ReferenceInitFailed:
4989 OS << "reference initialization failed";
4990 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004991
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004992 case FK_ConversionFailed:
4993 OS << "conversion failed";
4994 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004995
John Wiegley429bb272011-04-08 18:41:53 +00004996 case FK_ConversionFromPropertyFailed:
4997 OS << "conversion from property failed";
4998 break;
4999
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005000 case FK_TooManyInitsForScalar:
5001 OS << "too many initializers for scalar";
5002 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005003
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005004 case FK_ReferenceBindingToInitList:
5005 OS << "referencing binding to initializer list";
5006 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005007
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005008 case FK_InitListBadDestinationType:
5009 OS << "initializer list for non-aggregate, non-scalar type";
5010 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005011
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005012 case FK_UserConversionOverloadFailed:
5013 OS << "overloading failed for user-defined conversion";
5014 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005016 case FK_ConstructorOverloadFailed:
5017 OS << "constructor overloading failed";
5018 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005019
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005020 case FK_DefaultInitOfConst:
5021 OS << "default initialization of a const variable";
5022 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005023
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005024 case FK_Incomplete:
5025 OS << "initialization of incomplete type";
5026 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005027 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005028 OS << '\n';
5029 return;
5030 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005031
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005032 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005033 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005034 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005035
Sebastian Redl7491c492011-06-05 13:59:11 +00005036 case NormalSequence:
5037 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005038 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005040
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005041 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5042 if (S != step_begin()) {
5043 OS << " -> ";
5044 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005045
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005046 switch (S->Kind) {
5047 case SK_ResolveAddressOfOverloadedFunction:
5048 OS << "resolve address of overloaded function";
5049 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005050
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005051 case SK_CastDerivedToBaseRValue:
5052 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5053 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005054
Sebastian Redl906082e2010-07-20 04:20:21 +00005055 case SK_CastDerivedToBaseXValue:
5056 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5057 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005058
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005059 case SK_CastDerivedToBaseLValue:
5060 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5061 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005062
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005063 case SK_BindReference:
5064 OS << "bind reference to lvalue";
5065 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005066
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005067 case SK_BindReferenceToTemporary:
5068 OS << "bind reference to a temporary";
5069 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005070
Douglas Gregor523d46a2010-04-18 07:40:54 +00005071 case SK_ExtraneousCopyToTemporary:
5072 OS << "extraneous C++03 copy to temporary";
5073 break;
5074
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005075 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00005076 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005077 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005078
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005079 case SK_QualificationConversionRValue:
5080 OS << "qualification conversion (rvalue)";
5081
Sebastian Redl906082e2010-07-20 04:20:21 +00005082 case SK_QualificationConversionXValue:
5083 OS << "qualification conversion (xvalue)";
5084
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005085 case SK_QualificationConversionLValue:
5086 OS << "qualification conversion (lvalue)";
5087 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005088
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005089 case SK_ConversionSequence:
5090 OS << "implicit conversion sequence (";
5091 S->ICS->DebugPrint(); // FIXME: use OS
5092 OS << ")";
5093 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005094
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005095 case SK_ListInitialization:
5096 OS << "list initialization";
5097 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005098
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005099 case SK_ConstructorInitialization:
5100 OS << "constructor initialization";
5101 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005102
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005103 case SK_ZeroInitialization:
5104 OS << "zero initialization";
5105 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005106
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005107 case SK_CAssignment:
5108 OS << "C assignment";
5109 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005110
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005111 case SK_StringInit:
5112 OS << "string initialization";
5113 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005114
5115 case SK_ObjCObjectConversion:
5116 OS << "Objective-C object conversion";
5117 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005118
5119 case SK_ArrayInit:
5120 OS << "array initialization";
5121 break;
John McCallf85e1932011-06-15 23:02:42 +00005122
5123 case SK_PassByIndirectCopyRestore:
5124 OS << "pass by indirect copy and restore";
5125 break;
5126
5127 case SK_PassByIndirectRestore:
5128 OS << "pass by indirect restore";
5129 break;
5130
5131 case SK_ProduceObjCObject:
5132 OS << "Objective-C object retension";
5133 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005134 }
5135 }
5136}
5137
5138void InitializationSequence::dump() const {
5139 dump(llvm::errs());
5140}
5141
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005142static void DiagnoseNarrowingInInitList(
5143 Sema& S, QualType EntityType, const Expr *InitE,
5144 bool Constant, const APValue &ConstantValue) {
5145 if (Constant) {
5146 S.Diag(InitE->getLocStart(),
5147 S.getLangOptions().CPlusPlus0x
5148 ? diag::err_init_list_constant_narrowing
5149 : diag::warn_init_list_constant_narrowing)
5150 << InitE->getSourceRange()
5151 << ConstantValue
5152 << EntityType;
5153 } else
5154 S.Diag(InitE->getLocStart(),
5155 S.getLangOptions().CPlusPlus0x
5156 ? diag::err_init_list_variable_narrowing
5157 : diag::warn_init_list_variable_narrowing)
5158 << InitE->getSourceRange()
5159 << InitE->getType()
5160 << EntityType;
5161
5162 llvm::SmallString<128> StaticCast;
5163 llvm::raw_svector_ostream OS(StaticCast);
5164 OS << "static_cast<";
5165 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5166 // It's important to use the typedef's name if there is one so that the
5167 // fixit doesn't break code using types like int64_t.
5168 //
5169 // FIXME: This will break if the typedef requires qualification. But
5170 // getQualifiedNameAsString() includes non-machine-parsable components.
5171 OS << TT->getDecl();
5172 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5173 OS << BT->getName(S.getLangOptions());
5174 else {
5175 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5176 // with a broken cast.
5177 return;
5178 }
5179 OS << ">(";
5180 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5181 << InitE->getSourceRange()
5182 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5183 << FixItHint::CreateInsertion(
5184 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5185}
5186
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005187//===----------------------------------------------------------------------===//
5188// Initialization helper functions
5189//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005190bool
5191Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5192 ExprResult Init) {
5193 if (Init.isInvalid())
5194 return false;
5195
5196 Expr *InitE = Init.get();
5197 assert(InitE && "No initialization expression");
5198
5199 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5200 SourceLocation());
5201 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005202 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005203}
5204
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005205ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005206Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5207 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005208 ExprResult Init,
5209 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005210 if (Init.isInvalid())
5211 return ExprError();
5212
John McCall15d7d122010-11-11 03:21:53 +00005213 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005214 assert(InitE && "No initialization expression?");
5215
5216 if (EqualLoc.isInvalid())
5217 EqualLoc = InitE->getLocStart();
5218
5219 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5220 EqualLoc);
5221 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5222 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005223
5224 bool Constant = false;
5225 APValue Result;
5226 if (TopLevelOfInitList &&
5227 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5228 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5229 Constant, Result);
5230 }
John McCallf312b1e2010-08-26 23:41:50 +00005231 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005232}