blob: 9458e3580c3eb661347c70efc657cad4dd9a106d [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Steve Naroff0cca7492008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattner79e079d2009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman8718a6a2009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner8879e3b2009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000057
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000064 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 return 0;
67}
68
Chris Lattner79e079d2009-02-24 23:10:27 +000069static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
70 // Get the length of the string as parsed.
71 uint64_t StrLength =
72 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
73
Mike Stump1eb44332009-09-09 15:08:12 +000074
Chris Lattner79e079d2009-02-24 23:10:27 +000075 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000077 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000078 // being initialized to a string literal.
79 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000080 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000081 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000082 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
83 ConstVal,
84 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000085 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086 }
Mike Stump1eb44332009-09-09 15:08:12 +000087
Eli Friedman8718a6a2009-05-29 18:22:49 +000088 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000089
Eli Friedman8718a6a2009-05-29 18:22:49 +000090 // C99 6.7.8p14. We have an array of character type with known size. However,
91 // the size may be smaller or larger than the string we are initializing.
92 // FIXME: Avoid truncation for 64-bit length strings.
93 if (StrLength-1 > CAT->getSize().getZExtValue())
94 S.Diag(Str->getSourceRange().getBegin(),
95 diag::warn_initializer_string_for_char_array_too_long)
96 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000097
Eli Friedman8718a6a2009-05-29 18:22:49 +000098 // Set the type to the actual size that we are initializing. If we have
99 // something like:
100 // char x[1] = "foo";
101 // then this will set the string literal's type to char[1].
102 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000103}
104
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000105//===----------------------------------------------------------------------===//
106// Semantic checking for initializer lists.
107//===----------------------------------------------------------------------===//
108
Douglas Gregor9e80f722009-01-29 01:05:33 +0000109/// @brief Semantic checking for initializer lists.
110///
111/// The InitListChecker class contains a set of routines that each
112/// handle the initialization of a certain kind of entity, e.g.,
113/// arrays, vectors, struct/union types, scalars, etc. The
114/// InitListChecker itself performs a recursive walk of the subobject
115/// structure of the type to be initialized, while stepping through
116/// the initializer list one element at a time. The IList and Index
117/// parameters to each of the Check* routines contain the active
118/// (syntactic) initializer list and the index into that initializer
119/// list that represents the current initializer. Each routine is
120/// responsible for moving that Index forward as it consumes elements.
121///
122/// Each Check* routine also has a StructuredList/StructuredIndex
123/// arguments, which contains the current the "structured" (semantic)
124/// initializer list and the index into that initializer list where we
125/// are copying initializers as we map them over to the semantic
126/// list. Once we have completed our recursive walk of the subobject
127/// structure, we will have constructed a full semantic initializer
128/// list.
129///
130/// C99 designators cause changes in the initializer list traversal,
131/// because they make the initialization "jump" into a specific
132/// subobject and then continue the initialization from that
133/// point. CheckDesignatedInitializer() recursively steps into the
134/// designated subobject and manages backing out the recursion to
135/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000136namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000137class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000138 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000139 bool hadError;
140 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
141 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000143 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000144 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000145 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000146 unsigned &StructuredIndex,
147 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000148 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000149 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000153 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000155 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000156 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000158 unsigned &StructuredIndex,
159 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000160 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000161 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000162 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000163 InitListExpr *StructuredList,
164 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000165 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000170 void CheckReferenceType(const InitializedEntity &Entity,
171 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000172 unsigned &Index,
173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000175 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000176 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000177 InitListExpr *StructuredList,
178 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000179 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000180 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000181 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000182 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000183 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000186 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000188 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000189 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
191 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000192 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000193 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000194 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000195 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 RecordDecl::field_iterator *NextField,
197 llvm::APSInt *NextElementIndex,
198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000201 bool FinishSubobjectInit,
202 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000203 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
204 QualType CurrentObjectType,
205 InitListExpr *StructuredList,
206 unsigned StructuredIndex,
207 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 void UpdateStructuredListElement(InitListExpr *StructuredList,
209 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000210 Expr *expr);
211 int numArrayElements(QualType DeclType);
212 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000213
Douglas Gregord6d37de2009-12-22 00:05:34 +0000214 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
215 const InitializedEntity &ParentEntity,
216 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000217 void FillInValueInitializations(const InitializedEntity &Entity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000220 InitListChecker(Sema &S, const InitializedEntity &Entity,
221 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool HadError() { return hadError; }
223
224 // @brief Retrieves the fully-structured initializer list used for
225 // semantic analysis and code generation.
226 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
227};
Chris Lattner8b419b92009-02-24 22:48:58 +0000228} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000229
Douglas Gregord6d37de2009-12-22 00:05:34 +0000230void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
231 const InitializedEntity &ParentEntity,
232 InitListExpr *ILE,
233 bool &RequiresSecondPass) {
234 SourceLocation Loc = ILE->getSourceRange().getBegin();
235 unsigned NumInits = ILE->getNumInits();
236 InitializedEntity MemberEntity
237 = InitializedEntity::InitializeMember(Field, &ParentEntity);
238 if (Init >= NumInits || !ILE->getInit(Init)) {
239 // FIXME: We probably don't need to handle references
240 // specially here, since value-initialization of references is
241 // handled in InitializationSequence.
242 if (Field->getType()->isReferenceType()) {
243 // C++ [dcl.init.aggr]p9:
244 // If an incomplete or empty initializer-list leaves a
245 // member of reference type uninitialized, the program is
246 // ill-formed.
247 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
248 << Field->getType()
249 << ILE->getSyntacticForm()->getSourceRange();
250 SemaRef.Diag(Field->getLocation(),
251 diag::note_uninit_reference_member);
252 hadError = true;
253 return;
254 }
255
256 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
257 true);
258 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
259 if (!InitSeq) {
260 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
261 hadError = true;
262 return;
263 }
264
John McCall60d7b3a2010-08-24 06:29:42 +0000265 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000266 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000267 if (MemberInit.isInvalid()) {
268 hadError = true;
269 return;
270 }
271
272 if (hadError) {
273 // Do nothing
274 } else if (Init < NumInits) {
275 ILE->setInit(Init, MemberInit.takeAs<Expr>());
276 } else if (InitSeq.getKind()
277 == InitializationSequence::ConstructorInitialization) {
278 // Value-initialization requires a constructor call, so
279 // extend the initializer list to include the constructor
280 // call and make a note that we'll need to take another pass
281 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000282 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000283 RequiresSecondPass = true;
284 }
285 } else if (InitListExpr *InnerILE
286 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
287 FillInValueInitializations(MemberEntity, InnerILE,
288 RequiresSecondPass);
289}
290
Douglas Gregor4c678342009-01-28 21:54:33 +0000291/// Recursively replaces NULL values within the given initializer list
292/// with expressions that perform value-initialization of the
293/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000294void
295InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
296 InitListExpr *ILE,
297 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000298 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000299 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000300 SourceLocation Loc = ILE->getSourceRange().getBegin();
301 if (ILE->getSyntacticForm())
302 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Ted Kremenek6217b802009-07-29 21:53:49 +0000304 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000305 if (RType->getDecl()->isUnion() &&
306 ILE->getInitializedFieldInUnion())
307 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
308 Entity, ILE, RequiresSecondPass);
309 else {
310 unsigned Init = 0;
311 for (RecordDecl::field_iterator
312 Field = RType->getDecl()->field_begin(),
313 FieldEnd = RType->getDecl()->field_end();
314 Field != FieldEnd; ++Field) {
315 if (Field->isUnnamedBitfield())
316 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000317
Douglas Gregord6d37de2009-12-22 00:05:34 +0000318 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000319 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000320
321 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
322 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000323 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000324
Douglas Gregord6d37de2009-12-22 00:05:34 +0000325 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000326
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 // Only look at the first initialization of a union.
328 if (RType->getDecl()->isUnion())
329 break;
330 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000331 }
332
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000335
336 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000338 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000339 unsigned NumInits = ILE->getNumInits();
340 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000341 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000342 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000343 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
344 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000345 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
346 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000347 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000348 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000349 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000350 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
351 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000352 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000353 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000355
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000357 if (hadError)
358 return;
359
Anders Carlssond3d824d2010-01-23 04:34:47 +0000360 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
361 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000362 ElementEntity.setElementIndex(Init);
363
Douglas Gregor87fd7032009-02-02 17:43:21 +0000364 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000365 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
366 true);
367 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
368 if (!InitSeq) {
369 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000370 hadError = true;
371 return;
372 }
373
John McCall60d7b3a2010-08-24 06:29:42 +0000374 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000375 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000376 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000377 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000378 return;
379 }
380
381 if (hadError) {
382 // Do nothing
383 } else if (Init < NumInits) {
384 ILE->setInit(Init, ElementInit.takeAs<Expr>());
385 } else if (InitSeq.getKind()
386 == InitializationSequence::ConstructorInitialization) {
387 // Value-initialization requires a constructor call, so
388 // extend the initializer list to include the constructor
389 // call and make a note that we'll need to take another pass
390 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000391 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000392 RequiresSecondPass = true;
393 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000394 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
396 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000397 }
398}
399
Chris Lattner68355a52009-01-29 05:10:57 +0000400
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
402 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000403 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000404 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000405
Eli Friedmanb85f7072008-05-19 19:16:24 +0000406 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000407 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000408 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000409 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000410 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000411 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000412 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000413
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000414 if (!hadError) {
415 bool RequiresSecondPass = false;
416 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000417 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 FillInValueInitializations(Entity, FullyStructuredList,
419 RequiresSecondPass);
420 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000421}
422
423int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000424 // FIXME: use a proper constant
425 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000426 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000427 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000428 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
429 }
430 return maxElements;
431}
432
433int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000434 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000435 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000436 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000437 Field = structDecl->field_begin(),
438 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000439 Field != FieldEnd; ++Field) {
440 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
441 ++InitializableMembers;
442 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000443 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000444 return std::min(InitializableMembers, 1);
445 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000446}
447
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000448void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000449 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000450 QualType T, unsigned &Index,
451 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000452 unsigned &StructuredIndex,
453 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000454 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Steve Naroff0cca7492008-05-01 22:18:59 +0000456 if (T->isArrayType())
457 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000458 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000460 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000461 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000462 else
463 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000464
Eli Friedman402256f2008-05-25 13:49:22 +0000465 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000466 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000467 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000468 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000469 hadError = true;
470 return;
471 }
472
Douglas Gregor4c678342009-01-28 21:54:33 +0000473 // Build a structured initializer list corresponding to this subobject.
474 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000475 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
476 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000477 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
478 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000480
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000482 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000483 CheckListElementTypes(Entity, ParentIList, T,
484 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000485 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000486 StructuredSubobjectInitIndex,
487 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000488 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000489 StructuredSubobjectInitList->setType(T);
490
Douglas Gregored8a93d2009-03-01 17:12:46 +0000491 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000492 // range corresponds with the end of the last initializer it used.
493 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000494 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000495 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
496 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
497 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000498
499 // Warn about missing braces.
500 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000501 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
502 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000503 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000504 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
505 "{")
506 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner1dcd0612010-03-07 04:47:12 +0000507 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000508 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000509 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000510}
511
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000512void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000513 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 unsigned &Index,
515 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000516 unsigned &StructuredIndex,
517 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000518 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 SyntacticToSemantic[IList] = StructuredList;
520 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000521 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
522 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000523 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
524 IList->setType(ExprTy);
525 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000526 if (hadError)
527 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000528
Eli Friedman638e1442008-05-25 13:22:35 +0000529 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000530 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000531 if (StructuredIndex == 1 &&
532 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000533 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000534 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000536 hadError = true;
537 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000538 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000539 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000540 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000541 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000542 // Don't complain for incomplete types, since we'll get an error
543 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000544 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000545 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 CurrentObjectType->isArrayType()? 0 :
547 CurrentObjectType->isVectorType()? 1 :
548 CurrentObjectType->isScalarType()? 2 :
549 CurrentObjectType->isUnionType()? 3 :
550 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000551
552 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000553 if (SemaRef.getLangOptions().CPlusPlus) {
554 DK = diag::err_excess_initializers;
555 hadError = true;
556 }
Nate Begeman08634522009-07-07 21:53:06 +0000557 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000561
Chris Lattner08202542009-02-24 22:50:46 +0000562 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000563 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000564 }
565 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000566
Eli Friedman759f2522009-05-16 11:45:48 +0000567 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000568 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000569 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000570 << FixItHint::CreateRemoval(IList->getLocStart())
571 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000572}
573
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000574void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000575 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000576 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000577 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000578 unsigned &Index,
579 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000580 unsigned &StructuredIndex,
581 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000582 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000583 CheckScalarType(Entity, IList, DeclType, Index,
584 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000585 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000586 CheckVectorType(Entity, IList, DeclType, Index,
587 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000588 } else if (DeclType->isAggregateType()) {
589 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000590 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000591 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000592 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000593 StructuredList, StructuredIndex,
594 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000595 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000596 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000597 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000598 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000599 CheckArrayType(Entity, IList, DeclType, Zero,
600 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000601 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000602 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000604 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
605 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000608 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000609 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000610 } else if (DeclType->isRecordType()) {
611 // C++ [dcl.init]p14:
612 // [...] If the class is an aggregate (8.5.1), and the initializer
613 // is a brace-enclosed list, see 8.5.1.
614 //
615 // Note: 8.5.1 is handled below; here, we diagnose the case where
616 // we have an initializer list and a destination type that is not
617 // an aggregate.
618 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000619 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000620 << DeclType << IList->getSourceRange();
621 hadError = true;
622 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000623 CheckReferenceType(Entity, IList, DeclType, Index,
624 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000625 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000626 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
627 << DeclType;
628 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000629 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000630 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
631 << DeclType;
632 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000633 }
634}
635
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000636void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000637 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000638 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 unsigned &Index,
640 InitListExpr *StructuredList,
641 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000642 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000643 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
644 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000645 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000646 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 = getStructuredSubobjectInit(IList, Index, ElemType,
648 StructuredList, StructuredIndex,
649 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000650 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000651 newStructuredList, newStructuredIndex);
652 ++StructuredIndex;
653 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000654 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
655 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000656 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000657 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000658 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000659 CheckScalarType(Entity, IList, ElemType, Index,
660 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000661 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000662 CheckReferenceType(Entity, IList, ElemType, Index,
663 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000664 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000665 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000666 // C++ [dcl.init.aggr]p12:
667 // All implicit type conversions (clause 4) are considered when
668 // initializing the aggregate member with an ini- tializer from
669 // an initializer-list. If the initializer can initialize a
670 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000671
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000672 // FIXME: Better EqualLoc?
673 InitializationKind Kind =
674 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
675 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
676
677 if (Seq) {
John McCall60d7b3a2010-08-24 06:29:42 +0000678 ExprResult Result =
John McCallf312b1e2010-08-26 23:41:50 +0000679 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000680 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000681 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000682
683 UpdateStructuredListElement(StructuredList, StructuredIndex,
684 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 ++Index;
686 return;
687 }
688
689 // Fall through for subaggregate initialization
690 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000691 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000692 //
693 // The initializer for a structure or union object that has
694 // automatic storage duration shall be either an initializer
695 // list as described below, or a single expression that has
696 // compatible structure or union type. In the latter case, the
697 // initial value of the object, including unnamed members, is
698 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000699 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000700 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000701 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
702 ++Index;
703 return;
704 }
705
706 // Fall through for subaggregate initialization
707 }
708
709 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000710 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000711 // [...] Otherwise, if the member is itself a non-empty
712 // subaggregate, brace elision is assumed and the initializer is
713 // considered for the initialization of the first member of
714 // the subaggregate.
715 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000716 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000717 StructuredIndex);
718 ++StructuredIndex;
719 } else {
720 // We cannot initialize this element, so let
721 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000722 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
723 SemaRef.Owned(expr));
Douglas Gregor930d8b52009-01-30 22:09:00 +0000724 hadError = true;
725 ++Index;
726 ++StructuredIndex;
727 }
728 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000729}
730
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000731void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000732 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000733 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000734 InitListExpr *StructuredList,
735 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000736 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000737 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000738 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000739 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000740 ++Index;
741 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000742 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000743 }
John McCallb934c2d2010-11-11 00:46:36 +0000744
745 Expr *expr = IList->getInit(Index);
746 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
747 SemaRef.Diag(SubIList->getLocStart(),
748 diag::warn_many_braces_around_scalar_init)
749 << SubIList->getSourceRange();
750
751 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
752 StructuredIndex);
753 return;
754 } else if (isa<DesignatedInitExpr>(expr)) {
755 SemaRef.Diag(expr->getSourceRange().getBegin(),
756 diag::err_designator_for_scalar_init)
757 << DeclType << expr->getSourceRange();
758 hadError = true;
759 ++Index;
760 ++StructuredIndex;
761 return;
762 }
763
764 ExprResult Result =
765 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
766 SemaRef.Owned(expr));
767
768 Expr *ResultExpr = 0;
769
770 if (Result.isInvalid())
771 hadError = true; // types weren't compatible.
772 else {
773 ResultExpr = Result.takeAs<Expr>();
774
775 if (ResultExpr != expr) {
776 // The type was promoted, update initializer list.
777 IList->setInit(Index, ResultExpr);
778 }
779 }
780 if (hadError)
781 ++StructuredIndex;
782 else
783 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
784 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000785}
786
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000787void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
788 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000789 unsigned &Index,
790 InitListExpr *StructuredList,
791 unsigned &StructuredIndex) {
792 if (Index < IList->getNumInits()) {
793 Expr *expr = IList->getInit(Index);
794 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000795 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000796 << DeclType << IList->getSourceRange();
797 hadError = true;
798 ++Index;
799 ++StructuredIndex;
800 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000801 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000802
John McCall60d7b3a2010-08-24 06:29:42 +0000803 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000804 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
805 SemaRef.Owned(expr));
806
807 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000808 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000809
810 expr = Result.takeAs<Expr>();
811 IList->setInit(Index, expr);
812
Douglas Gregor930d8b52009-01-30 22:09:00 +0000813 if (hadError)
814 ++StructuredIndex;
815 else
816 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
817 ++Index;
818 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000819 // FIXME: It would be wonderful if we could point at the actual member. In
820 // general, it would be useful to pass location information down the stack,
821 // so that we know the location (or decl) of the "current object" being
822 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000823 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000824 diag::err_init_reference_member_uninitialized)
825 << DeclType
826 << IList->getSourceRange();
827 hadError = true;
828 ++Index;
829 ++StructuredIndex;
830 return;
831 }
832}
833
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000834void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000835 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000836 unsigned &Index,
837 InitListExpr *StructuredList,
838 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000839 if (Index >= IList->getNumInits())
840 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000841
John McCall20e047a2010-10-30 00:11:39 +0000842 const VectorType *VT = DeclType->getAs<VectorType>();
843 unsigned maxElements = VT->getNumElements();
844 unsigned numEltsInit = 0;
845 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000846
John McCall20e047a2010-10-30 00:11:39 +0000847 if (!SemaRef.getLangOptions().OpenCL) {
848 // If the initializing element is a vector, try to copy-initialize
849 // instead of breaking it apart (which is doomed to failure anyway).
850 Expr *Init = IList->getInit(Index);
851 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
852 ExprResult Result =
853 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
854 SemaRef.Owned(Init));
855
856 Expr *ResultExpr = 0;
857 if (Result.isInvalid())
858 hadError = true; // types weren't compatible.
859 else {
860 ResultExpr = Result.takeAs<Expr>();
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000861
John McCall20e047a2010-10-30 00:11:39 +0000862 if (ResultExpr != Init) {
863 // The type was promoted, update initializer list.
864 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000865 }
866 }
John McCall20e047a2010-10-30 00:11:39 +0000867 if (hadError)
868 ++StructuredIndex;
869 else
870 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
871 ++Index;
872 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000873 }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
John McCall20e047a2010-10-30 00:11:39 +0000875 InitializedEntity ElementEntity =
876 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
877
878 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
879 // Don't attempt to go past the end of the init list
880 if (Index >= IList->getNumInits())
881 break;
882
883 ElementEntity.setElementIndex(Index);
884 CheckSubElementType(ElementEntity, IList, elementType, Index,
885 StructuredList, StructuredIndex);
886 }
887 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000888 }
John McCall20e047a2010-10-30 00:11:39 +0000889
890 InitializedEntity ElementEntity =
891 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
892
893 // OpenCL initializers allows vectors to be constructed from vectors.
894 for (unsigned i = 0; i < maxElements; ++i) {
895 // Don't attempt to go past the end of the init list
896 if (Index >= IList->getNumInits())
897 break;
898
899 ElementEntity.setElementIndex(Index);
900
901 QualType IType = IList->getInit(Index)->getType();
902 if (!IType->isVectorType()) {
903 CheckSubElementType(ElementEntity, IList, elementType, Index,
904 StructuredList, StructuredIndex);
905 ++numEltsInit;
906 } else {
907 QualType VecType;
908 const VectorType *IVT = IType->getAs<VectorType>();
909 unsigned numIElts = IVT->getNumElements();
910
911 if (IType->isExtVectorType())
912 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
913 else
914 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000915 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000916 CheckSubElementType(ElementEntity, IList, VecType, Index,
917 StructuredList, StructuredIndex);
918 numEltsInit += numIElts;
919 }
920 }
921
922 // OpenCL requires all elements to be initialized.
923 if (numEltsInit != maxElements)
924 if (SemaRef.getLangOptions().OpenCL)
925 SemaRef.Diag(IList->getSourceRange().getBegin(),
926 diag::err_vector_incorrect_num_initializers)
927 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000928}
929
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000930void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000931 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000932 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000933 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000934 unsigned &Index,
935 InitListExpr *StructuredList,
936 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000937 // Check for the special-case of initializing an array with a string.
938 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000939 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
940 SemaRef.Context)) {
941 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000942 // We place the string literal directly into the resulting
943 // initializer list. This is the only place where the structure
944 // of the structured initializer list doesn't match exactly,
945 // because doing so would involve allocating one character
946 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000947 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000948 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000949 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000950 return;
951 }
952 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000953 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000954 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000955 // Check for VLAs; in standard C it would be possible to check this
956 // earlier, but I don't know where clang accepts VLAs (gcc accepts
957 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000958 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000959 diag::err_variable_object_no_init)
960 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000961 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000962 ++Index;
963 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000964 return;
965 }
966
Douglas Gregor05c13a32009-01-22 00:58:24 +0000967 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000968 llvm::APSInt maxElements(elementIndex.getBitWidth(),
969 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000970 bool maxElementsKnown = false;
971 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000972 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000973 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000974 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000975 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000976 maxElementsKnown = true;
977 }
978
Chris Lattner08202542009-02-24 22:50:46 +0000979 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000980 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000981 while (Index < IList->getNumInits()) {
982 Expr *Init = IList->getInit(Index);
983 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000984 // If we're not the subobject that matches up with the '{' for
985 // the designator, we shouldn't be handling the
986 // designator. Return immediately.
987 if (!SubobjectIsDesignatorContext)
988 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000989
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000990 // Handle this designated initializer. elementIndex will be
991 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000992 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000993 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000994 StructuredList, StructuredIndex, true,
995 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000996 hadError = true;
997 continue;
998 }
999
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001000 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1001 maxElements.extend(elementIndex.getBitWidth());
1002 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1003 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001004 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001005
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001006 // If the array is of incomplete type, keep track of the number of
1007 // elements in the initializer.
1008 if (!maxElementsKnown && elementIndex > maxElements)
1009 maxElements = elementIndex;
1010
Douglas Gregor05c13a32009-01-22 00:58:24 +00001011 continue;
1012 }
1013
1014 // If we know the maximum number of elements, and we've already
1015 // hit it, stop consuming elements in the initializer list.
1016 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001017 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001018
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001019 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +00001020 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001021 Entity);
1022 // Check this element.
1023 CheckSubElementType(ElementEntity, IList, elementType, Index,
1024 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001025 ++elementIndex;
1026
1027 // If the array is of incomplete type, keep track of the number of
1028 // elements in the initializer.
1029 if (!maxElementsKnown && elementIndex > maxElements)
1030 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001031 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001032 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001033 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001034 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001035 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001036 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001037 // Sizing an array implicitly to zero is not allowed by ISO C,
1038 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001039 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001040 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001041 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001042
Mike Stump1eb44332009-09-09 15:08:12 +00001043 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001044 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001045 }
1046}
1047
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001048void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001049 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001050 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001051 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001052 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001053 unsigned &Index,
1054 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001055 unsigned &StructuredIndex,
1056 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001057 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Eli Friedmanb85f7072008-05-19 19:16:24 +00001059 // If the record is invalid, some of it's members are invalid. To avoid
1060 // confusion, we forgo checking the intializer for the entire record.
1061 if (structDecl->isInvalidDecl()) {
1062 hadError = true;
1063 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001064 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001065
1066 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1067 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001068 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001069 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001070 Field != FieldEnd; ++Field) {
1071 if (Field->getDeclName()) {
1072 StructuredList->setInitializedFieldInUnion(*Field);
1073 break;
1074 }
1075 }
1076 return;
1077 }
1078
Douglas Gregor05c13a32009-01-22 00:58:24 +00001079 // If structDecl is a forward declaration, this loop won't do
1080 // anything except look at designated initializers; That's okay,
1081 // because an error should get printed out elsewhere. It might be
1082 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001083 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001084 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001085 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001086 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001087 while (Index < IList->getNumInits()) {
1088 Expr *Init = IList->getInit(Index);
1089
1090 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001091 // If we're not the subobject that matches up with the '{' for
1092 // the designator, we shouldn't be handling the
1093 // designator. Return immediately.
1094 if (!SubobjectIsDesignatorContext)
1095 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001096
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001097 // Handle this designated initializer. Field will be updated to
1098 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001099 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001100 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001101 StructuredList, StructuredIndex,
1102 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001103 hadError = true;
1104
Douglas Gregordfb5e592009-02-12 19:00:39 +00001105 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001106
1107 // Disable check for missing fields when designators are used.
1108 // This matches gcc behaviour.
1109 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001110 continue;
1111 }
1112
1113 if (Field == FieldEnd) {
1114 // We've run out of fields. We're done.
1115 break;
1116 }
1117
Douglas Gregordfb5e592009-02-12 19:00:39 +00001118 // We've already initialized a member of a union. We're done.
1119 if (InitializedSomething && DeclType->isUnionType())
1120 break;
1121
Douglas Gregor44b43212008-12-11 16:49:14 +00001122 // If we've hit the flexible array member at the end, we're done.
1123 if (Field->getType()->isIncompleteArrayType())
1124 break;
1125
Douglas Gregor0bb76892009-01-29 16:53:55 +00001126 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001127 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001128 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001129 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001130 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001131
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001132 InitializedEntity MemberEntity =
1133 InitializedEntity::InitializeMember(*Field, &Entity);
1134 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1135 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001136 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001137
1138 if (DeclType->isUnionType()) {
1139 // Initialize the first field within the union.
1140 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001141 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001142
1143 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001144 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001145
John McCall80639de2010-03-11 19:32:38 +00001146 // Emit warnings for missing struct field initializers.
Douglas Gregor8e198902010-06-18 21:43:10 +00001147 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001148 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1149 // It is possible we have one or more unnamed bitfields remaining.
1150 // Find first (if any) named field and emit warning.
1151 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1152 it != end; ++it) {
1153 if (!it->isUnnamedBitfield()) {
1154 SemaRef.Diag(IList->getSourceRange().getEnd(),
1155 diag::warn_missing_field_initializers) << it->getName();
1156 break;
1157 }
1158 }
1159 }
1160
Mike Stump1eb44332009-09-09 15:08:12 +00001161 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001162 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001163 return;
1164
1165 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001166 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001167 (!isa<InitListExpr>(IList->getInit(Index)) ||
1168 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001169 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001170 diag::err_flexible_array_init_nonempty)
1171 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001172 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001173 << *Field;
1174 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001175 ++Index;
1176 return;
1177 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001178 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001179 diag::ext_flexible_array_init)
1180 << IList->getInit(Index)->getSourceRange().getBegin();
1181 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1182 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001183 }
1184
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001185 InitializedEntity MemberEntity =
1186 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001187
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001188 if (isa<InitListExpr>(IList->getInit(Index)))
1189 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1190 StructuredList, StructuredIndex);
1191 else
1192 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001193 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001194}
Steve Naroff0cca7492008-05-01 22:18:59 +00001195
Douglas Gregor022d13d2010-10-08 20:44:28 +00001196/// \brief Similar to Sema::BuildAnonymousStructUnionMemberPath() but builds a
1197/// relative path and has strict checks.
1198static void BuildRelativeAnonymousStructUnionMemberPath(FieldDecl *Field,
1199 llvm::SmallVectorImpl<FieldDecl *> &Path,
1200 DeclContext *BaseDC) {
1201 Path.push_back(Field);
1202 for (DeclContext *Ctx = Field->getDeclContext();
1203 !Ctx->Equals(BaseDC);
1204 Ctx = Ctx->getParent()) {
1205 ValueDecl *AnonObject =
1206 cast<RecordDecl>(Ctx)->getAnonymousStructOrUnionObject();
1207 FieldDecl *AnonField = cast<FieldDecl>(AnonObject);
1208 Path.push_back(AnonField);
1209 }
1210}
1211
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001212/// \brief Expand a field designator that refers to a member of an
1213/// anonymous struct or union into a series of field designators that
1214/// refers to the field within the appropriate subobject.
1215///
1216/// Field/FieldIndex will be updated to point to the (new)
1217/// currently-designated field.
1218static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001219 DesignatedInitExpr *DIE,
1220 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001221 FieldDecl *Field,
1222 RecordDecl::field_iterator &FieldIter,
Douglas Gregor022d13d2010-10-08 20:44:28 +00001223 unsigned &FieldIndex,
1224 DeclContext *BaseDC) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001225 typedef DesignatedInitExpr::Designator Designator;
1226
1227 // Build the path from the current object to the member of the
1228 // anonymous struct/union (backwards).
1229 llvm::SmallVector<FieldDecl *, 4> Path;
Douglas Gregor022d13d2010-10-08 20:44:28 +00001230 BuildRelativeAnonymousStructUnionMemberPath(Field, Path, BaseDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001232 // Build the replacement designators.
1233 llvm::SmallVector<Designator, 4> Replacements;
1234 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1235 FI = Path.rbegin(), FIEnd = Path.rend();
1236 FI != FIEnd; ++FI) {
1237 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001238 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001239 DIE->getDesignator(DesigIdx)->getDotLoc(),
1240 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1241 else
1242 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1243 SourceLocation()));
1244 Replacements.back().setField(*FI);
1245 }
1246
1247 // Expand the current designator into the set of replacement
1248 // designators, so we have a full subobject path down to where the
1249 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001250 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001251 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001253 // Update FieldIter/FieldIndex;
1254 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001255 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001256 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001257 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001258 FieldIter != FEnd; ++FieldIter) {
1259 if (FieldIter->isUnnamedBitfield())
1260 continue;
1261
1262 if (*FieldIter == Path.back())
1263 return;
1264
1265 ++FieldIndex;
1266 }
1267
1268 assert(false && "Unable to find anonymous struct/union field");
1269}
1270
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271/// @brief Check the well-formedness of a C99 designated initializer.
1272///
1273/// Determines whether the designated initializer @p DIE, which
1274/// resides at the given @p Index within the initializer list @p
1275/// IList, is well-formed for a current object of type @p DeclType
1276/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001277/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001278/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001279///
1280/// @param IList The initializer list in which this designated
1281/// initializer occurs.
1282///
Douglas Gregor71199712009-04-15 04:56:10 +00001283/// @param DIE The designated initializer expression.
1284///
1285/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001286///
1287/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1288/// into which the designation in @p DIE should refer.
1289///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001290/// @param NextField If non-NULL and the first designator in @p DIE is
1291/// a field, this will be set to the field declaration corresponding
1292/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001293///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001294/// @param NextElementIndex If non-NULL and the first designator in @p
1295/// DIE is an array designator or GNU array-range designator, this
1296/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001297///
1298/// @param Index Index into @p IList where the designated initializer
1299/// @p DIE occurs.
1300///
Douglas Gregor4c678342009-01-28 21:54:33 +00001301/// @param StructuredList The initializer list expression that
1302/// describes all of the subobject initializers in the order they'll
1303/// actually be initialized.
1304///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001305/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001306bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001307InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001308 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001309 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001310 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001311 QualType &CurrentObjectType,
1312 RecordDecl::field_iterator *NextField,
1313 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001314 unsigned &Index,
1315 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001316 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001317 bool FinishSubobjectInit,
1318 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001319 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001320 // Check the actual initialization for the designated object type.
1321 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001322
1323 // Temporarily remove the designator expression from the
1324 // initializer list that the child calls see, so that we don't try
1325 // to re-process the designator.
1326 unsigned OldIndex = Index;
1327 IList->setInit(OldIndex, DIE->getInit());
1328
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001329 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001330 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001331
1332 // Restore the designated initializer expression in the syntactic
1333 // form of the initializer list.
1334 if (IList->getInit(OldIndex) != DIE->getInit())
1335 DIE->setInit(IList->getInit(OldIndex));
1336 IList->setInit(OldIndex, DIE);
1337
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001338 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001339 }
1340
Douglas Gregor71199712009-04-15 04:56:10 +00001341 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001342 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001343 "Need a non-designated initializer list to start from");
1344
Douglas Gregor71199712009-04-15 04:56:10 +00001345 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001346 // Determine the structural initializer list that corresponds to the
1347 // current subobject.
1348 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001349 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001350 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001351 SourceRange(D->getStartLocation(),
1352 DIE->getSourceRange().getEnd()));
1353 assert(StructuredList && "Expected a structured initializer list");
1354
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001355 if (D->isFieldDesignator()) {
1356 // C99 6.7.8p7:
1357 //
1358 // If a designator has the form
1359 //
1360 // . identifier
1361 //
1362 // then the current object (defined below) shall have
1363 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001364 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001365 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001366 if (!RT) {
1367 SourceLocation Loc = D->getDotLoc();
1368 if (Loc.isInvalid())
1369 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001370 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1371 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001372 ++Index;
1373 return true;
1374 }
1375
Douglas Gregor4c678342009-01-28 21:54:33 +00001376 // Note: we perform a linear search of the fields here, despite
1377 // the fact that we have a faster lookup method, because we always
1378 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001379 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001380 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001381 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001382 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001383 Field = RT->getDecl()->field_begin(),
1384 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001385 for (; Field != FieldEnd; ++Field) {
1386 if (Field->isUnnamedBitfield())
1387 continue;
1388
Douglas Gregor022d13d2010-10-08 20:44:28 +00001389 if (KnownField && KnownField == *Field)
1390 break;
1391 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001392 break;
1393
1394 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001395 }
1396
Douglas Gregor4c678342009-01-28 21:54:33 +00001397 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001398 // There was no normal field in the struct with the designated
1399 // name. Perform another lookup for this name, which may find
1400 // something that we can't designate (e.g., a member function),
1401 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001402 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001403 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001404 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001405 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001406 // Name lookup didn't find anything. Determine whether this
1407 // was a typo for another field name.
1408 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1409 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001410 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1411 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001412 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001413 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001414 ->Equals(RT->getDecl())) {
1415 SemaRef.Diag(D->getFieldLoc(),
1416 diag::err_field_designator_unknown_suggest)
1417 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001418 << FixItHint::CreateReplacement(D->getFieldLoc(),
1419 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001420 SemaRef.Diag(ReplacementField->getLocation(),
1421 diag::note_previous_decl)
1422 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001423 } else {
1424 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1425 << FieldName << CurrentObjectType;
1426 ++Index;
1427 return true;
1428 }
1429 } else if (!KnownField) {
1430 // Determine whether we found a field at all.
1431 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1432 }
1433
1434 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001435 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001436 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001437 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001438 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001439 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001440 ++Index;
1441 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001442 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001443
1444 if (!KnownField &&
1445 cast<RecordDecl>((ReplacementField)->getDeclContext())
1446 ->isAnonymousStructOrUnion()) {
1447 // Handle an field designator that refers to a member of an
Douglas Gregor022d13d2010-10-08 20:44:28 +00001448 // anonymous struct or union. This is a C1X feature.
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001449 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1450 ReplacementField,
Douglas Gregor022d13d2010-10-08 20:44:28 +00001451 Field, FieldIndex, RT->getDecl());
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001452 D = DIE->getDesignator(DesigIdx);
1453 } else if (!KnownField) {
1454 // The replacement field comes from typo correction; find it
1455 // in the list of fields.
1456 FieldIndex = 0;
1457 Field = RT->getDecl()->field_begin();
1458 for (; Field != FieldEnd; ++Field) {
1459 if (Field->isUnnamedBitfield())
1460 continue;
1461
1462 if (ReplacementField == *Field ||
1463 Field->getIdentifier() == ReplacementField->getIdentifier())
1464 break;
1465
1466 ++FieldIndex;
1467 }
1468 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001469 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001470
1471 // All of the fields of a union are located at the same place in
1472 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001473 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001474 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001475 StructuredList->setInitializedFieldInUnion(*Field);
1476 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001477
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001478 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001479 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Douglas Gregor4c678342009-01-28 21:54:33 +00001481 // Make sure that our non-designated initializer list has space
1482 // for a subobject corresponding to this field.
1483 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001484 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001485
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001486 // This designator names a flexible array member.
1487 if (Field->getType()->isIncompleteArrayType()) {
1488 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001489 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001490 // We can't designate an object within the flexible array
1491 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001492 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001493 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001494 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001495 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001496 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001497 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001498 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001499 << *Field;
1500 Invalid = true;
1501 }
1502
Chris Lattner9046c222010-10-10 17:49:49 +00001503 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1504 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001505 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001506 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001507 diag::err_flexible_array_init_needs_braces)
1508 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001509 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001510 << *Field;
1511 Invalid = true;
1512 }
1513
1514 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001515 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001516 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001517 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001518 diag::err_flexible_array_init_nonempty)
1519 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001520 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001521 << *Field;
1522 Invalid = true;
1523 }
1524
1525 if (Invalid) {
1526 ++Index;
1527 return true;
1528 }
1529
1530 // Initialize the array.
1531 bool prevHadError = hadError;
1532 unsigned newStructuredIndex = FieldIndex;
1533 unsigned OldIndex = Index;
1534 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001535
1536 InitializedEntity MemberEntity =
1537 InitializedEntity::InitializeMember(*Field, &Entity);
1538 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001539 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001540
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001541 IList->setInit(OldIndex, DIE);
1542 if (hadError && !prevHadError) {
1543 ++Field;
1544 ++FieldIndex;
1545 if (NextField)
1546 *NextField = Field;
1547 StructuredIndex = FieldIndex;
1548 return true;
1549 }
1550 } else {
1551 // Recurse to check later designated subobjects.
1552 QualType FieldType = (*Field)->getType();
1553 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001554
1555 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001556 InitializedEntity::InitializeMember(*Field, &Entity);
1557 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001558 FieldType, 0, 0, Index,
1559 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001560 true, false))
1561 return true;
1562 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001563
1564 // Find the position of the next field to be initialized in this
1565 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001566 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001567 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001568
1569 // If this the first designator, our caller will continue checking
1570 // the rest of this struct/class/union subobject.
1571 if (IsFirstDesignator) {
1572 if (NextField)
1573 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001574 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001575 return false;
1576 }
1577
Douglas Gregor34e79462009-01-28 23:36:17 +00001578 if (!FinishSubobjectInit)
1579 return false;
1580
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001581 // We've already initialized something in the union; we're done.
1582 if (RT->getDecl()->isUnion())
1583 return hadError;
1584
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001585 // Check the remaining fields within this class/struct/union subobject.
1586 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001587
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001588 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001589 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001590 return hadError && !prevHadError;
1591 }
1592
1593 // C99 6.7.8p6:
1594 //
1595 // If a designator has the form
1596 //
1597 // [ constant-expression ]
1598 //
1599 // then the current object (defined below) shall have array
1600 // type and the expression shall be an integer constant
1601 // expression. If the array is of unknown size, any
1602 // nonnegative value is valid.
1603 //
1604 // Additionally, cope with the GNU extension that permits
1605 // designators of the form
1606 //
1607 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001608 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001609 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001610 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001611 << CurrentObjectType;
1612 ++Index;
1613 return true;
1614 }
1615
1616 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001617 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1618 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001619 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001620 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001621 DesignatedEndIndex = DesignatedStartIndex;
1622 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001623 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001624
Mike Stump1eb44332009-09-09 15:08:12 +00001625
1626 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001627 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001628 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001629 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001630 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001631
Chris Lattner3bf68932009-04-25 21:59:05 +00001632 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001633 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001634 }
1635
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001636 if (isa<ConstantArrayType>(AT)) {
1637 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001638 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1639 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1640 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1641 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1642 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001643 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001644 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001645 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001646 << IndexExpr->getSourceRange();
1647 ++Index;
1648 return true;
1649 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001650 } else {
1651 // Make sure the bit-widths and signedness match.
1652 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1653 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001654 else if (DesignatedStartIndex.getBitWidth() <
1655 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001656 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1657 DesignatedStartIndex.setIsUnsigned(true);
1658 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001659 }
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Douglas Gregor4c678342009-01-28 21:54:33 +00001661 // Make sure that our non-designated initializer list has space
1662 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001663 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001664 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001665 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001666
Douglas Gregor34e79462009-01-28 23:36:17 +00001667 // Repeatedly perform subobject initializations in the range
1668 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001669
Douglas Gregor34e79462009-01-28 23:36:17 +00001670 // Move to the next designator
1671 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1672 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001673
1674 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001675 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001676
Douglas Gregor34e79462009-01-28 23:36:17 +00001677 while (DesignatedStartIndex <= DesignatedEndIndex) {
1678 // Recurse to check later designated subobjects.
1679 QualType ElementType = AT->getElementType();
1680 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001681
1682 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001683 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001684 ElementType, 0, 0, Index,
1685 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001686 (DesignatedStartIndex == DesignatedEndIndex),
1687 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001688 return true;
1689
1690 // Move to the next index in the array that we'll be initializing.
1691 ++DesignatedStartIndex;
1692 ElementIndex = DesignatedStartIndex.getZExtValue();
1693 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001694
1695 // If this the first designator, our caller will continue checking
1696 // the rest of this array subobject.
1697 if (IsFirstDesignator) {
1698 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001699 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001700 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001701 return false;
1702 }
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Douglas Gregor34e79462009-01-28 23:36:17 +00001704 if (!FinishSubobjectInit)
1705 return false;
1706
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001707 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001708 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001709 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001710 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001711 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001712 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001713}
1714
Douglas Gregor4c678342009-01-28 21:54:33 +00001715// Get the structured initializer list for a subobject of type
1716// @p CurrentObjectType.
1717InitListExpr *
1718InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1719 QualType CurrentObjectType,
1720 InitListExpr *StructuredList,
1721 unsigned StructuredIndex,
1722 SourceRange InitRange) {
1723 Expr *ExistingInit = 0;
1724 if (!StructuredList)
1725 ExistingInit = SyntacticToSemantic[IList];
1726 else if (StructuredIndex < StructuredList->getNumInits())
1727 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Douglas Gregor4c678342009-01-28 21:54:33 +00001729 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1730 return Result;
1731
1732 if (ExistingInit) {
1733 // We are creating an initializer list that initializes the
1734 // subobjects of the current object, but there was already an
1735 // initialization that completely initialized the current
1736 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001737 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001738 // struct X { int a, b; };
1739 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001740 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001741 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1742 // designated initializer re-initializes the whole
1743 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001744 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001745 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001746 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001747 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001748 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001749 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001750 << ExistingInit->getSourceRange();
1751 }
1752
Mike Stump1eb44332009-09-09 15:08:12 +00001753 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001754 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1755 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001756 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001757
Douglas Gregor63982352010-07-13 18:40:04 +00001758 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001759
Douglas Gregorfa219202009-03-20 23:58:33 +00001760 // Pre-allocate storage for the structured initializer list.
1761 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001762 unsigned NumInits = 0;
1763 if (!StructuredList)
1764 NumInits = IList->getNumInits();
1765 else if (Index < IList->getNumInits()) {
1766 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1767 NumInits = SubList->getNumInits();
1768 }
1769
Mike Stump1eb44332009-09-09 15:08:12 +00001770 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001771 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1772 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1773 NumElements = CAType->getSize().getZExtValue();
1774 // Simple heuristic so that we don't allocate a very large
1775 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001776 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001777 NumElements = 0;
1778 }
John McCall183700f2009-09-21 23:43:11 +00001779 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001780 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001781 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001782 RecordDecl *RDecl = RType->getDecl();
1783 if (RDecl->isUnion())
1784 NumElements = 1;
1785 else
Mike Stump1eb44332009-09-09 15:08:12 +00001786 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001787 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001788 }
1789
Douglas Gregor08457732009-03-21 18:13:52 +00001790 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001791 NumElements = IList->getNumInits();
1792
Ted Kremenek709210f2010-04-13 23:39:13 +00001793 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001794
Douglas Gregor4c678342009-01-28 21:54:33 +00001795 // Link this new initializer list into the structured initializer
1796 // lists.
1797 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001798 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001799 else {
1800 Result->setSyntacticForm(IList);
1801 SyntacticToSemantic[IList] = Result;
1802 }
1803
1804 return Result;
1805}
1806
1807/// Update the initializer at index @p StructuredIndex within the
1808/// structured initializer list to the value @p expr.
1809void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1810 unsigned &StructuredIndex,
1811 Expr *expr) {
1812 // No structured initializer list to update
1813 if (!StructuredList)
1814 return;
1815
Ted Kremenek709210f2010-04-13 23:39:13 +00001816 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1817 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001818 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001819 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001820 diag::warn_initializer_overrides)
1821 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001822 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001823 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001824 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001825 << PrevInit->getSourceRange();
1826 }
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Douglas Gregor4c678342009-01-28 21:54:33 +00001828 ++StructuredIndex;
1829}
1830
Douglas Gregor05c13a32009-01-22 00:58:24 +00001831/// Check that the given Index expression is a valid array designator
1832/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001833/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001834/// and produces a reasonable diagnostic if there is a
1835/// failure. Returns true if there was an error, false otherwise. If
1836/// everything went okay, Value will receive the value of the constant
1837/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001838static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001839CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001840 SourceLocation Loc = Index->getSourceRange().getBegin();
1841
1842 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001843 if (S.VerifyIntegerConstantExpression(Index, &Value))
1844 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001845
Chris Lattner3bf68932009-04-25 21:59:05 +00001846 if (Value.isSigned() && Value.isNegative())
1847 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001848 << Value.toString(10) << Index->getSourceRange();
1849
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001850 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001851 return false;
1852}
1853
John McCall60d7b3a2010-08-24 06:29:42 +00001854ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001855 SourceLocation Loc,
1856 bool GNUSyntax,
1857 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001858 typedef DesignatedInitExpr::Designator ASTDesignator;
1859
1860 bool Invalid = false;
1861 llvm::SmallVector<ASTDesignator, 32> Designators;
1862 llvm::SmallVector<Expr *, 32> InitExpressions;
1863
1864 // Build designators and check array designator expressions.
1865 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1866 const Designator &D = Desig.getDesignator(Idx);
1867 switch (D.getKind()) {
1868 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001869 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001870 D.getFieldLoc()));
1871 break;
1872
1873 case Designator::ArrayDesignator: {
1874 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1875 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001876 if (!Index->isTypeDependent() &&
1877 !Index->isValueDependent() &&
1878 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001879 Invalid = true;
1880 else {
1881 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001882 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001883 D.getRBracketLoc()));
1884 InitExpressions.push_back(Index);
1885 }
1886 break;
1887 }
1888
1889 case Designator::ArrayRangeDesignator: {
1890 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1891 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1892 llvm::APSInt StartValue;
1893 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001894 bool StartDependent = StartIndex->isTypeDependent() ||
1895 StartIndex->isValueDependent();
1896 bool EndDependent = EndIndex->isTypeDependent() ||
1897 EndIndex->isValueDependent();
1898 if ((!StartDependent &&
1899 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1900 (!EndDependent &&
1901 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001902 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001903 else {
1904 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001905 if (StartDependent || EndDependent) {
1906 // Nothing to compute.
1907 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001908 EndValue.extend(StartValue.getBitWidth());
1909 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1910 StartValue.extend(EndValue.getBitWidth());
1911
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001912 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001913 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001914 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001915 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1916 Invalid = true;
1917 } else {
1918 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001919 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001920 D.getEllipsisLoc(),
1921 D.getRBracketLoc()));
1922 InitExpressions.push_back(StartIndex);
1923 InitExpressions.push_back(EndIndex);
1924 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001925 }
1926 break;
1927 }
1928 }
1929 }
1930
1931 if (Invalid || Init.isInvalid())
1932 return ExprError();
1933
1934 // Clear out the expressions within the designation.
1935 Desig.ClearExprs(*this);
1936
1937 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001938 = DesignatedInitExpr::Create(Context,
1939 Designators.data(), Designators.size(),
1940 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001941 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001942 return Owned(DIE);
1943}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001944
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001945bool Sema::CheckInitList(const InitializedEntity &Entity,
1946 InitListExpr *&InitList, QualType &DeclType) {
1947 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001948 if (!CheckInitList.HadError())
1949 InitList = CheckInitList.getFullyStructuredList();
1950
1951 return CheckInitList.HadError();
1952}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001953
Douglas Gregor20093b42009-12-09 23:02:17 +00001954//===----------------------------------------------------------------------===//
1955// Initialization entity
1956//===----------------------------------------------------------------------===//
1957
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001958InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1959 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001960 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001961{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001962 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1963 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001964 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001965 } else {
1966 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001967 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001968 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001969}
1970
1971InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001972 CXXBaseSpecifier *Base,
1973 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001974{
1975 InitializedEntity Result;
1976 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001977 Result.Base = reinterpret_cast<uintptr_t>(Base);
1978 if (IsInheritedVirtualBase)
1979 Result.Base |= 0x01;
1980
Douglas Gregord6542d82009-12-22 15:35:07 +00001981 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001982 return Result;
1983}
1984
Douglas Gregor99a2e602009-12-16 01:38:02 +00001985DeclarationName InitializedEntity::getName() const {
1986 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001987 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001988 if (!VariableOrMember)
1989 return DeclarationName();
1990 // Fall through
1991
1992 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001993 case EK_Member:
1994 return VariableOrMember->getDeclName();
1995
1996 case EK_Result:
1997 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001998 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001999 case EK_Temporary:
2000 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002001 case EK_ArrayElement:
2002 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002003 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002004 return DeclarationName();
2005 }
2006
2007 // Silence GCC warning
2008 return DeclarationName();
2009}
2010
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002011DeclaratorDecl *InitializedEntity::getDecl() const {
2012 switch (getKind()) {
2013 case EK_Variable:
2014 case EK_Parameter:
2015 case EK_Member:
2016 return VariableOrMember;
2017
2018 case EK_Result:
2019 case EK_Exception:
2020 case EK_New:
2021 case EK_Temporary:
2022 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002023 case EK_ArrayElement:
2024 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002025 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002026 return 0;
2027 }
2028
2029 // Silence GCC warning
2030 return 0;
2031}
2032
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002033bool InitializedEntity::allowsNRVO() const {
2034 switch (getKind()) {
2035 case EK_Result:
2036 case EK_Exception:
2037 return LocAndNRVO.NRVO;
2038
2039 case EK_Variable:
2040 case EK_Parameter:
2041 case EK_Member:
2042 case EK_New:
2043 case EK_Temporary:
2044 case EK_Base:
2045 case EK_ArrayElement:
2046 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002047 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002048 break;
2049 }
2050
2051 return false;
2052}
2053
Douglas Gregor20093b42009-12-09 23:02:17 +00002054//===----------------------------------------------------------------------===//
2055// Initialization sequence
2056//===----------------------------------------------------------------------===//
2057
2058void InitializationSequence::Step::Destroy() {
2059 switch (Kind) {
2060 case SK_ResolveAddressOfOverloadedFunction:
2061 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002062 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002063 case SK_CastDerivedToBaseLValue:
2064 case SK_BindReference:
2065 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002066 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002067 case SK_UserConversion:
2068 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002069 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002070 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002071 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002072 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002073 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002074 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002075 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002076 case SK_ObjCObjectConversion:
Douglas Gregor20093b42009-12-09 23:02:17 +00002077 break;
2078
2079 case SK_ConversionSequence:
2080 delete ICS;
2081 }
2082}
2083
Douglas Gregorb70cf442010-03-26 20:14:36 +00002084bool InitializationSequence::isDirectReferenceBinding() const {
2085 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2086}
2087
2088bool InitializationSequence::isAmbiguous() const {
2089 if (getKind() != FailedSequence)
2090 return false;
2091
2092 switch (getFailureKind()) {
2093 case FK_TooManyInitsForReference:
2094 case FK_ArrayNeedsInitList:
2095 case FK_ArrayNeedsInitListOrStringLiteral:
2096 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2097 case FK_NonConstLValueReferenceBindingToTemporary:
2098 case FK_NonConstLValueReferenceBindingToUnrelated:
2099 case FK_RValueReferenceBindingToLValue:
2100 case FK_ReferenceInitDropsQualifiers:
2101 case FK_ReferenceInitFailed:
2102 case FK_ConversionFailed:
2103 case FK_TooManyInitsForScalar:
2104 case FK_ReferenceBindingToInitList:
2105 case FK_InitListBadDestinationType:
2106 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002107 case FK_Incomplete:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002108 return false;
2109
2110 case FK_ReferenceInitOverloadFailed:
2111 case FK_UserConversionOverloadFailed:
2112 case FK_ConstructorOverloadFailed:
2113 return FailedOverloadResult == OR_Ambiguous;
2114 }
2115
2116 return false;
2117}
2118
Douglas Gregord6e44a32010-04-16 22:09:46 +00002119bool InitializationSequence::isConstructorInitialization() const {
2120 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2121}
2122
Douglas Gregor20093b42009-12-09 23:02:17 +00002123void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002124 FunctionDecl *Function,
2125 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002126 Step S;
2127 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2128 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002129 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002130 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002131 Steps.push_back(S);
2132}
2133
2134void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002135 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002136 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002137 switch (VK) {
2138 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2139 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2140 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002141 default: llvm_unreachable("No such category");
2142 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002143 S.Type = BaseType;
2144 Steps.push_back(S);
2145}
2146
2147void InitializationSequence::AddReferenceBindingStep(QualType T,
2148 bool BindingTemporary) {
2149 Step S;
2150 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2151 S.Type = T;
2152 Steps.push_back(S);
2153}
2154
Douglas Gregor523d46a2010-04-18 07:40:54 +00002155void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2156 Step S;
2157 S.Kind = SK_ExtraneousCopyToTemporary;
2158 S.Type = T;
2159 Steps.push_back(S);
2160}
2161
Eli Friedman03981012009-12-11 02:42:07 +00002162void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002163 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002164 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002165 Step S;
2166 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002167 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002168 S.Function.Function = Function;
2169 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002170 Steps.push_back(S);
2171}
2172
2173void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002174 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002175 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002176 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002177 switch (VK) {
2178 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002179 S.Kind = SK_QualificationConversionRValue;
2180 break;
John McCall5baba9d2010-08-25 10:28:54 +00002181 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002182 S.Kind = SK_QualificationConversionXValue;
2183 break;
John McCall5baba9d2010-08-25 10:28:54 +00002184 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002185 S.Kind = SK_QualificationConversionLValue;
2186 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002187 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002188 S.Type = Ty;
2189 Steps.push_back(S);
2190}
2191
2192void InitializationSequence::AddConversionSequenceStep(
2193 const ImplicitConversionSequence &ICS,
2194 QualType T) {
2195 Step S;
2196 S.Kind = SK_ConversionSequence;
2197 S.Type = T;
2198 S.ICS = new ImplicitConversionSequence(ICS);
2199 Steps.push_back(S);
2200}
2201
Douglas Gregord87b61f2009-12-10 17:56:55 +00002202void InitializationSequence::AddListInitializationStep(QualType T) {
2203 Step S;
2204 S.Kind = SK_ListInitialization;
2205 S.Type = T;
2206 Steps.push_back(S);
2207}
2208
Douglas Gregor51c56d62009-12-14 20:49:26 +00002209void
2210InitializationSequence::AddConstructorInitializationStep(
2211 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002212 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002213 QualType T) {
2214 Step S;
2215 S.Kind = SK_ConstructorInitialization;
2216 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002217 S.Function.Function = Constructor;
2218 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002219 Steps.push_back(S);
2220}
2221
Douglas Gregor71d17402009-12-15 00:01:57 +00002222void InitializationSequence::AddZeroInitializationStep(QualType T) {
2223 Step S;
2224 S.Kind = SK_ZeroInitialization;
2225 S.Type = T;
2226 Steps.push_back(S);
2227}
2228
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002229void InitializationSequence::AddCAssignmentStep(QualType T) {
2230 Step S;
2231 S.Kind = SK_CAssignment;
2232 S.Type = T;
2233 Steps.push_back(S);
2234}
2235
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002236void InitializationSequence::AddStringInitStep(QualType T) {
2237 Step S;
2238 S.Kind = SK_StringInit;
2239 S.Type = T;
2240 Steps.push_back(S);
2241}
2242
Douglas Gregor569c3162010-08-07 11:51:51 +00002243void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2244 Step S;
2245 S.Kind = SK_ObjCObjectConversion;
2246 S.Type = T;
2247 Steps.push_back(S);
2248}
2249
Douglas Gregor20093b42009-12-09 23:02:17 +00002250void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2251 OverloadingResult Result) {
2252 SequenceKind = FailedSequence;
2253 this->Failure = Failure;
2254 this->FailedOverloadResult = Result;
2255}
2256
2257//===----------------------------------------------------------------------===//
2258// Attempt initialization
2259//===----------------------------------------------------------------------===//
2260
2261/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002262static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002263 const InitializedEntity &Entity,
2264 const InitializationKind &Kind,
2265 InitListExpr *InitList,
2266 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002267 // FIXME: We only perform rudimentary checking of list
2268 // initializations at this point, then assume that any list
2269 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002270 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002271 // do all of the necessary checking. C++0x initializer lists will
2272 // force us to perform more checking here.
2273 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2274
Douglas Gregord6542d82009-12-22 15:35:07 +00002275 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002276
2277 // C++ [dcl.init]p13:
2278 // If T is a scalar type, then a declaration of the form
2279 //
2280 // T x = { a };
2281 //
2282 // is equivalent to
2283 //
2284 // T x = a;
2285 if (DestType->isScalarType()) {
2286 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2287 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2288 return;
2289 }
2290
2291 // Assume scalar initialization from a single value works.
2292 } else if (DestType->isAggregateType()) {
2293 // Assume aggregate initialization works.
2294 } else if (DestType->isVectorType()) {
2295 // Assume vector initialization works.
2296 } else if (DestType->isReferenceType()) {
2297 // FIXME: C++0x defines behavior for this.
2298 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2299 return;
2300 } else if (DestType->isRecordType()) {
2301 // FIXME: C++0x defines behavior for this
2302 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2303 }
2304
2305 // Add a general "list initialization" step.
2306 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002307}
2308
2309/// \brief Try a reference initialization that involves calling a conversion
2310/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002311static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2312 const InitializedEntity &Entity,
2313 const InitializationKind &Kind,
2314 Expr *Initializer,
2315 bool AllowRValues,
2316 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002317 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002318 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2319 QualType T1 = cv1T1.getUnqualifiedType();
2320 QualType cv2T2 = Initializer->getType();
2321 QualType T2 = cv2T2.getUnqualifiedType();
2322
2323 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002324 bool ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002325 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002326 T1, T2, DerivedToBase,
2327 ObjCConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002328 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002329 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002330 (void)ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002331
2332 // Build the candidate set directly in the initialization sequence
2333 // structure, so that it will persist if we fail.
2334 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2335 CandidateSet.clear();
2336
2337 // Determine whether we are allowed to call explicit constructors or
2338 // explicit conversion operators.
2339 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2340
2341 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002342 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2343 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002344 // The type we're converting to is a class type. Enumerate its constructors
2345 // to see if there is a suitable conversion.
2346 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002347
Douglas Gregor20093b42009-12-09 23:02:17 +00002348 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002349 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002350 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002351 NamedDecl *D = *Con;
2352 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2353
Douglas Gregor20093b42009-12-09 23:02:17 +00002354 // Find the constructor (which may be a template).
2355 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002356 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002357 if (ConstructorTmpl)
2358 Constructor = cast<CXXConstructorDecl>(
2359 ConstructorTmpl->getTemplatedDecl());
2360 else
John McCall9aa472c2010-03-19 07:35:19 +00002361 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002362
2363 if (!Constructor->isInvalidDecl() &&
2364 Constructor->isConvertingConstructor(AllowExplicit)) {
2365 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002366 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002367 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002368 &Initializer, 1, CandidateSet,
2369 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002370 else
John McCall9aa472c2010-03-19 07:35:19 +00002371 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002372 &Initializer, 1, CandidateSet,
2373 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002374 }
2375 }
2376 }
John McCall572fc622010-08-17 07:23:57 +00002377 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2378 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002379
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002380 const RecordType *T2RecordType = 0;
2381 if ((T2RecordType = T2->getAs<RecordType>()) &&
2382 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002383 // The type we're converting from is a class type, enumerate its conversion
2384 // functions.
2385 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2386
2387 // Determine the type we are converting to. If we are allowed to
2388 // convert to an rvalue, take the type that the destination type
2389 // refers to.
2390 QualType ToType = AllowRValues? cv1T1 : DestType;
2391
John McCalleec51cf2010-01-20 00:46:10 +00002392 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002393 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002394 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2395 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002396 NamedDecl *D = *I;
2397 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2398 if (isa<UsingShadowDecl>(D))
2399 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2400
2401 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2402 CXXConversionDecl *Conv;
2403 if (ConvTemplate)
2404 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2405 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002406 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002407
2408 // If the conversion function doesn't return a reference type,
2409 // it can't be considered for this conversion unless we're allowed to
2410 // consider rvalues.
2411 // FIXME: Do we need to make sure that we only consider conversion
2412 // candidates with reference-compatible results? That might be needed to
2413 // break recursion.
2414 if ((AllowExplicit || !Conv->isExplicit()) &&
2415 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2416 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002417 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002418 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002419 ToType, CandidateSet);
2420 else
John McCall9aa472c2010-03-19 07:35:19 +00002421 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002422 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002423 }
2424 }
2425 }
John McCall572fc622010-08-17 07:23:57 +00002426 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2427 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002428
2429 SourceLocation DeclLoc = Initializer->getLocStart();
2430
2431 // Perform overload resolution. If it fails, return the failed result.
2432 OverloadCandidateSet::iterator Best;
2433 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002434 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002435 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002436
Douglas Gregor20093b42009-12-09 23:02:17 +00002437 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002438
2439 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002440 if (isa<CXXConversionDecl>(Function))
2441 T2 = Function->getResultType();
2442 else
2443 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002444
2445 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002446 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002447 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002448
2449 // Determine whether we need to perform derived-to-base or
2450 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002451 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002452 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002453 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002454 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002455 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002456
Douglas Gregor20093b42009-12-09 23:02:17 +00002457 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002458 bool NewObjCConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002459 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregor63982352010-07-13 18:40:04 +00002460 = S.CompareReferenceRelationship(DeclLoc, T1,
2461 T2.getNonLValueExprType(S.Context),
Douglas Gregor569c3162010-08-07 11:51:51 +00002462 NewDerivedToBase, NewObjCConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002463 if (NewRefRelationship == Sema::Ref_Incompatible) {
2464 // If the type we've converted to is not reference-related to the
2465 // type we're looking for, then there is another conversion step
2466 // we need to perform to produce a temporary of the right type
2467 // that we'll be binding to.
2468 ImplicitConversionSequence ICS;
2469 ICS.setStandard();
2470 ICS.Standard = Best->FinalConversion;
2471 T2 = ICS.Standard.getToType(2);
2472 Sequence.AddConversionSequenceStep(ICS, T2);
2473 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002474 Sequence.AddDerivedToBaseCastStep(
2475 S.Context.getQualifiedType(T1,
2476 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002477 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002478 else if (NewObjCConversion)
2479 Sequence.AddObjCObjectConversionStep(
2480 S.Context.getQualifiedType(T1,
2481 T2.getNonReferenceType().getQualifiers()));
2482
Douglas Gregor20093b42009-12-09 23:02:17 +00002483 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002484 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00002485
2486 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2487 return OR_Success;
2488}
2489
Sebastian Redl4680bf22010-06-30 18:13:39 +00002490/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor20093b42009-12-09 23:02:17 +00002491static void TryReferenceInitialization(Sema &S,
2492 const InitializedEntity &Entity,
2493 const InitializationKind &Kind,
2494 Expr *Initializer,
2495 InitializationSequence &Sequence) {
2496 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002497
Douglas Gregord6542d82009-12-22 15:35:07 +00002498 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002499 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002500 Qualifiers T1Quals;
2501 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002502 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002503 Qualifiers T2Quals;
2504 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002505 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002506
Douglas Gregor20093b42009-12-09 23:02:17 +00002507 // If the initializer is the address of an overloaded function, try
2508 // to resolve the overloaded function. If all goes well, T2 is the
2509 // type of the resulting function.
2510 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002511 DeclAccessPair Found;
Douglas Gregor3afb9772010-11-08 15:20:28 +00002512 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2513 T1,
2514 false,
2515 Found)) {
2516 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2517 cv2T2 = Fn->getType();
2518 T2 = cv2T2.getUnqualifiedType();
2519 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002520 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2521 return;
2522 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002523 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002524
Douglas Gregor20093b42009-12-09 23:02:17 +00002525 // Compute some basic properties of the types and the initializer.
2526 bool isLValueRef = DestType->isLValueReferenceType();
2527 bool isRValueRef = !isLValueRef;
2528 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002529 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002530 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002531 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002532 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2533 ObjCConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002534
Douglas Gregor20093b42009-12-09 23:02:17 +00002535 // C++0x [dcl.init.ref]p5:
2536 // A reference to type "cv1 T1" is initialized by an expression of type
2537 // "cv2 T2" as follows:
2538 //
2539 // - If the reference is an lvalue reference and the initializer
2540 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002541 // Note the analogous bullet points for rvlaue refs to functions. Because
2542 // there are no function rvalues in C++, rvalue refs to functions are treated
2543 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002544 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002545 bool T1Function = T1->isFunctionType();
2546 if (isLValueRef || T1Function) {
2547 if (InitCategory.isLValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002548 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2549 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2550 // reference-compatible with "cv2 T2," or
2551 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002552 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002553 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002554 // can occur. However, we do pay attention to whether it is a bit-field
2555 // to decide whether we're actually binding to a temporary created from
2556 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002557 if (DerivedToBase)
2558 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002559 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002560 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002561 else if (ObjCConversion)
2562 Sequence.AddObjCObjectConversionStep(
2563 S.Context.getQualifiedType(T1, T2Quals));
2564
Chandler Carruth5535c382010-01-12 20:32:25 +00002565 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002566 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002567 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002568 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002569 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002570 return;
2571 }
2572
2573 // - has a class type (i.e., T2 is a class type), where T1 is not
2574 // reference-related to T2, and can be implicitly converted to an
2575 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2576 // with "cv3 T3" (this conversion is selected by enumerating the
2577 // applicable conversion functions (13.3.1.6) and choosing the best
2578 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002579 // If we have an rvalue ref to function type here, the rhs must be
2580 // an rvalue.
2581 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2582 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002583 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2584 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002585 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002586 Sequence);
2587 if (ConvOvlResult == OR_Success)
2588 return;
John McCall1d318332010-01-12 00:44:57 +00002589 if (ConvOvlResult != OR_No_Viable_Function) {
2590 Sequence.SetOverloadFailure(
2591 InitializationSequence::FK_ReferenceInitOverloadFailed,
2592 ConvOvlResult);
2593 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002594 }
2595 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002596
Douglas Gregor20093b42009-12-09 23:02:17 +00002597 // - Otherwise, the reference shall be an lvalue reference to a
2598 // non-volatile const type (i.e., cv1 shall be const), or the reference
2599 // shall be an rvalue reference and the initializer expression shall
Sebastian Redl4680bf22010-06-30 18:13:39 +00002600 // be an rvalue or have a function type.
2601 // We handled the function type stuff above.
Douglas Gregoref06e242010-01-29 19:39:15 +00002602 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redl4680bf22010-06-30 18:13:39 +00002603 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002604 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2605 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2606 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002607 Sequence.SetOverloadFailure(
2608 InitializationSequence::FK_ReferenceInitOverloadFailed,
2609 ConvOvlResult);
2610 else if (isLValueRef)
Sebastian Redl4680bf22010-06-30 18:13:39 +00002611 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 ? (RefRelationship == Sema::Ref_Related
2613 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2614 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2615 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2616 else
2617 Sequence.SetFailed(
2618 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002619
Douglas Gregor20093b42009-12-09 23:02:17 +00002620 return;
2621 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002622
2623 // - [If T1 is not a function type], if T2 is a class type and
2624 if (!T1Function && T2->isRecordType()) {
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002625 bool isXValue = InitCategory.isXValue();
Douglas Gregor20093b42009-12-09 23:02:17 +00002626 // - the initializer expression is an rvalue and "cv1 T1" is
2627 // reference-compatible with "cv2 T2", or
Sebastian Redl4680bf22010-06-30 18:13:39 +00002628 if (InitCategory.isRValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002629 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002630 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2631 // compiler the freedom to perform a copy here or bind to the
2632 // object, while C++0x requires that we bind directly to the
2633 // object. Hence, we always bind to the object without making an
2634 // extra copy. However, in C++03 requires that we check for the
2635 // presence of a suitable copy constructor:
2636 //
2637 // The constructor that would be used to make the copy shall
2638 // be callable whether or not the copy is actually done.
2639 if (!S.getLangOptions().CPlusPlus0x)
2640 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2641
Douglas Gregor20093b42009-12-09 23:02:17 +00002642 if (DerivedToBase)
2643 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002644 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002645 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002646 else if (ObjCConversion)
2647 Sequence.AddObjCObjectConversionStep(
2648 S.Context.getQualifiedType(T1, T2Quals));
2649
Chandler Carruth5535c382010-01-12 20:32:25 +00002650 if (T1Quals != T2Quals)
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002651 Sequence.AddQualificationConversionStep(cv1T1,
John McCall5baba9d2010-08-25 10:28:54 +00002652 isXValue ? VK_XValue : VK_RValue);
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002653 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00002654 return;
2655 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002656
Douglas Gregor20093b42009-12-09 23:02:17 +00002657 // - T1 is not reference-related to T2 and the initializer expression
2658 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2659 // conversion is selected by enumerating the applicable conversion
2660 // functions (13.3.1.6) and choosing the best one through overload
2661 // resolution (13.3)),
2662 if (RefRelationship == Sema::Ref_Incompatible) {
2663 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2664 Kind, Initializer,
2665 /*AllowRValues=*/true,
2666 Sequence);
2667 if (ConvOvlResult)
2668 Sequence.SetOverloadFailure(
2669 InitializationSequence::FK_ReferenceInitOverloadFailed,
2670 ConvOvlResult);
2671
2672 return;
2673 }
2674
2675 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2676 return;
2677 }
2678
2679 // - If the initializer expression is an rvalue, with T2 an array type,
2680 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2681 // is bound to the object represented by the rvalue (see 3.10).
2682 // FIXME: How can an array type be reference-compatible with anything?
2683 // Don't we mean the element types of T1 and T2?
2684
2685 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2686 // from the initializer expression using the rules for a non-reference
2687 // copy initialization (8.5). The reference is then bound to the
2688 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002689
Douglas Gregor20093b42009-12-09 23:02:17 +00002690 // Determine whether we are allowed to call explicit constructors or
2691 // explicit conversion operators.
2692 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002693
2694 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2695
2696 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2697 /*SuppressUserConversions*/ false,
2698 AllowExplicit,
2699 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002700 // FIXME: Use the conversion function set stored in ICS to turn
2701 // this into an overloading ambiguity diagnostic. However, we need
2702 // to keep that set as an OverloadCandidateSet rather than as some
2703 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002704 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2705 Sequence.SetOverloadFailure(
2706 InitializationSequence::FK_ReferenceInitOverloadFailed,
2707 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002708 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2709 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002710 else
2711 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002712 return;
2713 }
2714
2715 // [...] If T1 is reference-related to T2, cv1 must be the
2716 // same cv-qualification as, or greater cv-qualification
2717 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002718 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2719 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002720 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002721 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002722 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2723 return;
2724 }
2725
Douglas Gregor20093b42009-12-09 23:02:17 +00002726 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2727 return;
2728}
2729
2730/// \brief Attempt character array initialization from a string literal
2731/// (C++ [dcl.init.string], C99 6.7.8).
2732static void TryStringLiteralInitialization(Sema &S,
2733 const InitializedEntity &Entity,
2734 const InitializationKind &Kind,
2735 Expr *Initializer,
2736 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002737 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002738 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002739}
2740
Douglas Gregor20093b42009-12-09 23:02:17 +00002741/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2742/// enumerates the constructors of the initialized entity and performs overload
2743/// resolution to select the best.
2744static void TryConstructorInitialization(Sema &S,
2745 const InitializedEntity &Entity,
2746 const InitializationKind &Kind,
2747 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002748 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002749 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002750 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002751
2752 // Build the candidate set directly in the initialization sequence
2753 // structure, so that it will persist if we fail.
2754 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2755 CandidateSet.clear();
2756
2757 // Determine whether we are allowed to call explicit constructors or
2758 // explicit conversion operators.
2759 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2760 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002761 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002762
2763 // The type we're constructing needs to be complete.
2764 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002765 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002766 return;
2767 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002768
2769 // The type we're converting to is a class type. Enumerate its constructors
2770 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002771 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2772 assert(DestRecordType && "Constructor initialization requires record type");
2773 CXXRecordDecl *DestRecordDecl
2774 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2775
Douglas Gregor51c56d62009-12-14 20:49:26 +00002776 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002777 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002778 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002779 NamedDecl *D = *Con;
2780 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002781 bool SuppressUserConversions = false;
2782
Douglas Gregor51c56d62009-12-14 20:49:26 +00002783 // Find the constructor (which may be a template).
2784 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002785 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002786 if (ConstructorTmpl)
2787 Constructor = cast<CXXConstructorDecl>(
2788 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002789 else {
John McCall9aa472c2010-03-19 07:35:19 +00002790 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002791
2792 // If we're performing copy initialization using a copy constructor, we
2793 // suppress user-defined conversions on the arguments.
2794 // FIXME: Move constructors?
2795 if (Kind.getKind() == InitializationKind::IK_Copy &&
2796 Constructor->isCopyConstructor())
2797 SuppressUserConversions = true;
2798 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002799
2800 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002801 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002802 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002803 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002804 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002805 Args, NumArgs, CandidateSet,
2806 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002807 else
John McCall9aa472c2010-03-19 07:35:19 +00002808 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002809 Args, NumArgs, CandidateSet,
2810 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002811 }
2812 }
2813
2814 SourceLocation DeclLoc = Kind.getLocation();
2815
2816 // Perform overload resolution. If it fails, return the failed result.
2817 OverloadCandidateSet::iterator Best;
2818 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002819 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002820 Sequence.SetOverloadFailure(
2821 InitializationSequence::FK_ConstructorOverloadFailed,
2822 Result);
2823 return;
2824 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002825
2826 // C++0x [dcl.init]p6:
2827 // If a program calls for the default initialization of an object
2828 // of a const-qualified type T, T shall be a class type with a
2829 // user-provided default constructor.
2830 if (Kind.getKind() == InitializationKind::IK_Default &&
2831 Entity.getType().isConstQualified() &&
2832 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2833 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2834 return;
2835 }
2836
Douglas Gregor51c56d62009-12-14 20:49:26 +00002837 // Add the constructor initialization step. Any cv-qualification conversion is
2838 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002839 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002840 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002841 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002842 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002843}
2844
Douglas Gregor71d17402009-12-15 00:01:57 +00002845/// \brief Attempt value initialization (C++ [dcl.init]p7).
2846static void TryValueInitialization(Sema &S,
2847 const InitializedEntity &Entity,
2848 const InitializationKind &Kind,
2849 InitializationSequence &Sequence) {
2850 // C++ [dcl.init]p5:
2851 //
2852 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002853 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002854
2855 // -- if T is an array type, then each element is value-initialized;
2856 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2857 T = AT->getElementType();
2858
2859 if (const RecordType *RT = T->getAs<RecordType>()) {
2860 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2861 // -- if T is a class type (clause 9) with a user-declared
2862 // constructor (12.1), then the default constructor for T is
2863 // called (and the initialization is ill-formed if T has no
2864 // accessible default constructor);
2865 //
2866 // FIXME: we really want to refer to a single subobject of the array,
2867 // but Entity doesn't have a way to capture that (yet).
2868 if (ClassDecl->hasUserDeclaredConstructor())
2869 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2870
Douglas Gregor16006c92009-12-16 18:50:27 +00002871 // -- if T is a (possibly cv-qualified) non-union class type
2872 // without a user-provided constructor, then the object is
2873 // zero-initialized and, if T’s implicitly-declared default
2874 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002875 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002876 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002877 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002878 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2879 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002880 }
2881 }
2882
Douglas Gregord6542d82009-12-22 15:35:07 +00002883 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002884 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2885}
2886
Douglas Gregor99a2e602009-12-16 01:38:02 +00002887/// \brief Attempt default initialization (C++ [dcl.init]p6).
2888static void TryDefaultInitialization(Sema &S,
2889 const InitializedEntity &Entity,
2890 const InitializationKind &Kind,
2891 InitializationSequence &Sequence) {
2892 assert(Kind.getKind() == InitializationKind::IK_Default);
2893
2894 // C++ [dcl.init]p6:
2895 // To default-initialize an object of type T means:
2896 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002897 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002898 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2899 DestType = Array->getElementType();
2900
2901 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2902 // constructor for T is called (and the initialization is ill-formed if
2903 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002904 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00002905 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2906 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002907 }
2908
2909 // - otherwise, no initialization is performed.
2910 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2911
2912 // If a program calls for the default initialization of an object of
2913 // a const-qualified type T, T shall be a class type with a user-provided
2914 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002915 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002916 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2917}
2918
Douglas Gregor20093b42009-12-09 23:02:17 +00002919/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2920/// which enumerates all conversion functions and performs overload resolution
2921/// to select the best.
2922static void TryUserDefinedConversion(Sema &S,
2923 const InitializedEntity &Entity,
2924 const InitializationKind &Kind,
2925 Expr *Initializer,
2926 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002927 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2928
Douglas Gregord6542d82009-12-22 15:35:07 +00002929 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002930 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2931 QualType SourceType = Initializer->getType();
2932 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2933 "Must have a class type to perform a user-defined conversion");
2934
2935 // Build the candidate set directly in the initialization sequence
2936 // structure, so that it will persist if we fail.
2937 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2938 CandidateSet.clear();
2939
2940 // Determine whether we are allowed to call explicit constructors or
2941 // explicit conversion operators.
2942 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2943
2944 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2945 // The type we're converting to is a class type. Enumerate its constructors
2946 // to see if there is a suitable conversion.
2947 CXXRecordDecl *DestRecordDecl
2948 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2949
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002950 // Try to complete the type we're converting to.
2951 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002952 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002953 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002954 Con != ConEnd; ++Con) {
2955 NamedDecl *D = *Con;
2956 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002957
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002958 // Find the constructor (which may be a template).
2959 CXXConstructorDecl *Constructor = 0;
2960 FunctionTemplateDecl *ConstructorTmpl
2961 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002962 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002963 Constructor = cast<CXXConstructorDecl>(
2964 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002965 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002966 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002967
2968 if (!Constructor->isInvalidDecl() &&
2969 Constructor->isConvertingConstructor(AllowExplicit)) {
2970 if (ConstructorTmpl)
2971 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2972 /*ExplicitArgs*/ 0,
2973 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002974 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002975 else
2976 S.AddOverloadCandidate(Constructor, FoundDecl,
2977 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002978 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002979 }
2980 }
2981 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002982 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002983
2984 SourceLocation DeclLoc = Initializer->getLocStart();
2985
Douglas Gregor4a520a22009-12-14 17:27:33 +00002986 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2987 // The type we're converting from is a class type, enumerate its conversion
2988 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002989
Eli Friedman33c2da92009-12-20 22:12:03 +00002990 // We can only enumerate the conversion functions for a complete type; if
2991 // the type isn't complete, simply skip this step.
2992 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2993 CXXRecordDecl *SourceRecordDecl
2994 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002995
John McCalleec51cf2010-01-20 00:46:10 +00002996 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002997 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002998 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002999 E = Conversions->end();
3000 I != E; ++I) {
3001 NamedDecl *D = *I;
3002 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3003 if (isa<UsingShadowDecl>(D))
3004 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3005
3006 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3007 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003008 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003009 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003010 else
John McCall32daa422010-03-31 01:36:47 +00003011 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00003012
3013 if (AllowExplicit || !Conv->isExplicit()) {
3014 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003015 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003016 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003017 CandidateSet);
3018 else
John McCall9aa472c2010-03-19 07:35:19 +00003019 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003020 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003021 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003022 }
3023 }
3024 }
3025
Douglas Gregor4a520a22009-12-14 17:27:33 +00003026 // Perform overload resolution. If it fails, return the failed result.
3027 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003028 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003029 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003030 Sequence.SetOverloadFailure(
3031 InitializationSequence::FK_UserConversionOverloadFailed,
3032 Result);
3033 return;
3034 }
John McCall1d318332010-01-12 00:44:57 +00003035
Douglas Gregor4a520a22009-12-14 17:27:33 +00003036 FunctionDecl *Function = Best->Function;
3037
3038 if (isa<CXXConstructorDecl>(Function)) {
3039 // Add the user-defined conversion step. Any cv-qualification conversion is
3040 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003041 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003042 return;
3043 }
3044
3045 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003046 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003047 if (ConvType->getAs<RecordType>()) {
3048 // If we're converting to a class type, there may be an copy if
3049 // the resulting temporary object (possible to create an object of
3050 // a base class type). That copy is not a separate conversion, so
3051 // we just make a note of the actual destination type (possibly a
3052 // base class of the type returned by the conversion function) and
3053 // let the user-defined conversion step handle the conversion.
3054 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3055 return;
3056 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003057
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003058 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3059
3060 // If the conversion following the call to the conversion function
3061 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003062 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3063 Best->FinalConversion.Third) {
3064 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003065 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003066 ICS.Standard = Best->FinalConversion;
3067 Sequence.AddConversionSequenceStep(ICS, DestType);
3068 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003069}
3070
Douglas Gregor20093b42009-12-09 23:02:17 +00003071InitializationSequence::InitializationSequence(Sema &S,
3072 const InitializedEntity &Entity,
3073 const InitializationKind &Kind,
3074 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003075 unsigned NumArgs)
3076 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003077 ASTContext &Context = S.Context;
3078
3079 // C++0x [dcl.init]p16:
3080 // The semantics of initializers are as follows. The destination type is
3081 // the type of the object or reference being initialized and the source
3082 // type is the type of the initializer expression. The source type is not
3083 // defined when the initializer is a braced-init-list or when it is a
3084 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003085 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003086
3087 if (DestType->isDependentType() ||
3088 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3089 SequenceKind = DependentSequence;
3090 return;
3091 }
3092
3093 QualType SourceType;
3094 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003095 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003096 Initializer = Args[0];
3097 if (!isa<InitListExpr>(Initializer))
3098 SourceType = Initializer->getType();
3099 }
3100
3101 // - If the initializer is a braced-init-list, the object is
3102 // list-initialized (8.5.4).
3103 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3104 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003105 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003106 }
3107
3108 // - If the destination type is a reference type, see 8.5.3.
3109 if (DestType->isReferenceType()) {
3110 // C++0x [dcl.init.ref]p1:
3111 // A variable declared to be a T& or T&&, that is, "reference to type T"
3112 // (8.3.2), shall be initialized by an object, or function, of type T or
3113 // by an object that can be converted into a T.
3114 // (Therefore, multiple arguments are not permitted.)
3115 if (NumArgs != 1)
3116 SetFailed(FK_TooManyInitsForReference);
3117 else
3118 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3119 return;
3120 }
3121
3122 // - If the destination type is an array of characters, an array of
3123 // char16_t, an array of char32_t, or an array of wchar_t, and the
3124 // initializer is a string literal, see 8.5.2.
3125 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3126 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3127 return;
3128 }
3129
3130 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003131 if (Kind.getKind() == InitializationKind::IK_Value ||
3132 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003133 TryValueInitialization(S, Entity, Kind, *this);
3134 return;
3135 }
3136
Douglas Gregor99a2e602009-12-16 01:38:02 +00003137 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003138 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003139 TryDefaultInitialization(S, Entity, Kind, *this);
3140 return;
3141 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003142
Douglas Gregor20093b42009-12-09 23:02:17 +00003143 // - Otherwise, if the destination type is an array, the program is
3144 // ill-formed.
3145 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3146 if (AT->getElementType()->isAnyCharacterType())
3147 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3148 else
3149 SetFailed(FK_ArrayNeedsInitList);
3150
3151 return;
3152 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003153
3154 // Handle initialization in C
3155 if (!S.getLangOptions().CPlusPlus) {
3156 setSequenceKind(CAssignment);
3157 AddCAssignmentStep(DestType);
3158 return;
3159 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003160
3161 // - If the destination type is a (possibly cv-qualified) class type:
3162 if (DestType->isRecordType()) {
3163 // - If the initialization is direct-initialization, or if it is
3164 // copy-initialization where the cv-unqualified version of the
3165 // source type is the same class as, or a derived class of, the
3166 // class of the destination, constructors are considered. [...]
3167 if (Kind.getKind() == InitializationKind::IK_Direct ||
3168 (Kind.getKind() == InitializationKind::IK_Copy &&
3169 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3170 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003171 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003172 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003173 // - Otherwise (i.e., for the remaining copy-initialization cases),
3174 // user-defined conversion sequences that can convert from the source
3175 // type to the destination type or (when a conversion function is
3176 // used) to a derived class thereof are enumerated as described in
3177 // 13.3.1.4, and the best one is chosen through overload resolution
3178 // (13.3).
3179 else
3180 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3181 return;
3182 }
3183
Douglas Gregor99a2e602009-12-16 01:38:02 +00003184 if (NumArgs > 1) {
3185 SetFailed(FK_TooManyInitsForScalar);
3186 return;
3187 }
3188 assert(NumArgs == 1 && "Zero-argument case handled above");
3189
Douglas Gregor20093b42009-12-09 23:02:17 +00003190 // - Otherwise, if the source type is a (possibly cv-qualified) class
3191 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003192 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003193 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3194 return;
3195 }
3196
3197 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003198 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003199 // conversions (Clause 4) will be used, if necessary, to convert the
3200 // initializer expression to the cv-unqualified version of the
3201 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003202 if (S.TryImplicitConversion(*this, Entity, Initializer,
3203 /*SuppressUserConversions*/ true,
3204 /*AllowExplicitConversions*/ false,
3205 /*InOverloadResolution*/ false))
Douglas Gregor8e960432010-11-08 03:40:48 +00003206 {
3207 if (Initializer->getType() == Context.OverloadTy )
3208 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3209 else
3210 SetFailed(InitializationSequence::FK_ConversionFailed);
3211 }
John McCall369371c2010-06-04 02:29:22 +00003212 else
3213 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003214}
3215
3216InitializationSequence::~InitializationSequence() {
3217 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3218 StepEnd = Steps.end();
3219 Step != StepEnd; ++Step)
3220 Step->Destroy();
3221}
3222
3223//===----------------------------------------------------------------------===//
3224// Perform initialization
3225//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003226static Sema::AssignmentAction
3227getAssignmentAction(const InitializedEntity &Entity) {
3228 switch(Entity.getKind()) {
3229 case InitializedEntity::EK_Variable:
3230 case InitializedEntity::EK_New:
3231 return Sema::AA_Initializing;
3232
3233 case InitializedEntity::EK_Parameter:
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003234 if (Entity.getDecl() &&
3235 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3236 return Sema::AA_Sending;
3237
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003238 return Sema::AA_Passing;
3239
3240 case InitializedEntity::EK_Result:
3241 return Sema::AA_Returning;
3242
3243 case InitializedEntity::EK_Exception:
3244 case InitializedEntity::EK_Base:
3245 llvm_unreachable("No assignment action for C++-specific initialization");
3246 break;
3247
3248 case InitializedEntity::EK_Temporary:
3249 // FIXME: Can we tell apart casting vs. converting?
3250 return Sema::AA_Casting;
3251
3252 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003253 case InitializedEntity::EK_ArrayElement:
3254 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003255 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003256 return Sema::AA_Initializing;
3257 }
3258
3259 return Sema::AA_Converting;
3260}
3261
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003262/// \brief Whether we should binding a created object as a temporary when
3263/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003264static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003265 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003266 case InitializedEntity::EK_ArrayElement:
3267 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003268 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003269 case InitializedEntity::EK_New:
3270 case InitializedEntity::EK_Variable:
3271 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003272 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003273 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003274 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003275 return false;
3276
3277 case InitializedEntity::EK_Parameter:
3278 case InitializedEntity::EK_Temporary:
3279 return true;
3280 }
3281
3282 llvm_unreachable("missed an InitializedEntity kind?");
3283}
3284
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003285/// \brief Whether the given entity, when initialized with an object
3286/// created for that initialization, requires destruction.
3287static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3288 switch (Entity.getKind()) {
3289 case InitializedEntity::EK_Member:
3290 case InitializedEntity::EK_Result:
3291 case InitializedEntity::EK_New:
3292 case InitializedEntity::EK_Base:
3293 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003294 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003295 return false;
3296
3297 case InitializedEntity::EK_Variable:
3298 case InitializedEntity::EK_Parameter:
3299 case InitializedEntity::EK_Temporary:
3300 case InitializedEntity::EK_ArrayElement:
3301 case InitializedEntity::EK_Exception:
3302 return true;
3303 }
3304
3305 llvm_unreachable("missed an InitializedEntity kind?");
3306}
3307
Douglas Gregor523d46a2010-04-18 07:40:54 +00003308/// \brief Make a (potentially elidable) temporary copy of the object
3309/// provided by the given initializer by calling the appropriate copy
3310/// constructor.
3311///
3312/// \param S The Sema object used for type-checking.
3313///
3314/// \param T The type of the temporary object, which must either by
3315/// the type of the initializer expression or a superclass thereof.
3316///
3317/// \param Enter The entity being initialized.
3318///
3319/// \param CurInit The initializer expression.
3320///
3321/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3322/// is permitted in C++03 (but not C++0x) when binding a reference to
3323/// an rvalue.
3324///
3325/// \returns An expression that copies the initializer expression into
3326/// a temporary object, or an error expression if a copy could not be
3327/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003328static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003329 QualType T,
3330 const InitializedEntity &Entity,
3331 ExprResult CurInit,
3332 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003333 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003334 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003335 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003336 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003337 Class = cast<CXXRecordDecl>(Record->getDecl());
3338 if (!Class)
3339 return move(CurInit);
3340
3341 // C++0x [class.copy]p34:
3342 // When certain criteria are met, an implementation is allowed to
3343 // omit the copy/move construction of a class object, even if the
3344 // copy/move constructor and/or destructor for the object have
3345 // side effects. [...]
3346 // - when a temporary class object that has not been bound to a
3347 // reference (12.2) would be copied/moved to a class object
3348 // with the same cv-unqualified type, the copy/move operation
3349 // can be omitted by constructing the temporary object
3350 // directly into the target of the omitted copy/move
3351 //
3352 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003353 // elision for return statements and throw expressions are handled as part
3354 // of constructor initialization, while copy elision for exception handlers
3355 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003356 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003357 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003358 switch (Entity.getKind()) {
3359 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003360 Loc = Entity.getReturnLoc();
3361 break;
3362
3363 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003364 Loc = Entity.getThrowLoc();
3365 break;
3366
3367 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003368 Loc = Entity.getDecl()->getLocation();
3369 break;
3370
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003371 case InitializedEntity::EK_ArrayElement:
3372 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003373 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003374 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003375 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003376 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003377 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003378 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003379 Loc = CurInitExpr->getLocStart();
3380 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003381 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003382
3383 // Make sure that the type we are copying is complete.
3384 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3385 return move(CurInit);
3386
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003387 // Perform overload resolution using the class's copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003388 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003389 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003390 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003391 Con != ConEnd; ++Con) {
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003392 // Only consider copy constructors and constructor templates. Per
3393 // C++0x [dcl.init]p16, second bullet to class types, this
3394 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003395 CXXConstructorDecl *Constructor = 0;
3396
3397 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
3398 // Handle copy constructors, only.
3399 if (!Constructor || Constructor->isInvalidDecl() ||
3400 !Constructor->isCopyConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003401 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003402 continue;
3403
3404 DeclAccessPair FoundDecl
3405 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3406 S.AddOverloadCandidate(Constructor, FoundDecl,
3407 &CurInitExpr, 1, CandidateSet);
3408 continue;
3409 }
3410
3411 // Handle constructor templates.
3412 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3413 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003414 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003415
Douglas Gregor6493cc52010-11-08 17:16:59 +00003416 Constructor = cast<CXXConstructorDecl>(
3417 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003418 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003419 continue;
3420
3421 // FIXME: Do we need to limit this to copy-constructor-like
3422 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003423 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003424 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3425 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3426 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003427 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003428
3429 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00003430 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003431 case OR_Success:
3432 break;
3433
3434 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003435 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3436 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3437 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003438 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003439 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003440 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003441 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003442 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003443 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003444
3445 case OR_Ambiguous:
3446 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003447 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003448 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003449 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003450 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003451
3452 case OR_Deleted:
3453 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003454 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003455 << CurInitExpr->getSourceRange();
3456 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3457 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003458 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003459 }
3460
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003461 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003462 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003463 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003464
Anders Carlsson9a68a672010-04-21 18:47:17 +00003465 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003466 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003467
3468 if (IsExtraneousCopy) {
3469 // If this is a totally extraneous copy for C++03 reference
3470 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003471 // expression. We don't generate an (elided) copy operation here
3472 // because doing so would require us to pass down a flag to avoid
3473 // infinite recursion, where each step adds another extraneous,
3474 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003475
Douglas Gregor2559a702010-04-18 07:57:34 +00003476 // Instantiate the default arguments of any extra parameters in
3477 // the selected copy constructor, as if we were going to create a
3478 // proper call to the copy constructor.
3479 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3480 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3481 if (S.RequireCompleteType(Loc, Parm->getType(),
3482 S.PDiag(diag::err_call_incomplete_argument)))
3483 break;
3484
3485 // Build the default argument expression; we don't actually care
3486 // if this succeeds or not, because this routine will complain
3487 // if there was a problem.
3488 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3489 }
3490
Douglas Gregor523d46a2010-04-18 07:40:54 +00003491 return S.Owned(CurInitExpr);
3492 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003493
3494 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003495 // constructor call (we might have derived-to-base conversions, or
3496 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003497 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003498 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003499 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003500
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003501 // Actually perform the constructor call.
3502 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003503 move_arg(ConstructorArgs),
3504 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003505 CXXConstructExpr::CK_Complete,
3506 SourceRange());
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003507
3508 // If we're supposed to bind temporaries, do so.
3509 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3510 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3511 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003512}
Douglas Gregor20093b42009-12-09 23:02:17 +00003513
Douglas Gregora41a8c52010-04-22 00:20:18 +00003514void InitializationSequence::PrintInitLocationNote(Sema &S,
3515 const InitializedEntity &Entity) {
3516 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3517 if (Entity.getDecl()->getLocation().isInvalid())
3518 return;
3519
3520 if (Entity.getDecl()->getDeclName())
3521 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3522 << Entity.getDecl()->getDeclName();
3523 else
3524 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3525 }
3526}
3527
John McCall60d7b3a2010-08-24 06:29:42 +00003528ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003529InitializationSequence::Perform(Sema &S,
3530 const InitializedEntity &Entity,
3531 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003532 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003533 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003534 if (SequenceKind == FailedSequence) {
3535 unsigned NumArgs = Args.size();
3536 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003537 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003538 }
3539
3540 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003541 // If the declaration is a non-dependent, incomplete array type
3542 // that has an initializer, then its type will be completed once
3543 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003544 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003545 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003546 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003547 if (const IncompleteArrayType *ArrayT
3548 = S.Context.getAsIncompleteArrayType(DeclType)) {
3549 // FIXME: We don't currently have the ability to accurately
3550 // compute the length of an initializer list without
3551 // performing full type-checking of the initializer list
3552 // (since we have to determine where braces are implicitly
3553 // introduced and such). So, we fall back to making the array
3554 // type a dependently-sized array type with no specified
3555 // bound.
3556 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3557 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003558
Douglas Gregord87b61f2009-12-10 17:56:55 +00003559 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003560 if (DeclaratorDecl *DD = Entity.getDecl()) {
3561 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3562 TypeLoc TL = TInfo->getTypeLoc();
3563 if (IncompleteArrayTypeLoc *ArrayLoc
3564 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3565 Brackets = ArrayLoc->getBracketsRange();
3566 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003567 }
3568
3569 *ResultType
3570 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3571 /*NumElts=*/0,
3572 ArrayT->getSizeModifier(),
3573 ArrayT->getIndexTypeCVRQualifiers(),
3574 Brackets);
3575 }
3576
3577 }
3578 }
3579
Eli Friedman08544622009-12-22 02:35:53 +00003580 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003581 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003582
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003583 if (Args.size() == 0)
3584 return S.Owned((Expr *)0);
3585
Douglas Gregor20093b42009-12-09 23:02:17 +00003586 unsigned NumArgs = Args.size();
3587 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3588 SourceLocation(),
3589 (Expr **)Args.release(),
3590 NumArgs,
3591 SourceLocation()));
3592 }
3593
Douglas Gregor99a2e602009-12-16 01:38:02 +00003594 if (SequenceKind == NoInitialization)
3595 return S.Owned((Expr *)0);
3596
Douglas Gregord6542d82009-12-22 15:35:07 +00003597 QualType DestType = Entity.getType().getNonReferenceType();
3598 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003599 // the same as Entity.getDecl()->getType() in cases involving type merging,
3600 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003601 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003602 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003603 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003604
John McCall60d7b3a2010-08-24 06:29:42 +00003605 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003606
3607 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3608
3609 // For initialization steps that start with a single initializer,
3610 // grab the only argument out the Args and place it into the "current"
3611 // initializer.
3612 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003613 case SK_ResolveAddressOfOverloadedFunction:
3614 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003615 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003616 case SK_CastDerivedToBaseLValue:
3617 case SK_BindReference:
3618 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003619 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003620 case SK_UserConversion:
3621 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003622 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003623 case SK_QualificationConversionRValue:
3624 case SK_ConversionSequence:
3625 case SK_ListInitialization:
3626 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003627 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00003628 case SK_ObjCObjectConversion:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003629 assert(Args.size() == 1);
John McCall3fa5cae2010-10-26 07:05:15 +00003630 CurInit = ExprResult(Args.get()[0]);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003631 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003632 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003633 break;
3634
3635 case SK_ConstructorInitialization:
3636 case SK_ZeroInitialization:
3637 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003638 }
3639
3640 // Walk through the computed steps for the initialization sequence,
3641 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003642 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003643 for (step_iterator Step = step_begin(), StepEnd = step_end();
3644 Step != StepEnd; ++Step) {
3645 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003646 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003647
3648 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003649 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003650
3651 switch (Step->Kind) {
3652 case SK_ResolveAddressOfOverloadedFunction:
3653 // Overload resolution determined which function invoke; update the
3654 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003655 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003656 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003657 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003658 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003659 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003660 break;
3661
3662 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003663 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003664 case SK_CastDerivedToBaseLValue: {
3665 // We have a derived-to-base cast that produces either an rvalue or an
3666 // lvalue. Perform that cast.
3667
John McCallf871d0c2010-08-07 06:22:56 +00003668 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003669
Douglas Gregor20093b42009-12-09 23:02:17 +00003670 // Casts to inaccessible base classes are allowed with C-style casts.
3671 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3672 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3673 CurInitExpr->getLocStart(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003674 CurInitExpr->getSourceRange(),
3675 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003676 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003677
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003678 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3679 QualType T = SourceType;
3680 if (const PointerType *Pointer = T->getAs<PointerType>())
3681 T = Pointer->getPointeeType();
3682 if (const RecordType *RecordTy = T->getAs<RecordType>())
3683 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3684 cast<CXXRecordDecl>(RecordTy->getDecl()));
3685 }
3686
John McCall5baba9d2010-08-25 10:28:54 +00003687 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003688 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003689 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003690 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003691 VK_XValue :
3692 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00003693 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3694 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003695 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00003696 CurInit.get(),
3697 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00003698 break;
3699 }
3700
3701 case SK_BindReference:
3702 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3703 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3704 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003705 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003706 << BitField->getDeclName()
3707 << CurInitExpr->getSourceRange();
3708 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00003709 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003711
Anders Carlsson09380262010-01-31 17:18:49 +00003712 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003713 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003714 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3715 << Entity.getType().isVolatileQualified()
3716 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003717 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003718 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00003719 }
3720
Douglas Gregor20093b42009-12-09 23:02:17 +00003721 // Reference binding does not have any corresponding ASTs.
3722
3723 // Check exception specifications
3724 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003725 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003726
Douglas Gregor20093b42009-12-09 23:02:17 +00003727 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003728
Douglas Gregor20093b42009-12-09 23:02:17 +00003729 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003730 // Reference binding does not have any corresponding ASTs.
3731
Douglas Gregor20093b42009-12-09 23:02:17 +00003732 // Check exception specifications
3733 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003734 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003735
Douglas Gregor20093b42009-12-09 23:02:17 +00003736 break;
3737
Douglas Gregor523d46a2010-04-18 07:40:54 +00003738 case SK_ExtraneousCopyToTemporary:
3739 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3740 /*IsExtraneousCopy=*/true);
3741 break;
3742
Douglas Gregor20093b42009-12-09 23:02:17 +00003743 case SK_UserConversion: {
3744 // We have a user-defined conversion that invokes either a constructor
3745 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00003746 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003747 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003748 FunctionDecl *Fn = Step->Function.Function;
3749 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003750 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003751 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003752 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003753 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003754 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor20093b42009-12-09 23:02:17 +00003755 SourceLocation Loc = CurInitExpr->getLocStart();
3756 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003757
Douglas Gregor20093b42009-12-09 23:02:17 +00003758 // Determine the arguments required to actually perform the constructor
3759 // call.
3760 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00003761 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00003762 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003763 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003764
3765 // Build the an expression that constructs a temporary.
3766 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00003767 move_arg(ConstructorArgs),
3768 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003769 CXXConstructExpr::CK_Complete,
3770 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00003771 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003772 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003773
Anders Carlsson9a68a672010-04-21 18:47:17 +00003774 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003775 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003776 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor20093b42009-12-09 23:02:17 +00003777
John McCall2de56d12010-08-25 11:45:40 +00003778 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003779 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3780 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3781 S.IsDerivedFrom(SourceType, Class))
3782 IsCopy = true;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003783
3784 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003785 } else {
3786 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003787 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003788 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003789 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003790 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003791 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003792
Douglas Gregor20093b42009-12-09 23:02:17 +00003793 // FIXME: Should we move this initialization into a separate
3794 // derived-to-base conversion? I believe the answer is "no", because
3795 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003796 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003797 FoundFn, Conversion))
John McCallf312b1e2010-08-26 23:41:50 +00003798 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003799
3800 // Do a little dance to make sure that CurInit has the proper
3801 // pointer.
3802 CurInit.release();
3803
3804 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003805 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3806 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003807 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00003808 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003809
John McCall2de56d12010-08-25 11:45:40 +00003810 CastKind = CK_UserDefinedConversion;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003811
3812 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003813 }
3814
Douglas Gregor2f599792010-04-02 18:24:57 +00003815 bool RequiresCopy = !IsCopy &&
3816 getKind() != InitializationSequence::ReferenceBinding;
3817 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003818 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003819 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3820 CurInitExpr = static_cast<Expr *>(CurInit.get());
3821 QualType T = CurInitExpr->getType();
3822 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00003823 CXXDestructorDecl *Destructor
3824 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003825 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3826 S.PDiag(diag::err_access_dtor_temp) << T);
3827 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003828 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003829 }
3830 }
3831
Douglas Gregor20093b42009-12-09 23:02:17 +00003832 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redl906082e2010-07-20 04:20:21 +00003833 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00003834 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3835 CurInitExpr->getType(),
3836 CastKind, CurInitExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00003837 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003838
Douglas Gregor2f599792010-04-02 18:24:57 +00003839 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003840 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3841 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003842
Douglas Gregor20093b42009-12-09 23:02:17 +00003843 break;
3844 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003845
Douglas Gregor20093b42009-12-09 23:02:17 +00003846 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003847 case SK_QualificationConversionXValue:
3848 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003849 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00003850 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003851 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003852 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003853 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003854 VK_XValue :
3855 VK_RValue);
John McCall2de56d12010-08-25 11:45:40 +00003856 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00003857 CurInit.release();
3858 CurInit = S.Owned(CurInitExpr);
3859 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003860 }
3861
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003862 case SK_ConversionSequence: {
3863 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3864
3865 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3866 Sema::AA_Converting, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003867 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003868
3869 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003870 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003871 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003872 }
3873
Douglas Gregord87b61f2009-12-10 17:56:55 +00003874 case SK_ListInitialization: {
3875 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3876 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003877 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00003878 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003879
3880 CurInit.release();
3881 CurInit = S.Owned(InitList);
3882 break;
3883 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003884
3885 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003886 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003887 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003888 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003889
Douglas Gregor51c56d62009-12-14 20:49:26 +00003890 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003891 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00003892 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3893 ? Kind.getEqualLoc()
3894 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003895
3896 if (Kind.getKind() == InitializationKind::IK_Default) {
3897 // Force even a trivial, implicit default constructor to be
3898 // semantically checked. We do this explicitly because we don't build
3899 // the definition for completely trivial constructors.
3900 CXXRecordDecl *ClassDecl = Constructor->getParent();
3901 assert(ClassDecl && "No parent class for constructor.");
3902 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3903 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3904 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3905 }
3906
Douglas Gregor51c56d62009-12-14 20:49:26 +00003907 // Determine the arguments required to actually perform the constructor
3908 // call.
3909 if (S.CompleteConstructorCall(Constructor, move(Args),
3910 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003911 return ExprError();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003912
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003913
Douglas Gregor91be6f52010-03-02 17:18:33 +00003914 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003915 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003916 (Kind.getKind() == InitializationKind::IK_Direct ||
3917 Kind.getKind() == InitializationKind::IK_Value)) {
3918 // An explicitly-constructed temporary, e.g., X(1, 2).
3919 unsigned NumExprs = ConstructorArgs.size();
3920 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003921 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003922 S.DiagnoseUseOfDecl(Constructor, Loc);
3923
Douglas Gregorab6677e2010-09-08 00:15:04 +00003924 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3925 if (!TSInfo)
3926 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3927
Douglas Gregor91be6f52010-03-02 17:18:33 +00003928 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3929 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00003930 TSInfo,
Douglas Gregor91be6f52010-03-02 17:18:33 +00003931 Exprs,
3932 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003933 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003934 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003935 } else {
3936 CXXConstructExpr::ConstructionKind ConstructKind =
3937 CXXConstructExpr::CK_Complete;
3938
3939 if (Entity.getKind() == InitializedEntity::EK_Base) {
3940 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3941 CXXConstructExpr::CK_VirtualBase :
3942 CXXConstructExpr::CK_NonVirtualBase;
3943 }
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003944
Chandler Carruth428edaf2010-10-25 08:47:36 +00003945 // Only get the parenthesis range if it is a direct construction.
3946 SourceRange parenRange =
3947 Kind.getKind() == InitializationKind::IK_Direct ?
3948 Kind.getParenRange() : SourceRange();
3949
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003950 // If the entity allows NRVO, mark the construction as elidable
3951 // unconditionally.
3952 if (Entity.allowsNRVO())
3953 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3954 Constructor, /*Elidable=*/true,
3955 move_arg(ConstructorArgs),
3956 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003957 ConstructKind,
3958 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003959 else
3960 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3961 Constructor,
3962 move_arg(ConstructorArgs),
3963 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003964 ConstructKind,
3965 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003966 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003967 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003968 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003969
3970 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00003971 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003972 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003973 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003974
Douglas Gregor2f599792010-04-02 18:24:57 +00003975 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003976 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003977
Douglas Gregor51c56d62009-12-14 20:49:26 +00003978 break;
3979 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003980
3981 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003982 step_iterator NextStep = Step;
3983 ++NextStep;
3984 if (NextStep != StepEnd &&
3985 NextStep->Kind == SK_ConstructorInitialization) {
3986 // The need for zero-initialization is recorded directly into
3987 // the call to the object's constructor within the next step.
3988 ConstructorInitRequiresZeroInit = true;
3989 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3990 S.getLangOptions().CPlusPlus &&
3991 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00003992 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3993 if (!TSInfo)
3994 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
3995 Kind.getRange().getBegin());
3996
3997 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
3998 TSInfo->getType().getNonLValueExprType(S.Context),
3999 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004000 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004001 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004002 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004003 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004004 break;
4005 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004006
4007 case SK_CAssignment: {
4008 QualType SourceType = CurInitExpr->getType();
4009 Sema::AssignConvertType ConvTy =
4010 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00004011
4012 // If this is a call, allow conversion to a transparent union.
4013 if (ConvTy != Sema::Compatible &&
4014 Entity.getKind() == InitializedEntity::EK_Parameter &&
4015 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4016 == Sema::Compatible)
4017 ConvTy = Sema::Compatible;
4018
Douglas Gregora41a8c52010-04-22 00:20:18 +00004019 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004020 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4021 Step->Type, SourceType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00004022 CurInitExpr,
4023 getAssignmentAction(Entity),
4024 &Complained)) {
4025 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004026 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004027 } else if (Complained)
4028 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004029
4030 CurInit.release();
4031 CurInit = S.Owned(CurInitExpr);
4032 break;
4033 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004034
4035 case SK_StringInit: {
4036 QualType Ty = Step->Type;
4037 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
4038 break;
4039 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004040
4041 case SK_ObjCObjectConversion:
4042 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004043 CK_ObjCObjectLValueCast,
Douglas Gregor569c3162010-08-07 11:51:51 +00004044 S.CastCategory(CurInitExpr));
4045 CurInit.release();
4046 CurInit = S.Owned(CurInitExpr);
4047 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004048 }
4049 }
John McCall15d7d122010-11-11 03:21:53 +00004050
4051 // Diagnose non-fatal problems with the completed initialization.
4052 if (Entity.getKind() == InitializedEntity::EK_Member &&
4053 cast<FieldDecl>(Entity.getDecl())->isBitField())
4054 S.CheckBitFieldInitialization(Kind.getLocation(),
4055 cast<FieldDecl>(Entity.getDecl()),
4056 CurInit.get());
Douglas Gregor20093b42009-12-09 23:02:17 +00004057
4058 return move(CurInit);
4059}
4060
4061//===----------------------------------------------------------------------===//
4062// Diagnose initialization failures
4063//===----------------------------------------------------------------------===//
4064bool InitializationSequence::Diagnose(Sema &S,
4065 const InitializedEntity &Entity,
4066 const InitializationKind &Kind,
4067 Expr **Args, unsigned NumArgs) {
4068 if (SequenceKind != FailedSequence)
4069 return false;
4070
Douglas Gregord6542d82009-12-22 15:35:07 +00004071 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004072 switch (Failure) {
4073 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004074 // FIXME: Customize for the initialized entity?
4075 if (NumArgs == 0)
4076 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4077 << DestType.getNonReferenceType();
4078 else // FIXME: diagnostic below could be better!
4079 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4080 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004081 break;
4082
4083 case FK_ArrayNeedsInitList:
4084 case FK_ArrayNeedsInitListOrStringLiteral:
4085 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4086 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4087 break;
4088
John McCall6bb80172010-03-30 21:47:33 +00004089 case FK_AddressOfOverloadFailed: {
4090 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00004091 S.ResolveAddressOfOverloadedFunction(Args[0],
4092 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004093 true,
4094 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004095 break;
John McCall6bb80172010-03-30 21:47:33 +00004096 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004097
4098 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004099 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004100 switch (FailedOverloadResult) {
4101 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004102 if (Failure == FK_UserConversionOverloadFailed)
4103 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4104 << Args[0]->getType() << DestType
4105 << Args[0]->getSourceRange();
4106 else
4107 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4108 << DestType << Args[0]->getType()
4109 << Args[0]->getSourceRange();
4110
John McCall120d63c2010-08-24 20:38:10 +00004111 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004112 break;
4113
4114 case OR_No_Viable_Function:
4115 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4116 << Args[0]->getType() << DestType.getNonReferenceType()
4117 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004118 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004119 break;
4120
4121 case OR_Deleted: {
4122 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4123 << Args[0]->getType() << DestType.getNonReferenceType()
4124 << Args[0]->getSourceRange();
4125 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004126 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004127 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4128 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004129 if (Ovl == OR_Deleted) {
4130 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4131 << Best->Function->isDeleted();
4132 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004133 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004134 }
4135 break;
4136 }
4137
4138 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004139 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004140 break;
4141 }
4142 break;
4143
4144 case FK_NonConstLValueReferenceBindingToTemporary:
4145 case FK_NonConstLValueReferenceBindingToUnrelated:
4146 S.Diag(Kind.getLocation(),
4147 Failure == FK_NonConstLValueReferenceBindingToTemporary
4148 ? diag::err_lvalue_reference_bind_to_temporary
4149 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004150 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004151 << DestType.getNonReferenceType()
4152 << Args[0]->getType()
4153 << Args[0]->getSourceRange();
4154 break;
4155
4156 case FK_RValueReferenceBindingToLValue:
4157 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4158 << Args[0]->getSourceRange();
4159 break;
4160
4161 case FK_ReferenceInitDropsQualifiers:
4162 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4163 << DestType.getNonReferenceType()
4164 << Args[0]->getType()
4165 << Args[0]->getSourceRange();
4166 break;
4167
4168 case FK_ReferenceInitFailed:
4169 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4170 << DestType.getNonReferenceType()
4171 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4172 << Args[0]->getType()
4173 << Args[0]->getSourceRange();
4174 break;
4175
4176 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004177 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4178 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004179 << DestType
4180 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4181 << Args[0]->getType()
4182 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004183 break;
4184
4185 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004186 SourceRange R;
4187
4188 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004189 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004190 InitList->getLocEnd());
Douglas Gregor19311e72010-09-08 21:40:08 +00004191 else
4192 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004193
Douglas Gregor19311e72010-09-08 21:40:08 +00004194 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4195 if (Kind.isCStyleOrFunctionalCast())
4196 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4197 << R;
4198 else
4199 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4200 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004201 break;
4202 }
4203
4204 case FK_ReferenceBindingToInitList:
4205 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4206 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4207 break;
4208
4209 case FK_InitListBadDestinationType:
4210 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4211 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4212 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00004213
4214 case FK_ConstructorOverloadFailed: {
4215 SourceRange ArgsRange;
4216 if (NumArgs)
4217 ArgsRange = SourceRange(Args[0]->getLocStart(),
4218 Args[NumArgs - 1]->getLocEnd());
4219
4220 // FIXME: Using "DestType" for the entity we're printing is probably
4221 // bad.
4222 switch (FailedOverloadResult) {
4223 case OR_Ambiguous:
4224 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4225 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004226 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4227 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004228 break;
4229
4230 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004231 if (Kind.getKind() == InitializationKind::IK_Default &&
4232 (Entity.getKind() == InitializedEntity::EK_Base ||
4233 Entity.getKind() == InitializedEntity::EK_Member) &&
4234 isa<CXXConstructorDecl>(S.CurContext)) {
4235 // This is implicit default initialization of a member or
4236 // base within a constructor. If no viable function was
4237 // found, notify the user that she needs to explicitly
4238 // initialize this base/member.
4239 CXXConstructorDecl *Constructor
4240 = cast<CXXConstructorDecl>(S.CurContext);
4241 if (Entity.getKind() == InitializedEntity::EK_Base) {
4242 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4243 << Constructor->isImplicit()
4244 << S.Context.getTypeDeclType(Constructor->getParent())
4245 << /*base=*/0
4246 << Entity.getType();
4247
4248 RecordDecl *BaseDecl
4249 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4250 ->getDecl();
4251 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4252 << S.Context.getTagDeclType(BaseDecl);
4253 } else {
4254 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4255 << Constructor->isImplicit()
4256 << S.Context.getTypeDeclType(Constructor->getParent())
4257 << /*member=*/1
4258 << Entity.getName();
4259 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4260
4261 if (const RecordType *Record
4262 = Entity.getType()->getAs<RecordType>())
4263 S.Diag(Record->getDecl()->getLocation(),
4264 diag::note_previous_decl)
4265 << S.Context.getTagDeclType(Record->getDecl());
4266 }
4267 break;
4268 }
4269
Douglas Gregor51c56d62009-12-14 20:49:26 +00004270 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4271 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004272 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004273 break;
4274
4275 case OR_Deleted: {
4276 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4277 << true << DestType << ArgsRange;
4278 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004279 OverloadingResult Ovl
4280 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004281 if (Ovl == OR_Deleted) {
4282 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4283 << Best->Function->isDeleted();
4284 } else {
4285 llvm_unreachable("Inconsistent overload resolution?");
4286 }
4287 break;
4288 }
4289
4290 case OR_Success:
4291 llvm_unreachable("Conversion did not fail!");
4292 break;
4293 }
4294 break;
4295 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004296
4297 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004298 if (Entity.getKind() == InitializedEntity::EK_Member &&
4299 isa<CXXConstructorDecl>(S.CurContext)) {
4300 // This is implicit default-initialization of a const member in
4301 // a constructor. Complain that it needs to be explicitly
4302 // initialized.
4303 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4304 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4305 << Constructor->isImplicit()
4306 << S.Context.getTypeDeclType(Constructor->getParent())
4307 << /*const=*/1
4308 << Entity.getName();
4309 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4310 << Entity.getName();
4311 } else {
4312 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4313 << DestType << (bool)DestType->getAs<RecordType>();
4314 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004315 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004316
4317 case FK_Incomplete:
4318 S.RequireCompleteType(Kind.getLocation(), DestType,
4319 diag::err_init_incomplete_type);
4320 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004321 }
4322
Douglas Gregora41a8c52010-04-22 00:20:18 +00004323 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004324 return true;
4325}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004326
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004327void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4328 switch (SequenceKind) {
4329 case FailedSequence: {
4330 OS << "Failed sequence: ";
4331 switch (Failure) {
4332 case FK_TooManyInitsForReference:
4333 OS << "too many initializers for reference";
4334 break;
4335
4336 case FK_ArrayNeedsInitList:
4337 OS << "array requires initializer list";
4338 break;
4339
4340 case FK_ArrayNeedsInitListOrStringLiteral:
4341 OS << "array requires initializer list or string literal";
4342 break;
4343
4344 case FK_AddressOfOverloadFailed:
4345 OS << "address of overloaded function failed";
4346 break;
4347
4348 case FK_ReferenceInitOverloadFailed:
4349 OS << "overload resolution for reference initialization failed";
4350 break;
4351
4352 case FK_NonConstLValueReferenceBindingToTemporary:
4353 OS << "non-const lvalue reference bound to temporary";
4354 break;
4355
4356 case FK_NonConstLValueReferenceBindingToUnrelated:
4357 OS << "non-const lvalue reference bound to unrelated type";
4358 break;
4359
4360 case FK_RValueReferenceBindingToLValue:
4361 OS << "rvalue reference bound to an lvalue";
4362 break;
4363
4364 case FK_ReferenceInitDropsQualifiers:
4365 OS << "reference initialization drops qualifiers";
4366 break;
4367
4368 case FK_ReferenceInitFailed:
4369 OS << "reference initialization failed";
4370 break;
4371
4372 case FK_ConversionFailed:
4373 OS << "conversion failed";
4374 break;
4375
4376 case FK_TooManyInitsForScalar:
4377 OS << "too many initializers for scalar";
4378 break;
4379
4380 case FK_ReferenceBindingToInitList:
4381 OS << "referencing binding to initializer list";
4382 break;
4383
4384 case FK_InitListBadDestinationType:
4385 OS << "initializer list for non-aggregate, non-scalar type";
4386 break;
4387
4388 case FK_UserConversionOverloadFailed:
4389 OS << "overloading failed for user-defined conversion";
4390 break;
4391
4392 case FK_ConstructorOverloadFailed:
4393 OS << "constructor overloading failed";
4394 break;
4395
4396 case FK_DefaultInitOfConst:
4397 OS << "default initialization of a const variable";
4398 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004399
4400 case FK_Incomplete:
4401 OS << "initialization of incomplete type";
4402 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004403 }
4404 OS << '\n';
4405 return;
4406 }
4407
4408 case DependentSequence:
4409 OS << "Dependent sequence: ";
4410 return;
4411
4412 case UserDefinedConversion:
4413 OS << "User-defined conversion sequence: ";
4414 break;
4415
4416 case ConstructorInitialization:
4417 OS << "Constructor initialization sequence: ";
4418 break;
4419
4420 case ReferenceBinding:
4421 OS << "Reference binding: ";
4422 break;
4423
4424 case ListInitialization:
4425 OS << "List initialization: ";
4426 break;
4427
4428 case ZeroInitialization:
4429 OS << "Zero initialization\n";
4430 return;
4431
4432 case NoInitialization:
4433 OS << "No initialization\n";
4434 return;
4435
4436 case StandardConversion:
4437 OS << "Standard conversion: ";
4438 break;
4439
4440 case CAssignment:
4441 OS << "C assignment: ";
4442 break;
4443
4444 case StringInit:
4445 OS << "String initialization: ";
4446 break;
4447 }
4448
4449 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4450 if (S != step_begin()) {
4451 OS << " -> ";
4452 }
4453
4454 switch (S->Kind) {
4455 case SK_ResolveAddressOfOverloadedFunction:
4456 OS << "resolve address of overloaded function";
4457 break;
4458
4459 case SK_CastDerivedToBaseRValue:
4460 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4461 break;
4462
Sebastian Redl906082e2010-07-20 04:20:21 +00004463 case SK_CastDerivedToBaseXValue:
4464 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4465 break;
4466
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004467 case SK_CastDerivedToBaseLValue:
4468 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4469 break;
4470
4471 case SK_BindReference:
4472 OS << "bind reference to lvalue";
4473 break;
4474
4475 case SK_BindReferenceToTemporary:
4476 OS << "bind reference to a temporary";
4477 break;
4478
Douglas Gregor523d46a2010-04-18 07:40:54 +00004479 case SK_ExtraneousCopyToTemporary:
4480 OS << "extraneous C++03 copy to temporary";
4481 break;
4482
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004483 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004484 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004485 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004486
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004487 case SK_QualificationConversionRValue:
4488 OS << "qualification conversion (rvalue)";
4489
Sebastian Redl906082e2010-07-20 04:20:21 +00004490 case SK_QualificationConversionXValue:
4491 OS << "qualification conversion (xvalue)";
4492
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004493 case SK_QualificationConversionLValue:
4494 OS << "qualification conversion (lvalue)";
4495 break;
4496
4497 case SK_ConversionSequence:
4498 OS << "implicit conversion sequence (";
4499 S->ICS->DebugPrint(); // FIXME: use OS
4500 OS << ")";
4501 break;
4502
4503 case SK_ListInitialization:
4504 OS << "list initialization";
4505 break;
4506
4507 case SK_ConstructorInitialization:
4508 OS << "constructor initialization";
4509 break;
4510
4511 case SK_ZeroInitialization:
4512 OS << "zero initialization";
4513 break;
4514
4515 case SK_CAssignment:
4516 OS << "C assignment";
4517 break;
4518
4519 case SK_StringInit:
4520 OS << "string initialization";
4521 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004522
4523 case SK_ObjCObjectConversion:
4524 OS << "Objective-C object conversion";
4525 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004526 }
4527 }
4528}
4529
4530void InitializationSequence::dump() const {
4531 dump(llvm::errs());
4532}
4533
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004534//===----------------------------------------------------------------------===//
4535// Initialization helper functions
4536//===----------------------------------------------------------------------===//
John McCall60d7b3a2010-08-24 06:29:42 +00004537ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004538Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4539 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004540 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004541 if (Init.isInvalid())
4542 return ExprError();
4543
John McCall15d7d122010-11-11 03:21:53 +00004544 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004545 assert(InitE && "No initialization expression?");
4546
4547 if (EqualLoc.isInvalid())
4548 EqualLoc = InitE->getLocStart();
4549
4550 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4551 EqualLoc);
4552 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4553 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004554 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004555}