blob: d7048a129f1540baa5018fc897c16b1be82b5549 [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);
Francois Pichet87c2e122010-11-21 06:08:52 +00001432
1433 // Check if ReplacementField is an anonymous field.
1434 if (!ReplacementField)
1435 if (IndirectFieldDecl* IField = dyn_cast<IndirectFieldDecl>(*Lookup.first))
1436 ReplacementField = IField->getAnonField();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001437 }
1438
1439 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001440 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001441 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001442 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001443 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001444 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001445 ++Index;
1446 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001447 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001448
1449 if (!KnownField &&
1450 cast<RecordDecl>((ReplacementField)->getDeclContext())
1451 ->isAnonymousStructOrUnion()) {
1452 // Handle an field designator that refers to a member of an
Douglas Gregor022d13d2010-10-08 20:44:28 +00001453 // anonymous struct or union. This is a C1X feature.
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001454 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1455 ReplacementField,
Douglas Gregor022d13d2010-10-08 20:44:28 +00001456 Field, FieldIndex, RT->getDecl());
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001457 D = DIE->getDesignator(DesigIdx);
1458 } else if (!KnownField) {
1459 // The replacement field comes from typo correction; find it
1460 // in the list of fields.
1461 FieldIndex = 0;
1462 Field = RT->getDecl()->field_begin();
1463 for (; Field != FieldEnd; ++Field) {
1464 if (Field->isUnnamedBitfield())
1465 continue;
1466
1467 if (ReplacementField == *Field ||
1468 Field->getIdentifier() == ReplacementField->getIdentifier())
1469 break;
1470
1471 ++FieldIndex;
1472 }
1473 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001474 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001475
1476 // All of the fields of a union are located at the same place in
1477 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001478 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001479 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001480 StructuredList->setInitializedFieldInUnion(*Field);
1481 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001482
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001483 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001484 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Douglas Gregor4c678342009-01-28 21:54:33 +00001486 // Make sure that our non-designated initializer list has space
1487 // for a subobject corresponding to this field.
1488 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001489 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001490
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001491 // This designator names a flexible array member.
1492 if (Field->getType()->isIncompleteArrayType()) {
1493 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001494 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001495 // We can't designate an object within the flexible array
1496 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001497 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001498 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001499 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001500 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001501 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001502 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001503 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001504 << *Field;
1505 Invalid = true;
1506 }
1507
Chris Lattner9046c222010-10-10 17:49:49 +00001508 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1509 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001510 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001511 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001512 diag::err_flexible_array_init_needs_braces)
1513 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001514 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001515 << *Field;
1516 Invalid = true;
1517 }
1518
1519 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001520 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001521 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001522 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001523 diag::err_flexible_array_init_nonempty)
1524 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001525 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001526 << *Field;
1527 Invalid = true;
1528 }
1529
1530 if (Invalid) {
1531 ++Index;
1532 return true;
1533 }
1534
1535 // Initialize the array.
1536 bool prevHadError = hadError;
1537 unsigned newStructuredIndex = FieldIndex;
1538 unsigned OldIndex = Index;
1539 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001540
1541 InitializedEntity MemberEntity =
1542 InitializedEntity::InitializeMember(*Field, &Entity);
1543 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001544 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001545
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001546 IList->setInit(OldIndex, DIE);
1547 if (hadError && !prevHadError) {
1548 ++Field;
1549 ++FieldIndex;
1550 if (NextField)
1551 *NextField = Field;
1552 StructuredIndex = FieldIndex;
1553 return true;
1554 }
1555 } else {
1556 // Recurse to check later designated subobjects.
1557 QualType FieldType = (*Field)->getType();
1558 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001559
1560 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001561 InitializedEntity::InitializeMember(*Field, &Entity);
1562 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001563 FieldType, 0, 0, Index,
1564 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001565 true, false))
1566 return true;
1567 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001568
1569 // Find the position of the next field to be initialized in this
1570 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001572 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001573
1574 // If this the first designator, our caller will continue checking
1575 // the rest of this struct/class/union subobject.
1576 if (IsFirstDesignator) {
1577 if (NextField)
1578 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001579 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001580 return false;
1581 }
1582
Douglas Gregor34e79462009-01-28 23:36:17 +00001583 if (!FinishSubobjectInit)
1584 return false;
1585
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001586 // We've already initialized something in the union; we're done.
1587 if (RT->getDecl()->isUnion())
1588 return hadError;
1589
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001590 // Check the remaining fields within this class/struct/union subobject.
1591 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001592
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001593 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001594 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001595 return hadError && !prevHadError;
1596 }
1597
1598 // C99 6.7.8p6:
1599 //
1600 // If a designator has the form
1601 //
1602 // [ constant-expression ]
1603 //
1604 // then the current object (defined below) shall have array
1605 // type and the expression shall be an integer constant
1606 // expression. If the array is of unknown size, any
1607 // nonnegative value is valid.
1608 //
1609 // Additionally, cope with the GNU extension that permits
1610 // designators of the form
1611 //
1612 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001613 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001614 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001615 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001616 << CurrentObjectType;
1617 ++Index;
1618 return true;
1619 }
1620
1621 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001622 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1623 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001624 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001625 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001626 DesignatedEndIndex = DesignatedStartIndex;
1627 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001628 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001629
Mike Stump1eb44332009-09-09 15:08:12 +00001630
1631 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001632 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001633 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001634 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001635 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001636
Chris Lattner3bf68932009-04-25 21:59:05 +00001637 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001638 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001639 }
1640
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001641 if (isa<ConstantArrayType>(AT)) {
1642 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001643 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1644 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1645 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1646 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1647 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001648 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001649 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001650 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001651 << IndexExpr->getSourceRange();
1652 ++Index;
1653 return true;
1654 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001655 } else {
1656 // Make sure the bit-widths and signedness match.
1657 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1658 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001659 else if (DesignatedStartIndex.getBitWidth() <
1660 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001661 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1662 DesignatedStartIndex.setIsUnsigned(true);
1663 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001664 }
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Douglas Gregor4c678342009-01-28 21:54:33 +00001666 // Make sure that our non-designated initializer list has space
1667 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001668 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001669 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001670 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001671
Douglas Gregor34e79462009-01-28 23:36:17 +00001672 // Repeatedly perform subobject initializations in the range
1673 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001674
Douglas Gregor34e79462009-01-28 23:36:17 +00001675 // Move to the next designator
1676 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1677 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001678
1679 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001680 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001681
Douglas Gregor34e79462009-01-28 23:36:17 +00001682 while (DesignatedStartIndex <= DesignatedEndIndex) {
1683 // Recurse to check later designated subobjects.
1684 QualType ElementType = AT->getElementType();
1685 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001686
1687 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001688 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001689 ElementType, 0, 0, Index,
1690 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001691 (DesignatedStartIndex == DesignatedEndIndex),
1692 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001693 return true;
1694
1695 // Move to the next index in the array that we'll be initializing.
1696 ++DesignatedStartIndex;
1697 ElementIndex = DesignatedStartIndex.getZExtValue();
1698 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001699
1700 // If this the first designator, our caller will continue checking
1701 // the rest of this array subobject.
1702 if (IsFirstDesignator) {
1703 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001704 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001705 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001706 return false;
1707 }
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor34e79462009-01-28 23:36:17 +00001709 if (!FinishSubobjectInit)
1710 return false;
1711
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001712 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001713 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001714 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001715 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001716 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001717 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001718}
1719
Douglas Gregor4c678342009-01-28 21:54:33 +00001720// Get the structured initializer list for a subobject of type
1721// @p CurrentObjectType.
1722InitListExpr *
1723InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1724 QualType CurrentObjectType,
1725 InitListExpr *StructuredList,
1726 unsigned StructuredIndex,
1727 SourceRange InitRange) {
1728 Expr *ExistingInit = 0;
1729 if (!StructuredList)
1730 ExistingInit = SyntacticToSemantic[IList];
1731 else if (StructuredIndex < StructuredList->getNumInits())
1732 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Douglas Gregor4c678342009-01-28 21:54:33 +00001734 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1735 return Result;
1736
1737 if (ExistingInit) {
1738 // We are creating an initializer list that initializes the
1739 // subobjects of the current object, but there was already an
1740 // initialization that completely initialized the current
1741 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001742 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001743 // struct X { int a, b; };
1744 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001745 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001746 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1747 // designated initializer re-initializes the whole
1748 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001749 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001750 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001751 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001752 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001753 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001754 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001755 << ExistingInit->getSourceRange();
1756 }
1757
Mike Stump1eb44332009-09-09 15:08:12 +00001758 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001759 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1760 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001761 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001762
Douglas Gregor63982352010-07-13 18:40:04 +00001763 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001764
Douglas Gregorfa219202009-03-20 23:58:33 +00001765 // Pre-allocate storage for the structured initializer list.
1766 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001767 unsigned NumInits = 0;
1768 if (!StructuredList)
1769 NumInits = IList->getNumInits();
1770 else if (Index < IList->getNumInits()) {
1771 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1772 NumInits = SubList->getNumInits();
1773 }
1774
Mike Stump1eb44332009-09-09 15:08:12 +00001775 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001776 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1777 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1778 NumElements = CAType->getSize().getZExtValue();
1779 // Simple heuristic so that we don't allocate a very large
1780 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001781 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001782 NumElements = 0;
1783 }
John McCall183700f2009-09-21 23:43:11 +00001784 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001785 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001786 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001787 RecordDecl *RDecl = RType->getDecl();
1788 if (RDecl->isUnion())
1789 NumElements = 1;
1790 else
Mike Stump1eb44332009-09-09 15:08:12 +00001791 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001792 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001793 }
1794
Douglas Gregor08457732009-03-21 18:13:52 +00001795 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001796 NumElements = IList->getNumInits();
1797
Ted Kremenek709210f2010-04-13 23:39:13 +00001798 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001799
Douglas Gregor4c678342009-01-28 21:54:33 +00001800 // Link this new initializer list into the structured initializer
1801 // lists.
1802 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001803 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001804 else {
1805 Result->setSyntacticForm(IList);
1806 SyntacticToSemantic[IList] = Result;
1807 }
1808
1809 return Result;
1810}
1811
1812/// Update the initializer at index @p StructuredIndex within the
1813/// structured initializer list to the value @p expr.
1814void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1815 unsigned &StructuredIndex,
1816 Expr *expr) {
1817 // No structured initializer list to update
1818 if (!StructuredList)
1819 return;
1820
Ted Kremenek709210f2010-04-13 23:39:13 +00001821 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1822 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001823 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001824 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001825 diag::warn_initializer_overrides)
1826 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001827 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001828 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001829 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001830 << PrevInit->getSourceRange();
1831 }
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Douglas Gregor4c678342009-01-28 21:54:33 +00001833 ++StructuredIndex;
1834}
1835
Douglas Gregor05c13a32009-01-22 00:58:24 +00001836/// Check that the given Index expression is a valid array designator
1837/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001838/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001839/// and produces a reasonable diagnostic if there is a
1840/// failure. Returns true if there was an error, false otherwise. If
1841/// everything went okay, Value will receive the value of the constant
1842/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001843static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001844CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001845 SourceLocation Loc = Index->getSourceRange().getBegin();
1846
1847 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001848 if (S.VerifyIntegerConstantExpression(Index, &Value))
1849 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001850
Chris Lattner3bf68932009-04-25 21:59:05 +00001851 if (Value.isSigned() && Value.isNegative())
1852 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001853 << Value.toString(10) << Index->getSourceRange();
1854
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001855 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001856 return false;
1857}
1858
John McCall60d7b3a2010-08-24 06:29:42 +00001859ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001860 SourceLocation Loc,
1861 bool GNUSyntax,
1862 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001863 typedef DesignatedInitExpr::Designator ASTDesignator;
1864
1865 bool Invalid = false;
1866 llvm::SmallVector<ASTDesignator, 32> Designators;
1867 llvm::SmallVector<Expr *, 32> InitExpressions;
1868
1869 // Build designators and check array designator expressions.
1870 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1871 const Designator &D = Desig.getDesignator(Idx);
1872 switch (D.getKind()) {
1873 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001874 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001875 D.getFieldLoc()));
1876 break;
1877
1878 case Designator::ArrayDesignator: {
1879 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1880 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001881 if (!Index->isTypeDependent() &&
1882 !Index->isValueDependent() &&
1883 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001884 Invalid = true;
1885 else {
1886 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001887 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001888 D.getRBracketLoc()));
1889 InitExpressions.push_back(Index);
1890 }
1891 break;
1892 }
1893
1894 case Designator::ArrayRangeDesignator: {
1895 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1896 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1897 llvm::APSInt StartValue;
1898 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001899 bool StartDependent = StartIndex->isTypeDependent() ||
1900 StartIndex->isValueDependent();
1901 bool EndDependent = EndIndex->isTypeDependent() ||
1902 EndIndex->isValueDependent();
1903 if ((!StartDependent &&
1904 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1905 (!EndDependent &&
1906 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001907 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001908 else {
1909 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001910 if (StartDependent || EndDependent) {
1911 // Nothing to compute.
1912 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001913 EndValue.extend(StartValue.getBitWidth());
1914 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1915 StartValue.extend(EndValue.getBitWidth());
1916
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001917 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001918 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001919 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001920 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1921 Invalid = true;
1922 } else {
1923 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001924 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001925 D.getEllipsisLoc(),
1926 D.getRBracketLoc()));
1927 InitExpressions.push_back(StartIndex);
1928 InitExpressions.push_back(EndIndex);
1929 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001930 }
1931 break;
1932 }
1933 }
1934 }
1935
1936 if (Invalid || Init.isInvalid())
1937 return ExprError();
1938
1939 // Clear out the expressions within the designation.
1940 Desig.ClearExprs(*this);
1941
1942 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001943 = DesignatedInitExpr::Create(Context,
1944 Designators.data(), Designators.size(),
1945 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001946 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001947 return Owned(DIE);
1948}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001949
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001950bool Sema::CheckInitList(const InitializedEntity &Entity,
1951 InitListExpr *&InitList, QualType &DeclType) {
1952 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001953 if (!CheckInitList.HadError())
1954 InitList = CheckInitList.getFullyStructuredList();
1955
1956 return CheckInitList.HadError();
1957}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001958
Douglas Gregor20093b42009-12-09 23:02:17 +00001959//===----------------------------------------------------------------------===//
1960// Initialization entity
1961//===----------------------------------------------------------------------===//
1962
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001963InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1964 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001965 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001966{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001967 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1968 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001969 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001970 } else {
1971 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001972 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001973 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001974}
1975
1976InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001977 CXXBaseSpecifier *Base,
1978 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001979{
1980 InitializedEntity Result;
1981 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001982 Result.Base = reinterpret_cast<uintptr_t>(Base);
1983 if (IsInheritedVirtualBase)
1984 Result.Base |= 0x01;
1985
Douglas Gregord6542d82009-12-22 15:35:07 +00001986 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001987 return Result;
1988}
1989
Douglas Gregor99a2e602009-12-16 01:38:02 +00001990DeclarationName InitializedEntity::getName() const {
1991 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001992 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001993 if (!VariableOrMember)
1994 return DeclarationName();
1995 // Fall through
1996
1997 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001998 case EK_Member:
1999 return VariableOrMember->getDeclName();
2000
2001 case EK_Result:
2002 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002003 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002004 case EK_Temporary:
2005 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002006 case EK_ArrayElement:
2007 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002008 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002009 return DeclarationName();
2010 }
2011
2012 // Silence GCC warning
2013 return DeclarationName();
2014}
2015
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002016DeclaratorDecl *InitializedEntity::getDecl() const {
2017 switch (getKind()) {
2018 case EK_Variable:
2019 case EK_Parameter:
2020 case EK_Member:
2021 return VariableOrMember;
2022
2023 case EK_Result:
2024 case EK_Exception:
2025 case EK_New:
2026 case EK_Temporary:
2027 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002028 case EK_ArrayElement:
2029 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002030 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002031 return 0;
2032 }
2033
2034 // Silence GCC warning
2035 return 0;
2036}
2037
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002038bool InitializedEntity::allowsNRVO() const {
2039 switch (getKind()) {
2040 case EK_Result:
2041 case EK_Exception:
2042 return LocAndNRVO.NRVO;
2043
2044 case EK_Variable:
2045 case EK_Parameter:
2046 case EK_Member:
2047 case EK_New:
2048 case EK_Temporary:
2049 case EK_Base:
2050 case EK_ArrayElement:
2051 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002052 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002053 break;
2054 }
2055
2056 return false;
2057}
2058
Douglas Gregor20093b42009-12-09 23:02:17 +00002059//===----------------------------------------------------------------------===//
2060// Initialization sequence
2061//===----------------------------------------------------------------------===//
2062
2063void InitializationSequence::Step::Destroy() {
2064 switch (Kind) {
2065 case SK_ResolveAddressOfOverloadedFunction:
2066 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002067 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002068 case SK_CastDerivedToBaseLValue:
2069 case SK_BindReference:
2070 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002071 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002072 case SK_UserConversion:
2073 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002074 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002075 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002076 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002077 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002078 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002079 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002080 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002081 case SK_ObjCObjectConversion:
Douglas Gregor20093b42009-12-09 23:02:17 +00002082 break;
2083
2084 case SK_ConversionSequence:
2085 delete ICS;
2086 }
2087}
2088
Douglas Gregorb70cf442010-03-26 20:14:36 +00002089bool InitializationSequence::isDirectReferenceBinding() const {
2090 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2091}
2092
2093bool InitializationSequence::isAmbiguous() const {
2094 if (getKind() != FailedSequence)
2095 return false;
2096
2097 switch (getFailureKind()) {
2098 case FK_TooManyInitsForReference:
2099 case FK_ArrayNeedsInitList:
2100 case FK_ArrayNeedsInitListOrStringLiteral:
2101 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2102 case FK_NonConstLValueReferenceBindingToTemporary:
2103 case FK_NonConstLValueReferenceBindingToUnrelated:
2104 case FK_RValueReferenceBindingToLValue:
2105 case FK_ReferenceInitDropsQualifiers:
2106 case FK_ReferenceInitFailed:
2107 case FK_ConversionFailed:
2108 case FK_TooManyInitsForScalar:
2109 case FK_ReferenceBindingToInitList:
2110 case FK_InitListBadDestinationType:
2111 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002112 case FK_Incomplete:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002113 return false;
2114
2115 case FK_ReferenceInitOverloadFailed:
2116 case FK_UserConversionOverloadFailed:
2117 case FK_ConstructorOverloadFailed:
2118 return FailedOverloadResult == OR_Ambiguous;
2119 }
2120
2121 return false;
2122}
2123
Douglas Gregord6e44a32010-04-16 22:09:46 +00002124bool InitializationSequence::isConstructorInitialization() const {
2125 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2126}
2127
Douglas Gregor20093b42009-12-09 23:02:17 +00002128void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002129 FunctionDecl *Function,
2130 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002131 Step S;
2132 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2133 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002134 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002135 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002136 Steps.push_back(S);
2137}
2138
2139void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002140 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002141 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002142 switch (VK) {
2143 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2144 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2145 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002146 default: llvm_unreachable("No such category");
2147 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002148 S.Type = BaseType;
2149 Steps.push_back(S);
2150}
2151
2152void InitializationSequence::AddReferenceBindingStep(QualType T,
2153 bool BindingTemporary) {
2154 Step S;
2155 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2156 S.Type = T;
2157 Steps.push_back(S);
2158}
2159
Douglas Gregor523d46a2010-04-18 07:40:54 +00002160void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2161 Step S;
2162 S.Kind = SK_ExtraneousCopyToTemporary;
2163 S.Type = T;
2164 Steps.push_back(S);
2165}
2166
Eli Friedman03981012009-12-11 02:42:07 +00002167void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002168 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002169 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002170 Step S;
2171 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002172 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002173 S.Function.Function = Function;
2174 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002175 Steps.push_back(S);
2176}
2177
2178void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002179 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002180 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002181 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002182 switch (VK) {
2183 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002184 S.Kind = SK_QualificationConversionRValue;
2185 break;
John McCall5baba9d2010-08-25 10:28:54 +00002186 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002187 S.Kind = SK_QualificationConversionXValue;
2188 break;
John McCall5baba9d2010-08-25 10:28:54 +00002189 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002190 S.Kind = SK_QualificationConversionLValue;
2191 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002192 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002193 S.Type = Ty;
2194 Steps.push_back(S);
2195}
2196
2197void InitializationSequence::AddConversionSequenceStep(
2198 const ImplicitConversionSequence &ICS,
2199 QualType T) {
2200 Step S;
2201 S.Kind = SK_ConversionSequence;
2202 S.Type = T;
2203 S.ICS = new ImplicitConversionSequence(ICS);
2204 Steps.push_back(S);
2205}
2206
Douglas Gregord87b61f2009-12-10 17:56:55 +00002207void InitializationSequence::AddListInitializationStep(QualType T) {
2208 Step S;
2209 S.Kind = SK_ListInitialization;
2210 S.Type = T;
2211 Steps.push_back(S);
2212}
2213
Douglas Gregor51c56d62009-12-14 20:49:26 +00002214void
2215InitializationSequence::AddConstructorInitializationStep(
2216 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002217 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002218 QualType T) {
2219 Step S;
2220 S.Kind = SK_ConstructorInitialization;
2221 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002222 S.Function.Function = Constructor;
2223 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002224 Steps.push_back(S);
2225}
2226
Douglas Gregor71d17402009-12-15 00:01:57 +00002227void InitializationSequence::AddZeroInitializationStep(QualType T) {
2228 Step S;
2229 S.Kind = SK_ZeroInitialization;
2230 S.Type = T;
2231 Steps.push_back(S);
2232}
2233
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002234void InitializationSequence::AddCAssignmentStep(QualType T) {
2235 Step S;
2236 S.Kind = SK_CAssignment;
2237 S.Type = T;
2238 Steps.push_back(S);
2239}
2240
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002241void InitializationSequence::AddStringInitStep(QualType T) {
2242 Step S;
2243 S.Kind = SK_StringInit;
2244 S.Type = T;
2245 Steps.push_back(S);
2246}
2247
Douglas Gregor569c3162010-08-07 11:51:51 +00002248void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2249 Step S;
2250 S.Kind = SK_ObjCObjectConversion;
2251 S.Type = T;
2252 Steps.push_back(S);
2253}
2254
Douglas Gregor20093b42009-12-09 23:02:17 +00002255void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2256 OverloadingResult Result) {
2257 SequenceKind = FailedSequence;
2258 this->Failure = Failure;
2259 this->FailedOverloadResult = Result;
2260}
2261
2262//===----------------------------------------------------------------------===//
2263// Attempt initialization
2264//===----------------------------------------------------------------------===//
2265
2266/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002267static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002268 const InitializedEntity &Entity,
2269 const InitializationKind &Kind,
2270 InitListExpr *InitList,
2271 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002272 // FIXME: We only perform rudimentary checking of list
2273 // initializations at this point, then assume that any list
2274 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002275 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002276 // do all of the necessary checking. C++0x initializer lists will
2277 // force us to perform more checking here.
2278 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2279
Douglas Gregord6542d82009-12-22 15:35:07 +00002280 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002281
2282 // C++ [dcl.init]p13:
2283 // If T is a scalar type, then a declaration of the form
2284 //
2285 // T x = { a };
2286 //
2287 // is equivalent to
2288 //
2289 // T x = a;
2290 if (DestType->isScalarType()) {
2291 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2292 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2293 return;
2294 }
2295
2296 // Assume scalar initialization from a single value works.
2297 } else if (DestType->isAggregateType()) {
2298 // Assume aggregate initialization works.
2299 } else if (DestType->isVectorType()) {
2300 // Assume vector initialization works.
2301 } else if (DestType->isReferenceType()) {
2302 // FIXME: C++0x defines behavior for this.
2303 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2304 return;
2305 } else if (DestType->isRecordType()) {
2306 // FIXME: C++0x defines behavior for this
2307 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2308 }
2309
2310 // Add a general "list initialization" step.
2311 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002312}
2313
2314/// \brief Try a reference initialization that involves calling a conversion
2315/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002316static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2317 const InitializedEntity &Entity,
2318 const InitializationKind &Kind,
2319 Expr *Initializer,
2320 bool AllowRValues,
2321 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002322 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002323 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2324 QualType T1 = cv1T1.getUnqualifiedType();
2325 QualType cv2T2 = Initializer->getType();
2326 QualType T2 = cv2T2.getUnqualifiedType();
2327
2328 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002329 bool ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002330 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002331 T1, T2, DerivedToBase,
2332 ObjCConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002333 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002334 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002335 (void)ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002336
2337 // Build the candidate set directly in the initialization sequence
2338 // structure, so that it will persist if we fail.
2339 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2340 CandidateSet.clear();
2341
2342 // Determine whether we are allowed to call explicit constructors or
2343 // explicit conversion operators.
2344 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2345
2346 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002347 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2348 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002349 // The type we're converting to is a class type. Enumerate its constructors
2350 // to see if there is a suitable conversion.
2351 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002352
Douglas Gregor20093b42009-12-09 23:02:17 +00002353 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002354 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002355 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002356 NamedDecl *D = *Con;
2357 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2358
Douglas Gregor20093b42009-12-09 23:02:17 +00002359 // Find the constructor (which may be a template).
2360 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002361 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002362 if (ConstructorTmpl)
2363 Constructor = cast<CXXConstructorDecl>(
2364 ConstructorTmpl->getTemplatedDecl());
2365 else
John McCall9aa472c2010-03-19 07:35:19 +00002366 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002367
2368 if (!Constructor->isInvalidDecl() &&
2369 Constructor->isConvertingConstructor(AllowExplicit)) {
2370 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002371 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002372 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002373 &Initializer, 1, CandidateSet,
2374 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002375 else
John McCall9aa472c2010-03-19 07:35:19 +00002376 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002377 &Initializer, 1, CandidateSet,
2378 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002379 }
2380 }
2381 }
John McCall572fc622010-08-17 07:23:57 +00002382 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2383 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002384
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002385 const RecordType *T2RecordType = 0;
2386 if ((T2RecordType = T2->getAs<RecordType>()) &&
2387 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002388 // The type we're converting from is a class type, enumerate its conversion
2389 // functions.
2390 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2391
2392 // Determine the type we are converting to. If we are allowed to
2393 // convert to an rvalue, take the type that the destination type
2394 // refers to.
2395 QualType ToType = AllowRValues? cv1T1 : DestType;
2396
John McCalleec51cf2010-01-20 00:46:10 +00002397 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002398 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002399 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2400 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002401 NamedDecl *D = *I;
2402 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2403 if (isa<UsingShadowDecl>(D))
2404 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2405
2406 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2407 CXXConversionDecl *Conv;
2408 if (ConvTemplate)
2409 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2410 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002411 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002412
2413 // If the conversion function doesn't return a reference type,
2414 // it can't be considered for this conversion unless we're allowed to
2415 // consider rvalues.
2416 // FIXME: Do we need to make sure that we only consider conversion
2417 // candidates with reference-compatible results? That might be needed to
2418 // break recursion.
2419 if ((AllowExplicit || !Conv->isExplicit()) &&
2420 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2421 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002422 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002423 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002424 ToType, CandidateSet);
2425 else
John McCall9aa472c2010-03-19 07:35:19 +00002426 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002427 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002428 }
2429 }
2430 }
John McCall572fc622010-08-17 07:23:57 +00002431 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2432 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002433
2434 SourceLocation DeclLoc = Initializer->getLocStart();
2435
2436 // Perform overload resolution. If it fails, return the failed result.
2437 OverloadCandidateSet::iterator Best;
2438 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002439 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002440 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002441
Douglas Gregor20093b42009-12-09 23:02:17 +00002442 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002443
2444 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002445 if (isa<CXXConversionDecl>(Function))
2446 T2 = Function->getResultType();
2447 else
2448 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002449
2450 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002451 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002452 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002453
2454 // Determine whether we need to perform derived-to-base or
2455 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002456 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002457 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002458 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002459 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002460 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002461
Douglas Gregor20093b42009-12-09 23:02:17 +00002462 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002463 bool NewObjCConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002464 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregor63982352010-07-13 18:40:04 +00002465 = S.CompareReferenceRelationship(DeclLoc, T1,
2466 T2.getNonLValueExprType(S.Context),
Douglas Gregor569c3162010-08-07 11:51:51 +00002467 NewDerivedToBase, NewObjCConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002468 if (NewRefRelationship == Sema::Ref_Incompatible) {
2469 // If the type we've converted to is not reference-related to the
2470 // type we're looking for, then there is another conversion step
2471 // we need to perform to produce a temporary of the right type
2472 // that we'll be binding to.
2473 ImplicitConversionSequence ICS;
2474 ICS.setStandard();
2475 ICS.Standard = Best->FinalConversion;
2476 T2 = ICS.Standard.getToType(2);
2477 Sequence.AddConversionSequenceStep(ICS, T2);
2478 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002479 Sequence.AddDerivedToBaseCastStep(
2480 S.Context.getQualifiedType(T1,
2481 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002482 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002483 else if (NewObjCConversion)
2484 Sequence.AddObjCObjectConversionStep(
2485 S.Context.getQualifiedType(T1,
2486 T2.getNonReferenceType().getQualifiers()));
2487
Douglas Gregor20093b42009-12-09 23:02:17 +00002488 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002489 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00002490
2491 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2492 return OR_Success;
2493}
2494
Sebastian Redl4680bf22010-06-30 18:13:39 +00002495/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor20093b42009-12-09 23:02:17 +00002496static void TryReferenceInitialization(Sema &S,
2497 const InitializedEntity &Entity,
2498 const InitializationKind &Kind,
2499 Expr *Initializer,
2500 InitializationSequence &Sequence) {
2501 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002502
Douglas Gregord6542d82009-12-22 15:35:07 +00002503 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002504 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002505 Qualifiers T1Quals;
2506 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002507 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002508 Qualifiers T2Quals;
2509 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002510 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002511
Douglas Gregor20093b42009-12-09 23:02:17 +00002512 // If the initializer is the address of an overloaded function, try
2513 // to resolve the overloaded function. If all goes well, T2 is the
2514 // type of the resulting function.
2515 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002516 DeclAccessPair Found;
Douglas Gregor3afb9772010-11-08 15:20:28 +00002517 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2518 T1,
2519 false,
2520 Found)) {
2521 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2522 cv2T2 = Fn->getType();
2523 T2 = cv2T2.getUnqualifiedType();
2524 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002525 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2526 return;
2527 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002528 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002529
Douglas Gregor20093b42009-12-09 23:02:17 +00002530 // Compute some basic properties of the types and the initializer.
2531 bool isLValueRef = DestType->isLValueReferenceType();
2532 bool isRValueRef = !isLValueRef;
2533 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002534 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002535 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002537 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2538 ObjCConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002539
Douglas Gregor20093b42009-12-09 23:02:17 +00002540 // C++0x [dcl.init.ref]p5:
2541 // A reference to type "cv1 T1" is initialized by an expression of type
2542 // "cv2 T2" as follows:
2543 //
2544 // - If the reference is an lvalue reference and the initializer
2545 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002546 // Note the analogous bullet points for rvlaue refs to functions. Because
2547 // there are no function rvalues in C++, rvalue refs to functions are treated
2548 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002549 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002550 bool T1Function = T1->isFunctionType();
2551 if (isLValueRef || T1Function) {
2552 if (InitCategory.isLValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002553 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2554 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2555 // reference-compatible with "cv2 T2," or
2556 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002557 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002559 // can occur. However, we do pay attention to whether it is a bit-field
2560 // to decide whether we're actually binding to a temporary created from
2561 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002562 if (DerivedToBase)
2563 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002564 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002565 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002566 else if (ObjCConversion)
2567 Sequence.AddObjCObjectConversionStep(
2568 S.Context.getQualifiedType(T1, T2Quals));
2569
Chandler Carruth5535c382010-01-12 20:32:25 +00002570 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002571 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002572 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002573 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002574 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002575 return;
2576 }
2577
2578 // - has a class type (i.e., T2 is a class type), where T1 is not
2579 // reference-related to T2, and can be implicitly converted to an
2580 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2581 // with "cv3 T3" (this conversion is selected by enumerating the
2582 // applicable conversion functions (13.3.1.6) and choosing the best
2583 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002584 // If we have an rvalue ref to function type here, the rhs must be
2585 // an rvalue.
2586 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2587 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002588 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2589 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002590 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002591 Sequence);
2592 if (ConvOvlResult == OR_Success)
2593 return;
John McCall1d318332010-01-12 00:44:57 +00002594 if (ConvOvlResult != OR_No_Viable_Function) {
2595 Sequence.SetOverloadFailure(
2596 InitializationSequence::FK_ReferenceInitOverloadFailed,
2597 ConvOvlResult);
2598 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002599 }
2600 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002601
Douglas Gregor20093b42009-12-09 23:02:17 +00002602 // - Otherwise, the reference shall be an lvalue reference to a
2603 // non-volatile const type (i.e., cv1 shall be const), or the reference
2604 // shall be an rvalue reference and the initializer expression shall
Sebastian Redl4680bf22010-06-30 18:13:39 +00002605 // be an rvalue or have a function type.
2606 // We handled the function type stuff above.
Douglas Gregoref06e242010-01-29 19:39:15 +00002607 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redl4680bf22010-06-30 18:13:39 +00002608 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002609 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2610 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2611 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 Sequence.SetOverloadFailure(
2613 InitializationSequence::FK_ReferenceInitOverloadFailed,
2614 ConvOvlResult);
2615 else if (isLValueRef)
Sebastian Redl4680bf22010-06-30 18:13:39 +00002616 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002617 ? (RefRelationship == Sema::Ref_Related
2618 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2619 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2620 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2621 else
2622 Sequence.SetFailed(
2623 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002624
Douglas Gregor20093b42009-12-09 23:02:17 +00002625 return;
2626 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002627
2628 // - [If T1 is not a function type], if T2 is a class type and
2629 if (!T1Function && T2->isRecordType()) {
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002630 bool isXValue = InitCategory.isXValue();
Douglas Gregor20093b42009-12-09 23:02:17 +00002631 // - the initializer expression is an rvalue and "cv1 T1" is
2632 // reference-compatible with "cv2 T2", or
Sebastian Redl4680bf22010-06-30 18:13:39 +00002633 if (InitCategory.isRValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002634 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002635 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2636 // compiler the freedom to perform a copy here or bind to the
2637 // object, while C++0x requires that we bind directly to the
2638 // object. Hence, we always bind to the object without making an
2639 // extra copy. However, in C++03 requires that we check for the
2640 // presence of a suitable copy constructor:
2641 //
2642 // The constructor that would be used to make the copy shall
2643 // be callable whether or not the copy is actually done.
2644 if (!S.getLangOptions().CPlusPlus0x)
2645 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2646
Douglas Gregor20093b42009-12-09 23:02:17 +00002647 if (DerivedToBase)
2648 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002649 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002650 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002651 else if (ObjCConversion)
2652 Sequence.AddObjCObjectConversionStep(
2653 S.Context.getQualifiedType(T1, T2Quals));
2654
Chandler Carruth5535c382010-01-12 20:32:25 +00002655 if (T1Quals != T2Quals)
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002656 Sequence.AddQualificationConversionStep(cv1T1,
John McCall5baba9d2010-08-25 10:28:54 +00002657 isXValue ? VK_XValue : VK_RValue);
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002658 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00002659 return;
2660 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002661
Douglas Gregor20093b42009-12-09 23:02:17 +00002662 // - T1 is not reference-related to T2 and the initializer expression
2663 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2664 // conversion is selected by enumerating the applicable conversion
2665 // functions (13.3.1.6) and choosing the best one through overload
2666 // resolution (13.3)),
2667 if (RefRelationship == Sema::Ref_Incompatible) {
2668 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2669 Kind, Initializer,
2670 /*AllowRValues=*/true,
2671 Sequence);
2672 if (ConvOvlResult)
2673 Sequence.SetOverloadFailure(
2674 InitializationSequence::FK_ReferenceInitOverloadFailed,
2675 ConvOvlResult);
2676
2677 return;
2678 }
2679
2680 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2681 return;
2682 }
2683
2684 // - If the initializer expression is an rvalue, with T2 an array type,
2685 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2686 // is bound to the object represented by the rvalue (see 3.10).
2687 // FIXME: How can an array type be reference-compatible with anything?
2688 // Don't we mean the element types of T1 and T2?
2689
2690 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2691 // from the initializer expression using the rules for a non-reference
2692 // copy initialization (8.5). The reference is then bound to the
2693 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002694
Douglas Gregor20093b42009-12-09 23:02:17 +00002695 // Determine whether we are allowed to call explicit constructors or
2696 // explicit conversion operators.
2697 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002698
2699 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2700
2701 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2702 /*SuppressUserConversions*/ false,
2703 AllowExplicit,
2704 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002705 // FIXME: Use the conversion function set stored in ICS to turn
2706 // this into an overloading ambiguity diagnostic. However, we need
2707 // to keep that set as an OverloadCandidateSet rather than as some
2708 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002709 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2710 Sequence.SetOverloadFailure(
2711 InitializationSequence::FK_ReferenceInitOverloadFailed,
2712 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002713 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2714 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002715 else
2716 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002717 return;
2718 }
2719
2720 // [...] If T1 is reference-related to T2, cv1 must be the
2721 // same cv-qualification as, or greater cv-qualification
2722 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002723 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2724 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002725 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002726 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002727 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2728 return;
2729 }
2730
Douglas Gregor20093b42009-12-09 23:02:17 +00002731 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2732 return;
2733}
2734
2735/// \brief Attempt character array initialization from a string literal
2736/// (C++ [dcl.init.string], C99 6.7.8).
2737static void TryStringLiteralInitialization(Sema &S,
2738 const InitializedEntity &Entity,
2739 const InitializationKind &Kind,
2740 Expr *Initializer,
2741 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002742 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002743 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002744}
2745
Douglas Gregor20093b42009-12-09 23:02:17 +00002746/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2747/// enumerates the constructors of the initialized entity and performs overload
2748/// resolution to select the best.
2749static void TryConstructorInitialization(Sema &S,
2750 const InitializedEntity &Entity,
2751 const InitializationKind &Kind,
2752 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002753 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002754 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002755 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002756
2757 // Build the candidate set directly in the initialization sequence
2758 // structure, so that it will persist if we fail.
2759 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2760 CandidateSet.clear();
2761
2762 // Determine whether we are allowed to call explicit constructors or
2763 // explicit conversion operators.
2764 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2765 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002766 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002767
2768 // The type we're constructing needs to be complete.
2769 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002770 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002771 return;
2772 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002773
2774 // The type we're converting to is a class type. Enumerate its constructors
2775 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002776 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2777 assert(DestRecordType && "Constructor initialization requires record type");
2778 CXXRecordDecl *DestRecordDecl
2779 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2780
Douglas Gregor51c56d62009-12-14 20:49:26 +00002781 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002782 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002783 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002784 NamedDecl *D = *Con;
2785 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002786 bool SuppressUserConversions = false;
2787
Douglas Gregor51c56d62009-12-14 20:49:26 +00002788 // Find the constructor (which may be a template).
2789 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002790 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002791 if (ConstructorTmpl)
2792 Constructor = cast<CXXConstructorDecl>(
2793 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002794 else {
John McCall9aa472c2010-03-19 07:35:19 +00002795 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002796
2797 // If we're performing copy initialization using a copy constructor, we
2798 // suppress user-defined conversions on the arguments.
2799 // FIXME: Move constructors?
2800 if (Kind.getKind() == InitializationKind::IK_Copy &&
2801 Constructor->isCopyConstructor())
2802 SuppressUserConversions = true;
2803 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002804
2805 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002806 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002807 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002808 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002809 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002810 Args, NumArgs, CandidateSet,
2811 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002812 else
John McCall9aa472c2010-03-19 07:35:19 +00002813 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002814 Args, NumArgs, CandidateSet,
2815 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002816 }
2817 }
2818
2819 SourceLocation DeclLoc = Kind.getLocation();
2820
2821 // Perform overload resolution. If it fails, return the failed result.
2822 OverloadCandidateSet::iterator Best;
2823 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002824 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002825 Sequence.SetOverloadFailure(
2826 InitializationSequence::FK_ConstructorOverloadFailed,
2827 Result);
2828 return;
2829 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002830
2831 // C++0x [dcl.init]p6:
2832 // If a program calls for the default initialization of an object
2833 // of a const-qualified type T, T shall be a class type with a
2834 // user-provided default constructor.
2835 if (Kind.getKind() == InitializationKind::IK_Default &&
2836 Entity.getType().isConstQualified() &&
2837 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2838 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2839 return;
2840 }
2841
Douglas Gregor51c56d62009-12-14 20:49:26 +00002842 // Add the constructor initialization step. Any cv-qualification conversion is
2843 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002844 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002845 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002846 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002847 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002848}
2849
Douglas Gregor71d17402009-12-15 00:01:57 +00002850/// \brief Attempt value initialization (C++ [dcl.init]p7).
2851static void TryValueInitialization(Sema &S,
2852 const InitializedEntity &Entity,
2853 const InitializationKind &Kind,
2854 InitializationSequence &Sequence) {
2855 // C++ [dcl.init]p5:
2856 //
2857 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002858 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002859
2860 // -- if T is an array type, then each element is value-initialized;
2861 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2862 T = AT->getElementType();
2863
2864 if (const RecordType *RT = T->getAs<RecordType>()) {
2865 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2866 // -- if T is a class type (clause 9) with a user-declared
2867 // constructor (12.1), then the default constructor for T is
2868 // called (and the initialization is ill-formed if T has no
2869 // accessible default constructor);
2870 //
2871 // FIXME: we really want to refer to a single subobject of the array,
2872 // but Entity doesn't have a way to capture that (yet).
2873 if (ClassDecl->hasUserDeclaredConstructor())
2874 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2875
Douglas Gregor16006c92009-12-16 18:50:27 +00002876 // -- if T is a (possibly cv-qualified) non-union class type
2877 // without a user-provided constructor, then the object is
2878 // zero-initialized and, if T’s implicitly-declared default
2879 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002880 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002881 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002882 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002883 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2884 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002885 }
2886 }
2887
Douglas Gregord6542d82009-12-22 15:35:07 +00002888 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002889 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2890}
2891
Douglas Gregor99a2e602009-12-16 01:38:02 +00002892/// \brief Attempt default initialization (C++ [dcl.init]p6).
2893static void TryDefaultInitialization(Sema &S,
2894 const InitializedEntity &Entity,
2895 const InitializationKind &Kind,
2896 InitializationSequence &Sequence) {
2897 assert(Kind.getKind() == InitializationKind::IK_Default);
2898
2899 // C++ [dcl.init]p6:
2900 // To default-initialize an object of type T means:
2901 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002902 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002903 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2904 DestType = Array->getElementType();
2905
2906 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2907 // constructor for T is called (and the initialization is ill-formed if
2908 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002909 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00002910 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2911 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002912 }
2913
2914 // - otherwise, no initialization is performed.
2915 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2916
2917 // If a program calls for the default initialization of an object of
2918 // a const-qualified type T, T shall be a class type with a user-provided
2919 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002920 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002921 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2922}
2923
Douglas Gregor20093b42009-12-09 23:02:17 +00002924/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2925/// which enumerates all conversion functions and performs overload resolution
2926/// to select the best.
2927static void TryUserDefinedConversion(Sema &S,
2928 const InitializedEntity &Entity,
2929 const InitializationKind &Kind,
2930 Expr *Initializer,
2931 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002932 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2933
Douglas Gregord6542d82009-12-22 15:35:07 +00002934 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002935 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2936 QualType SourceType = Initializer->getType();
2937 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2938 "Must have a class type to perform a user-defined conversion");
2939
2940 // Build the candidate set directly in the initialization sequence
2941 // structure, so that it will persist if we fail.
2942 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2943 CandidateSet.clear();
2944
2945 // Determine whether we are allowed to call explicit constructors or
2946 // explicit conversion operators.
2947 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2948
2949 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2950 // The type we're converting to is a class type. Enumerate its constructors
2951 // to see if there is a suitable conversion.
2952 CXXRecordDecl *DestRecordDecl
2953 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2954
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002955 // Try to complete the type we're converting to.
2956 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002957 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002958 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002959 Con != ConEnd; ++Con) {
2960 NamedDecl *D = *Con;
2961 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002962
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002963 // Find the constructor (which may be a template).
2964 CXXConstructorDecl *Constructor = 0;
2965 FunctionTemplateDecl *ConstructorTmpl
2966 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002967 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002968 Constructor = cast<CXXConstructorDecl>(
2969 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002970 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002971 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002972
2973 if (!Constructor->isInvalidDecl() &&
2974 Constructor->isConvertingConstructor(AllowExplicit)) {
2975 if (ConstructorTmpl)
2976 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2977 /*ExplicitArgs*/ 0,
2978 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002979 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002980 else
2981 S.AddOverloadCandidate(Constructor, FoundDecl,
2982 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002983 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002984 }
2985 }
2986 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002987 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002988
2989 SourceLocation DeclLoc = Initializer->getLocStart();
2990
Douglas Gregor4a520a22009-12-14 17:27:33 +00002991 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2992 // The type we're converting from is a class type, enumerate its conversion
2993 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002994
Eli Friedman33c2da92009-12-20 22:12:03 +00002995 // We can only enumerate the conversion functions for a complete type; if
2996 // the type isn't complete, simply skip this step.
2997 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2998 CXXRecordDecl *SourceRecordDecl
2999 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003000
John McCalleec51cf2010-01-20 00:46:10 +00003001 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003002 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003003 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00003004 E = Conversions->end();
3005 I != E; ++I) {
3006 NamedDecl *D = *I;
3007 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3008 if (isa<UsingShadowDecl>(D))
3009 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3010
3011 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3012 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003013 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003014 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003015 else
John McCall32daa422010-03-31 01:36:47 +00003016 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00003017
3018 if (AllowExplicit || !Conv->isExplicit()) {
3019 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003020 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003021 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003022 CandidateSet);
3023 else
John McCall9aa472c2010-03-19 07:35:19 +00003024 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003025 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003026 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003027 }
3028 }
3029 }
3030
Douglas Gregor4a520a22009-12-14 17:27:33 +00003031 // Perform overload resolution. If it fails, return the failed result.
3032 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003033 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003034 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003035 Sequence.SetOverloadFailure(
3036 InitializationSequence::FK_UserConversionOverloadFailed,
3037 Result);
3038 return;
3039 }
John McCall1d318332010-01-12 00:44:57 +00003040
Douglas Gregor4a520a22009-12-14 17:27:33 +00003041 FunctionDecl *Function = Best->Function;
3042
3043 if (isa<CXXConstructorDecl>(Function)) {
3044 // Add the user-defined conversion step. Any cv-qualification conversion is
3045 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003046 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003047 return;
3048 }
3049
3050 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003051 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003052 if (ConvType->getAs<RecordType>()) {
3053 // If we're converting to a class type, there may be an copy if
3054 // the resulting temporary object (possible to create an object of
3055 // a base class type). That copy is not a separate conversion, so
3056 // we just make a note of the actual destination type (possibly a
3057 // base class of the type returned by the conversion function) and
3058 // let the user-defined conversion step handle the conversion.
3059 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3060 return;
3061 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003062
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003063 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3064
3065 // If the conversion following the call to the conversion function
3066 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003067 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3068 Best->FinalConversion.Third) {
3069 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003070 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003071 ICS.Standard = Best->FinalConversion;
3072 Sequence.AddConversionSequenceStep(ICS, DestType);
3073 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003074}
3075
Douglas Gregor20093b42009-12-09 23:02:17 +00003076InitializationSequence::InitializationSequence(Sema &S,
3077 const InitializedEntity &Entity,
3078 const InitializationKind &Kind,
3079 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003080 unsigned NumArgs)
3081 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003082 ASTContext &Context = S.Context;
3083
3084 // C++0x [dcl.init]p16:
3085 // The semantics of initializers are as follows. The destination type is
3086 // the type of the object or reference being initialized and the source
3087 // type is the type of the initializer expression. The source type is not
3088 // defined when the initializer is a braced-init-list or when it is a
3089 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003090 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003091
3092 if (DestType->isDependentType() ||
3093 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3094 SequenceKind = DependentSequence;
3095 return;
3096 }
3097
3098 QualType SourceType;
3099 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003100 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003101 Initializer = Args[0];
3102 if (!isa<InitListExpr>(Initializer))
3103 SourceType = Initializer->getType();
3104 }
3105
3106 // - If the initializer is a braced-init-list, the object is
3107 // list-initialized (8.5.4).
3108 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3109 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003110 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003111 }
3112
3113 // - If the destination type is a reference type, see 8.5.3.
3114 if (DestType->isReferenceType()) {
3115 // C++0x [dcl.init.ref]p1:
3116 // A variable declared to be a T& or T&&, that is, "reference to type T"
3117 // (8.3.2), shall be initialized by an object, or function, of type T or
3118 // by an object that can be converted into a T.
3119 // (Therefore, multiple arguments are not permitted.)
3120 if (NumArgs != 1)
3121 SetFailed(FK_TooManyInitsForReference);
3122 else
3123 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3124 return;
3125 }
3126
3127 // - If the destination type is an array of characters, an array of
3128 // char16_t, an array of char32_t, or an array of wchar_t, and the
3129 // initializer is a string literal, see 8.5.2.
3130 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3131 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3132 return;
3133 }
3134
3135 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003136 if (Kind.getKind() == InitializationKind::IK_Value ||
3137 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003138 TryValueInitialization(S, Entity, Kind, *this);
3139 return;
3140 }
3141
Douglas Gregor99a2e602009-12-16 01:38:02 +00003142 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003143 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003144 TryDefaultInitialization(S, Entity, Kind, *this);
3145 return;
3146 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003147
Douglas Gregor20093b42009-12-09 23:02:17 +00003148 // - Otherwise, if the destination type is an array, the program is
3149 // ill-formed.
3150 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3151 if (AT->getElementType()->isAnyCharacterType())
3152 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3153 else
3154 SetFailed(FK_ArrayNeedsInitList);
3155
3156 return;
3157 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003158
3159 // Handle initialization in C
3160 if (!S.getLangOptions().CPlusPlus) {
3161 setSequenceKind(CAssignment);
3162 AddCAssignmentStep(DestType);
3163 return;
3164 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003165
3166 // - If the destination type is a (possibly cv-qualified) class type:
3167 if (DestType->isRecordType()) {
3168 // - If the initialization is direct-initialization, or if it is
3169 // copy-initialization where the cv-unqualified version of the
3170 // source type is the same class as, or a derived class of, the
3171 // class of the destination, constructors are considered. [...]
3172 if (Kind.getKind() == InitializationKind::IK_Direct ||
3173 (Kind.getKind() == InitializationKind::IK_Copy &&
3174 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3175 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003176 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003177 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003178 // - Otherwise (i.e., for the remaining copy-initialization cases),
3179 // user-defined conversion sequences that can convert from the source
3180 // type to the destination type or (when a conversion function is
3181 // used) to a derived class thereof are enumerated as described in
3182 // 13.3.1.4, and the best one is chosen through overload resolution
3183 // (13.3).
3184 else
3185 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3186 return;
3187 }
3188
Douglas Gregor99a2e602009-12-16 01:38:02 +00003189 if (NumArgs > 1) {
3190 SetFailed(FK_TooManyInitsForScalar);
3191 return;
3192 }
3193 assert(NumArgs == 1 && "Zero-argument case handled above");
3194
Douglas Gregor20093b42009-12-09 23:02:17 +00003195 // - Otherwise, if the source type is a (possibly cv-qualified) class
3196 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003197 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003198 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3199 return;
3200 }
3201
3202 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003203 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003204 // conversions (Clause 4) will be used, if necessary, to convert the
3205 // initializer expression to the cv-unqualified version of the
3206 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003207 if (S.TryImplicitConversion(*this, Entity, Initializer,
3208 /*SuppressUserConversions*/ true,
3209 /*AllowExplicitConversions*/ false,
3210 /*InOverloadResolution*/ false))
Douglas Gregor8e960432010-11-08 03:40:48 +00003211 {
3212 if (Initializer->getType() == Context.OverloadTy )
3213 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3214 else
3215 SetFailed(InitializationSequence::FK_ConversionFailed);
3216 }
John McCall369371c2010-06-04 02:29:22 +00003217 else
3218 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003219}
3220
3221InitializationSequence::~InitializationSequence() {
3222 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3223 StepEnd = Steps.end();
3224 Step != StepEnd; ++Step)
3225 Step->Destroy();
3226}
3227
3228//===----------------------------------------------------------------------===//
3229// Perform initialization
3230//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003231static Sema::AssignmentAction
3232getAssignmentAction(const InitializedEntity &Entity) {
3233 switch(Entity.getKind()) {
3234 case InitializedEntity::EK_Variable:
3235 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003236 case InitializedEntity::EK_Exception:
3237 case InitializedEntity::EK_Base:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003238 return Sema::AA_Initializing;
3239
3240 case InitializedEntity::EK_Parameter:
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003241 if (Entity.getDecl() &&
3242 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3243 return Sema::AA_Sending;
3244
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003245 return Sema::AA_Passing;
3246
3247 case InitializedEntity::EK_Result:
3248 return Sema::AA_Returning;
3249
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003250 case InitializedEntity::EK_Temporary:
3251 // FIXME: Can we tell apart casting vs. converting?
3252 return Sema::AA_Casting;
3253
3254 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003255 case InitializedEntity::EK_ArrayElement:
3256 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003257 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003258 return Sema::AA_Initializing;
3259 }
3260
3261 return Sema::AA_Converting;
3262}
3263
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003264/// \brief Whether we should binding a created object as a temporary when
3265/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003266static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003267 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003268 case InitializedEntity::EK_ArrayElement:
3269 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003270 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003271 case InitializedEntity::EK_New:
3272 case InitializedEntity::EK_Variable:
3273 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003274 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003275 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003276 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003277 return false;
3278
3279 case InitializedEntity::EK_Parameter:
3280 case InitializedEntity::EK_Temporary:
3281 return true;
3282 }
3283
3284 llvm_unreachable("missed an InitializedEntity kind?");
3285}
3286
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003287/// \brief Whether the given entity, when initialized with an object
3288/// created for that initialization, requires destruction.
3289static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3290 switch (Entity.getKind()) {
3291 case InitializedEntity::EK_Member:
3292 case InitializedEntity::EK_Result:
3293 case InitializedEntity::EK_New:
3294 case InitializedEntity::EK_Base:
3295 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003296 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003297 return false;
3298
3299 case InitializedEntity::EK_Variable:
3300 case InitializedEntity::EK_Parameter:
3301 case InitializedEntity::EK_Temporary:
3302 case InitializedEntity::EK_ArrayElement:
3303 case InitializedEntity::EK_Exception:
3304 return true;
3305 }
3306
3307 llvm_unreachable("missed an InitializedEntity kind?");
3308}
3309
Douglas Gregor523d46a2010-04-18 07:40:54 +00003310/// \brief Make a (potentially elidable) temporary copy of the object
3311/// provided by the given initializer by calling the appropriate copy
3312/// constructor.
3313///
3314/// \param S The Sema object used for type-checking.
3315///
3316/// \param T The type of the temporary object, which must either by
3317/// the type of the initializer expression or a superclass thereof.
3318///
3319/// \param Enter The entity being initialized.
3320///
3321/// \param CurInit The initializer expression.
3322///
3323/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3324/// is permitted in C++03 (but not C++0x) when binding a reference to
3325/// an rvalue.
3326///
3327/// \returns An expression that copies the initializer expression into
3328/// a temporary object, or an error expression if a copy could not be
3329/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003330static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003331 QualType T,
3332 const InitializedEntity &Entity,
3333 ExprResult CurInit,
3334 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003335 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003336 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003337 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003338 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003339 Class = cast<CXXRecordDecl>(Record->getDecl());
3340 if (!Class)
3341 return move(CurInit);
3342
3343 // C++0x [class.copy]p34:
3344 // When certain criteria are met, an implementation is allowed to
3345 // omit the copy/move construction of a class object, even if the
3346 // copy/move constructor and/or destructor for the object have
3347 // side effects. [...]
3348 // - when a temporary class object that has not been bound to a
3349 // reference (12.2) would be copied/moved to a class object
3350 // with the same cv-unqualified type, the copy/move operation
3351 // can be omitted by constructing the temporary object
3352 // directly into the target of the omitted copy/move
3353 //
3354 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003355 // elision for return statements and throw expressions are handled as part
3356 // of constructor initialization, while copy elision for exception handlers
3357 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003358 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003359 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003360 switch (Entity.getKind()) {
3361 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003362 Loc = Entity.getReturnLoc();
3363 break;
3364
3365 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003366 Loc = Entity.getThrowLoc();
3367 break;
3368
3369 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003370 Loc = Entity.getDecl()->getLocation();
3371 break;
3372
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003373 case InitializedEntity::EK_ArrayElement:
3374 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003375 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003376 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003377 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003378 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003379 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003380 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003381 Loc = CurInitExpr->getLocStart();
3382 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003383 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003384
3385 // Make sure that the type we are copying is complete.
3386 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3387 return move(CurInit);
3388
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003389 // Perform overload resolution using the class's copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003390 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003391 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003392 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003393 Con != ConEnd; ++Con) {
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003394 // Only consider copy constructors and constructor templates. Per
3395 // C++0x [dcl.init]p16, second bullet to class types, this
3396 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003397 CXXConstructorDecl *Constructor = 0;
3398
3399 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
3400 // Handle copy constructors, only.
3401 if (!Constructor || Constructor->isInvalidDecl() ||
3402 !Constructor->isCopyConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003403 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003404 continue;
3405
3406 DeclAccessPair FoundDecl
3407 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3408 S.AddOverloadCandidate(Constructor, FoundDecl,
3409 &CurInitExpr, 1, CandidateSet);
3410 continue;
3411 }
3412
3413 // Handle constructor templates.
3414 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3415 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003416 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003417
Douglas Gregor6493cc52010-11-08 17:16:59 +00003418 Constructor = cast<CXXConstructorDecl>(
3419 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003420 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003421 continue;
3422
3423 // FIXME: Do we need to limit this to copy-constructor-like
3424 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003425 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003426 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3427 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3428 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003429 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003430
3431 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00003432 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003433 case OR_Success:
3434 break;
3435
3436 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003437 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3438 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3439 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003440 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003441 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003442 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003443 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003444 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003445 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003446
3447 case OR_Ambiguous:
3448 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003449 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003450 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003451 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003452 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003453
3454 case OR_Deleted:
3455 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003456 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003457 << CurInitExpr->getSourceRange();
3458 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3459 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003460 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003461 }
3462
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003463 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003464 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003465 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003466
Anders Carlsson9a68a672010-04-21 18:47:17 +00003467 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003468 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003469
3470 if (IsExtraneousCopy) {
3471 // If this is a totally extraneous copy for C++03 reference
3472 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003473 // expression. We don't generate an (elided) copy operation here
3474 // because doing so would require us to pass down a flag to avoid
3475 // infinite recursion, where each step adds another extraneous,
3476 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003477
Douglas Gregor2559a702010-04-18 07:57:34 +00003478 // Instantiate the default arguments of any extra parameters in
3479 // the selected copy constructor, as if we were going to create a
3480 // proper call to the copy constructor.
3481 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3482 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3483 if (S.RequireCompleteType(Loc, Parm->getType(),
3484 S.PDiag(diag::err_call_incomplete_argument)))
3485 break;
3486
3487 // Build the default argument expression; we don't actually care
3488 // if this succeeds or not, because this routine will complain
3489 // if there was a problem.
3490 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3491 }
3492
Douglas Gregor523d46a2010-04-18 07:40:54 +00003493 return S.Owned(CurInitExpr);
3494 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003495
3496 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003497 // constructor call (we might have derived-to-base conversions, or
3498 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003499 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003500 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003501 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003502
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003503 // Actually perform the constructor call.
3504 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003505 move_arg(ConstructorArgs),
3506 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003507 CXXConstructExpr::CK_Complete,
3508 SourceRange());
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003509
3510 // If we're supposed to bind temporaries, do so.
3511 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3512 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3513 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003514}
Douglas Gregor20093b42009-12-09 23:02:17 +00003515
Douglas Gregora41a8c52010-04-22 00:20:18 +00003516void InitializationSequence::PrintInitLocationNote(Sema &S,
3517 const InitializedEntity &Entity) {
3518 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3519 if (Entity.getDecl()->getLocation().isInvalid())
3520 return;
3521
3522 if (Entity.getDecl()->getDeclName())
3523 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3524 << Entity.getDecl()->getDeclName();
3525 else
3526 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3527 }
3528}
3529
John McCall60d7b3a2010-08-24 06:29:42 +00003530ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003531InitializationSequence::Perform(Sema &S,
3532 const InitializedEntity &Entity,
3533 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003534 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003535 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003536 if (SequenceKind == FailedSequence) {
3537 unsigned NumArgs = Args.size();
3538 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003539 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003540 }
3541
3542 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003543 // If the declaration is a non-dependent, incomplete array type
3544 // that has an initializer, then its type will be completed once
3545 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003546 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003547 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003548 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003549 if (const IncompleteArrayType *ArrayT
3550 = S.Context.getAsIncompleteArrayType(DeclType)) {
3551 // FIXME: We don't currently have the ability to accurately
3552 // compute the length of an initializer list without
3553 // performing full type-checking of the initializer list
3554 // (since we have to determine where braces are implicitly
3555 // introduced and such). So, we fall back to making the array
3556 // type a dependently-sized array type with no specified
3557 // bound.
3558 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3559 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003560
Douglas Gregord87b61f2009-12-10 17:56:55 +00003561 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003562 if (DeclaratorDecl *DD = Entity.getDecl()) {
3563 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3564 TypeLoc TL = TInfo->getTypeLoc();
3565 if (IncompleteArrayTypeLoc *ArrayLoc
3566 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3567 Brackets = ArrayLoc->getBracketsRange();
3568 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003569 }
3570
3571 *ResultType
3572 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3573 /*NumElts=*/0,
3574 ArrayT->getSizeModifier(),
3575 ArrayT->getIndexTypeCVRQualifiers(),
3576 Brackets);
3577 }
3578
3579 }
3580 }
3581
Eli Friedman08544622009-12-22 02:35:53 +00003582 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003583 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003584
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003585 if (Args.size() == 0)
3586 return S.Owned((Expr *)0);
3587
Douglas Gregor20093b42009-12-09 23:02:17 +00003588 unsigned NumArgs = Args.size();
3589 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3590 SourceLocation(),
3591 (Expr **)Args.release(),
3592 NumArgs,
3593 SourceLocation()));
3594 }
3595
Douglas Gregor99a2e602009-12-16 01:38:02 +00003596 if (SequenceKind == NoInitialization)
3597 return S.Owned((Expr *)0);
3598
Douglas Gregord6542d82009-12-22 15:35:07 +00003599 QualType DestType = Entity.getType().getNonReferenceType();
3600 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003601 // the same as Entity.getDecl()->getType() in cases involving type merging,
3602 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003603 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003604 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003605 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003606
John McCall60d7b3a2010-08-24 06:29:42 +00003607 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003608
3609 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3610
3611 // For initialization steps that start with a single initializer,
3612 // grab the only argument out the Args and place it into the "current"
3613 // initializer.
3614 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003615 case SK_ResolveAddressOfOverloadedFunction:
3616 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003617 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003618 case SK_CastDerivedToBaseLValue:
3619 case SK_BindReference:
3620 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003621 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003622 case SK_UserConversion:
3623 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003624 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003625 case SK_QualificationConversionRValue:
3626 case SK_ConversionSequence:
3627 case SK_ListInitialization:
3628 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003629 case SK_StringInit:
John McCallf6a16482010-12-04 03:47:34 +00003630 case SK_ObjCObjectConversion: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003631 assert(Args.size() == 1);
John McCallf6a16482010-12-04 03:47:34 +00003632 Expr *CurInitExpr = Args.get()[0];
3633 if (!CurInitExpr) return ExprError();
3634
3635 // Read from a property when initializing something with it.
3636 if (CurInitExpr->getObjectKind() == OK_ObjCProperty)
3637 S.ConvertPropertyForRValue(CurInitExpr);
3638
3639 CurInit = ExprResult(CurInitExpr);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003640 break;
John McCallf6a16482010-12-04 03:47:34 +00003641 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003642
3643 case SK_ConstructorInitialization:
3644 case SK_ZeroInitialization:
3645 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003646 }
3647
3648 // Walk through the computed steps for the initialization sequence,
3649 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003650 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003651 for (step_iterator Step = step_begin(), StepEnd = step_end();
3652 Step != StepEnd; ++Step) {
3653 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003654 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003655
John McCallf6a16482010-12-04 03:47:34 +00003656 Expr *CurInitExpr = CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003657 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003658
3659 switch (Step->Kind) {
3660 case SK_ResolveAddressOfOverloadedFunction:
3661 // Overload resolution determined which function invoke; update the
3662 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003663 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003664 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003665 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003666 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003667 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003668 break;
3669
3670 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003671 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003672 case SK_CastDerivedToBaseLValue: {
3673 // We have a derived-to-base cast that produces either an rvalue or an
3674 // lvalue. Perform that cast.
3675
John McCallf871d0c2010-08-07 06:22:56 +00003676 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003677
Douglas Gregor20093b42009-12-09 23:02:17 +00003678 // Casts to inaccessible base classes are allowed with C-style casts.
3679 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3680 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3681 CurInitExpr->getLocStart(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003682 CurInitExpr->getSourceRange(),
3683 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003684 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003685
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003686 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3687 QualType T = SourceType;
3688 if (const PointerType *Pointer = T->getAs<PointerType>())
3689 T = Pointer->getPointeeType();
3690 if (const RecordType *RecordTy = T->getAs<RecordType>())
3691 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3692 cast<CXXRecordDecl>(RecordTy->getDecl()));
3693 }
3694
John McCall5baba9d2010-08-25 10:28:54 +00003695 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003696 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003697 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003698 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003699 VK_XValue :
3700 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00003701 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3702 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003703 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00003704 CurInit.get(),
3705 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00003706 break;
3707 }
3708
3709 case SK_BindReference:
3710 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3711 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3712 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003713 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003714 << BitField->getDeclName()
3715 << CurInitExpr->getSourceRange();
3716 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00003717 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003718 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003719
Anders Carlsson09380262010-01-31 17:18:49 +00003720 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003721 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003722 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3723 << Entity.getType().isVolatileQualified()
3724 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003725 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003726 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00003727 }
3728
Douglas Gregor20093b42009-12-09 23:02:17 +00003729 // Reference binding does not have any corresponding ASTs.
3730
3731 // Check exception specifications
3732 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003733 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003734
Douglas Gregor20093b42009-12-09 23:02:17 +00003735 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003736
Douglas Gregor20093b42009-12-09 23:02:17 +00003737 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003738 // Reference binding does not have any corresponding ASTs.
3739
Douglas Gregor20093b42009-12-09 23:02:17 +00003740 // Check exception specifications
3741 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003742 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003743
Douglas Gregor20093b42009-12-09 23:02:17 +00003744 break;
3745
Douglas Gregor523d46a2010-04-18 07:40:54 +00003746 case SK_ExtraneousCopyToTemporary:
3747 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3748 /*IsExtraneousCopy=*/true);
3749 break;
3750
Douglas Gregor20093b42009-12-09 23:02:17 +00003751 case SK_UserConversion: {
3752 // We have a user-defined conversion that invokes either a constructor
3753 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00003754 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003755 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003756 FunctionDecl *Fn = Step->Function.Function;
3757 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003758 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003759 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003760 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003761 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003762 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor20093b42009-12-09 23:02:17 +00003763 SourceLocation Loc = CurInitExpr->getLocStart();
3764 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003765
Douglas Gregor20093b42009-12-09 23:02:17 +00003766 // Determine the arguments required to actually perform the constructor
3767 // call.
3768 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00003769 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00003770 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003771 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003772
3773 // Build the an expression that constructs a temporary.
3774 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00003775 move_arg(ConstructorArgs),
3776 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003777 CXXConstructExpr::CK_Complete,
3778 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00003779 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003780 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003781
Anders Carlsson9a68a672010-04-21 18:47:17 +00003782 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003783 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003784 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor20093b42009-12-09 23:02:17 +00003785
John McCall2de56d12010-08-25 11:45:40 +00003786 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003787 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3788 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3789 S.IsDerivedFrom(SourceType, Class))
3790 IsCopy = true;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003791
3792 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003793 } else {
3794 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003795 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003796 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003797 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003798 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003799 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003800
Douglas Gregor20093b42009-12-09 23:02:17 +00003801 // FIXME: Should we move this initialization into a separate
3802 // derived-to-base conversion? I believe the answer is "no", because
3803 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003804 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003805 FoundFn, Conversion))
John McCallf312b1e2010-08-26 23:41:50 +00003806 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003807
3808 // Do a little dance to make sure that CurInit has the proper
3809 // pointer.
3810 CurInit.release();
3811
3812 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003813 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3814 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003815 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00003816 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003817
John McCall2de56d12010-08-25 11:45:40 +00003818 CastKind = CK_UserDefinedConversion;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003819
3820 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003821 }
3822
Douglas Gregor2f599792010-04-02 18:24:57 +00003823 bool RequiresCopy = !IsCopy &&
3824 getKind() != InitializationSequence::ReferenceBinding;
3825 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003826 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003827 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3828 CurInitExpr = static_cast<Expr *>(CurInit.get());
3829 QualType T = CurInitExpr->getType();
3830 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00003831 CXXDestructorDecl *Destructor
3832 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003833 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3834 S.PDiag(diag::err_access_dtor_temp) << T);
3835 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003836 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003837 }
3838 }
3839
Douglas Gregor20093b42009-12-09 23:02:17 +00003840 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redl906082e2010-07-20 04:20:21 +00003841 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00003842 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3843 CurInitExpr->getType(),
3844 CastKind, CurInitExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00003845 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003846
Douglas Gregor2f599792010-04-02 18:24:57 +00003847 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003848 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3849 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003850
Douglas Gregor20093b42009-12-09 23:02:17 +00003851 break;
3852 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003853
Douglas Gregor20093b42009-12-09 23:02:17 +00003854 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003855 case SK_QualificationConversionXValue:
3856 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003857 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00003858 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003859 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003860 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003861 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003862 VK_XValue :
3863 VK_RValue);
John McCall2de56d12010-08-25 11:45:40 +00003864 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00003865 CurInit.release();
3866 CurInit = S.Owned(CurInitExpr);
3867 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003868 }
3869
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003870 case SK_ConversionSequence: {
3871 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3872
3873 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
Douglas Gregora3998bd2010-12-02 21:47:04 +00003874 getAssignmentAction(Entity),
3875 IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003876 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003877
3878 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003879 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003880 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003881 }
3882
Douglas Gregord87b61f2009-12-10 17:56:55 +00003883 case SK_ListInitialization: {
3884 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3885 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003886 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00003887 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003888
3889 CurInit.release();
3890 CurInit = S.Owned(InitList);
3891 break;
3892 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003893
3894 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003895 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003896 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003897 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003898
Douglas Gregor51c56d62009-12-14 20:49:26 +00003899 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003900 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00003901 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3902 ? Kind.getEqualLoc()
3903 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003904
3905 if (Kind.getKind() == InitializationKind::IK_Default) {
3906 // Force even a trivial, implicit default constructor to be
3907 // semantically checked. We do this explicitly because we don't build
3908 // the definition for completely trivial constructors.
3909 CXXRecordDecl *ClassDecl = Constructor->getParent();
3910 assert(ClassDecl && "No parent class for constructor.");
3911 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3912 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3913 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3914 }
3915
Douglas Gregor51c56d62009-12-14 20:49:26 +00003916 // Determine the arguments required to actually perform the constructor
3917 // call.
3918 if (S.CompleteConstructorCall(Constructor, move(Args),
3919 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003920 return ExprError();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003921
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003922
Douglas Gregor91be6f52010-03-02 17:18:33 +00003923 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003924 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003925 (Kind.getKind() == InitializationKind::IK_Direct ||
3926 Kind.getKind() == InitializationKind::IK_Value)) {
3927 // An explicitly-constructed temporary, e.g., X(1, 2).
3928 unsigned NumExprs = ConstructorArgs.size();
3929 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003930 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003931 S.DiagnoseUseOfDecl(Constructor, Loc);
3932
Douglas Gregorab6677e2010-09-08 00:15:04 +00003933 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3934 if (!TSInfo)
3935 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3936
Douglas Gregor91be6f52010-03-02 17:18:33 +00003937 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3938 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00003939 TSInfo,
Douglas Gregor91be6f52010-03-02 17:18:33 +00003940 Exprs,
3941 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003942 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003943 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003944 } else {
3945 CXXConstructExpr::ConstructionKind ConstructKind =
3946 CXXConstructExpr::CK_Complete;
3947
3948 if (Entity.getKind() == InitializedEntity::EK_Base) {
3949 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3950 CXXConstructExpr::CK_VirtualBase :
3951 CXXConstructExpr::CK_NonVirtualBase;
3952 }
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003953
Chandler Carruth428edaf2010-10-25 08:47:36 +00003954 // Only get the parenthesis range if it is a direct construction.
3955 SourceRange parenRange =
3956 Kind.getKind() == InitializationKind::IK_Direct ?
3957 Kind.getParenRange() : SourceRange();
3958
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003959 // If the entity allows NRVO, mark the construction as elidable
3960 // unconditionally.
3961 if (Entity.allowsNRVO())
3962 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3963 Constructor, /*Elidable=*/true,
3964 move_arg(ConstructorArgs),
3965 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003966 ConstructKind,
3967 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003968 else
3969 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3970 Constructor,
3971 move_arg(ConstructorArgs),
3972 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003973 ConstructKind,
3974 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003975 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003976 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003977 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003978
3979 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00003980 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003981 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003982 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003983
Douglas Gregor2f599792010-04-02 18:24:57 +00003984 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003985 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003986
Douglas Gregor51c56d62009-12-14 20:49:26 +00003987 break;
3988 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003989
3990 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003991 step_iterator NextStep = Step;
3992 ++NextStep;
3993 if (NextStep != StepEnd &&
3994 NextStep->Kind == SK_ConstructorInitialization) {
3995 // The need for zero-initialization is recorded directly into
3996 // the call to the object's constructor within the next step.
3997 ConstructorInitRequiresZeroInit = true;
3998 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3999 S.getLangOptions().CPlusPlus &&
4000 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004001 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4002 if (!TSInfo)
4003 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
4004 Kind.getRange().getBegin());
4005
4006 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4007 TSInfo->getType().getNonLValueExprType(S.Context),
4008 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004009 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004010 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004011 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004012 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004013 break;
4014 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004015
4016 case SK_CAssignment: {
4017 QualType SourceType = CurInitExpr->getType();
4018 Sema::AssignConvertType ConvTy =
4019 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00004020
4021 // If this is a call, allow conversion to a transparent union.
4022 if (ConvTy != Sema::Compatible &&
4023 Entity.getKind() == InitializedEntity::EK_Parameter &&
4024 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4025 == Sema::Compatible)
4026 ConvTy = Sema::Compatible;
4027
Douglas Gregora41a8c52010-04-22 00:20:18 +00004028 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004029 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4030 Step->Type, SourceType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00004031 CurInitExpr,
4032 getAssignmentAction(Entity),
4033 &Complained)) {
4034 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004035 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004036 } else if (Complained)
4037 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004038
4039 CurInit.release();
4040 CurInit = S.Owned(CurInitExpr);
4041 break;
4042 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004043
4044 case SK_StringInit: {
4045 QualType Ty = Step->Type;
4046 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
4047 break;
4048 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004049
4050 case SK_ObjCObjectConversion:
4051 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004052 CK_ObjCObjectLValueCast,
Douglas Gregor569c3162010-08-07 11:51:51 +00004053 S.CastCategory(CurInitExpr));
4054 CurInit.release();
4055 CurInit = S.Owned(CurInitExpr);
4056 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004057 }
4058 }
John McCall15d7d122010-11-11 03:21:53 +00004059
4060 // Diagnose non-fatal problems with the completed initialization.
4061 if (Entity.getKind() == InitializedEntity::EK_Member &&
4062 cast<FieldDecl>(Entity.getDecl())->isBitField())
4063 S.CheckBitFieldInitialization(Kind.getLocation(),
4064 cast<FieldDecl>(Entity.getDecl()),
4065 CurInit.get());
Douglas Gregor20093b42009-12-09 23:02:17 +00004066
4067 return move(CurInit);
4068}
4069
4070//===----------------------------------------------------------------------===//
4071// Diagnose initialization failures
4072//===----------------------------------------------------------------------===//
4073bool InitializationSequence::Diagnose(Sema &S,
4074 const InitializedEntity &Entity,
4075 const InitializationKind &Kind,
4076 Expr **Args, unsigned NumArgs) {
4077 if (SequenceKind != FailedSequence)
4078 return false;
4079
Douglas Gregord6542d82009-12-22 15:35:07 +00004080 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004081 switch (Failure) {
4082 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004083 // FIXME: Customize for the initialized entity?
4084 if (NumArgs == 0)
4085 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4086 << DestType.getNonReferenceType();
4087 else // FIXME: diagnostic below could be better!
4088 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4089 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004090 break;
4091
4092 case FK_ArrayNeedsInitList:
4093 case FK_ArrayNeedsInitListOrStringLiteral:
4094 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4095 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4096 break;
4097
John McCall6bb80172010-03-30 21:47:33 +00004098 case FK_AddressOfOverloadFailed: {
4099 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00004100 S.ResolveAddressOfOverloadedFunction(Args[0],
4101 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004102 true,
4103 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004104 break;
John McCall6bb80172010-03-30 21:47:33 +00004105 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004106
4107 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004108 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004109 switch (FailedOverloadResult) {
4110 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004111 if (Failure == FK_UserConversionOverloadFailed)
4112 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4113 << Args[0]->getType() << DestType
4114 << Args[0]->getSourceRange();
4115 else
4116 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4117 << DestType << Args[0]->getType()
4118 << Args[0]->getSourceRange();
4119
John McCall120d63c2010-08-24 20:38:10 +00004120 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004121 break;
4122
4123 case OR_No_Viable_Function:
4124 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4125 << Args[0]->getType() << DestType.getNonReferenceType()
4126 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004127 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004128 break;
4129
4130 case OR_Deleted: {
4131 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4132 << Args[0]->getType() << DestType.getNonReferenceType()
4133 << Args[0]->getSourceRange();
4134 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004135 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004136 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4137 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004138 if (Ovl == OR_Deleted) {
4139 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4140 << Best->Function->isDeleted();
4141 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004142 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004143 }
4144 break;
4145 }
4146
4147 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004148 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004149 break;
4150 }
4151 break;
4152
4153 case FK_NonConstLValueReferenceBindingToTemporary:
4154 case FK_NonConstLValueReferenceBindingToUnrelated:
4155 S.Diag(Kind.getLocation(),
4156 Failure == FK_NonConstLValueReferenceBindingToTemporary
4157 ? diag::err_lvalue_reference_bind_to_temporary
4158 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004159 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004160 << DestType.getNonReferenceType()
4161 << Args[0]->getType()
4162 << Args[0]->getSourceRange();
4163 break;
4164
4165 case FK_RValueReferenceBindingToLValue:
4166 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4167 << Args[0]->getSourceRange();
4168 break;
4169
4170 case FK_ReferenceInitDropsQualifiers:
4171 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4172 << DestType.getNonReferenceType()
4173 << Args[0]->getType()
4174 << Args[0]->getSourceRange();
4175 break;
4176
4177 case FK_ReferenceInitFailed:
4178 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4179 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004180 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004181 << Args[0]->getType()
4182 << Args[0]->getSourceRange();
4183 break;
4184
4185 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004186 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4187 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004188 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004189 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004190 << Args[0]->getType()
4191 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004192 break;
4193
4194 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004195 SourceRange R;
4196
4197 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004198 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004199 InitList->getLocEnd());
Douglas Gregor19311e72010-09-08 21:40:08 +00004200 else
4201 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004202
Douglas Gregor19311e72010-09-08 21:40:08 +00004203 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4204 if (Kind.isCStyleOrFunctionalCast())
4205 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4206 << R;
4207 else
4208 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4209 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004210 break;
4211 }
4212
4213 case FK_ReferenceBindingToInitList:
4214 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4215 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4216 break;
4217
4218 case FK_InitListBadDestinationType:
4219 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4220 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4221 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00004222
4223 case FK_ConstructorOverloadFailed: {
4224 SourceRange ArgsRange;
4225 if (NumArgs)
4226 ArgsRange = SourceRange(Args[0]->getLocStart(),
4227 Args[NumArgs - 1]->getLocEnd());
4228
4229 // FIXME: Using "DestType" for the entity we're printing is probably
4230 // bad.
4231 switch (FailedOverloadResult) {
4232 case OR_Ambiguous:
4233 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4234 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004235 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4236 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004237 break;
4238
4239 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004240 if (Kind.getKind() == InitializationKind::IK_Default &&
4241 (Entity.getKind() == InitializedEntity::EK_Base ||
4242 Entity.getKind() == InitializedEntity::EK_Member) &&
4243 isa<CXXConstructorDecl>(S.CurContext)) {
4244 // This is implicit default initialization of a member or
4245 // base within a constructor. If no viable function was
4246 // found, notify the user that she needs to explicitly
4247 // initialize this base/member.
4248 CXXConstructorDecl *Constructor
4249 = cast<CXXConstructorDecl>(S.CurContext);
4250 if (Entity.getKind() == InitializedEntity::EK_Base) {
4251 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4252 << Constructor->isImplicit()
4253 << S.Context.getTypeDeclType(Constructor->getParent())
4254 << /*base=*/0
4255 << Entity.getType();
4256
4257 RecordDecl *BaseDecl
4258 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4259 ->getDecl();
4260 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4261 << S.Context.getTagDeclType(BaseDecl);
4262 } else {
4263 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4264 << Constructor->isImplicit()
4265 << S.Context.getTypeDeclType(Constructor->getParent())
4266 << /*member=*/1
4267 << Entity.getName();
4268 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4269
4270 if (const RecordType *Record
4271 = Entity.getType()->getAs<RecordType>())
4272 S.Diag(Record->getDecl()->getLocation(),
4273 diag::note_previous_decl)
4274 << S.Context.getTagDeclType(Record->getDecl());
4275 }
4276 break;
4277 }
4278
Douglas Gregor51c56d62009-12-14 20:49:26 +00004279 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4280 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004281 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004282 break;
4283
4284 case OR_Deleted: {
4285 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4286 << true << DestType << ArgsRange;
4287 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004288 OverloadingResult Ovl
4289 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004290 if (Ovl == OR_Deleted) {
4291 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4292 << Best->Function->isDeleted();
4293 } else {
4294 llvm_unreachable("Inconsistent overload resolution?");
4295 }
4296 break;
4297 }
4298
4299 case OR_Success:
4300 llvm_unreachable("Conversion did not fail!");
4301 break;
4302 }
4303 break;
4304 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004305
4306 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004307 if (Entity.getKind() == InitializedEntity::EK_Member &&
4308 isa<CXXConstructorDecl>(S.CurContext)) {
4309 // This is implicit default-initialization of a const member in
4310 // a constructor. Complain that it needs to be explicitly
4311 // initialized.
4312 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4313 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4314 << Constructor->isImplicit()
4315 << S.Context.getTypeDeclType(Constructor->getParent())
4316 << /*const=*/1
4317 << Entity.getName();
4318 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4319 << Entity.getName();
4320 } else {
4321 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4322 << DestType << (bool)DestType->getAs<RecordType>();
4323 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004324 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004325
4326 case FK_Incomplete:
4327 S.RequireCompleteType(Kind.getLocation(), DestType,
4328 diag::err_init_incomplete_type);
4329 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004330 }
4331
Douglas Gregora41a8c52010-04-22 00:20:18 +00004332 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004333 return true;
4334}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004335
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004336void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4337 switch (SequenceKind) {
4338 case FailedSequence: {
4339 OS << "Failed sequence: ";
4340 switch (Failure) {
4341 case FK_TooManyInitsForReference:
4342 OS << "too many initializers for reference";
4343 break;
4344
4345 case FK_ArrayNeedsInitList:
4346 OS << "array requires initializer list";
4347 break;
4348
4349 case FK_ArrayNeedsInitListOrStringLiteral:
4350 OS << "array requires initializer list or string literal";
4351 break;
4352
4353 case FK_AddressOfOverloadFailed:
4354 OS << "address of overloaded function failed";
4355 break;
4356
4357 case FK_ReferenceInitOverloadFailed:
4358 OS << "overload resolution for reference initialization failed";
4359 break;
4360
4361 case FK_NonConstLValueReferenceBindingToTemporary:
4362 OS << "non-const lvalue reference bound to temporary";
4363 break;
4364
4365 case FK_NonConstLValueReferenceBindingToUnrelated:
4366 OS << "non-const lvalue reference bound to unrelated type";
4367 break;
4368
4369 case FK_RValueReferenceBindingToLValue:
4370 OS << "rvalue reference bound to an lvalue";
4371 break;
4372
4373 case FK_ReferenceInitDropsQualifiers:
4374 OS << "reference initialization drops qualifiers";
4375 break;
4376
4377 case FK_ReferenceInitFailed:
4378 OS << "reference initialization failed";
4379 break;
4380
4381 case FK_ConversionFailed:
4382 OS << "conversion failed";
4383 break;
4384
4385 case FK_TooManyInitsForScalar:
4386 OS << "too many initializers for scalar";
4387 break;
4388
4389 case FK_ReferenceBindingToInitList:
4390 OS << "referencing binding to initializer list";
4391 break;
4392
4393 case FK_InitListBadDestinationType:
4394 OS << "initializer list for non-aggregate, non-scalar type";
4395 break;
4396
4397 case FK_UserConversionOverloadFailed:
4398 OS << "overloading failed for user-defined conversion";
4399 break;
4400
4401 case FK_ConstructorOverloadFailed:
4402 OS << "constructor overloading failed";
4403 break;
4404
4405 case FK_DefaultInitOfConst:
4406 OS << "default initialization of a const variable";
4407 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004408
4409 case FK_Incomplete:
4410 OS << "initialization of incomplete type";
4411 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004412 }
4413 OS << '\n';
4414 return;
4415 }
4416
4417 case DependentSequence:
4418 OS << "Dependent sequence: ";
4419 return;
4420
4421 case UserDefinedConversion:
4422 OS << "User-defined conversion sequence: ";
4423 break;
4424
4425 case ConstructorInitialization:
4426 OS << "Constructor initialization sequence: ";
4427 break;
4428
4429 case ReferenceBinding:
4430 OS << "Reference binding: ";
4431 break;
4432
4433 case ListInitialization:
4434 OS << "List initialization: ";
4435 break;
4436
4437 case ZeroInitialization:
4438 OS << "Zero initialization\n";
4439 return;
4440
4441 case NoInitialization:
4442 OS << "No initialization\n";
4443 return;
4444
4445 case StandardConversion:
4446 OS << "Standard conversion: ";
4447 break;
4448
4449 case CAssignment:
4450 OS << "C assignment: ";
4451 break;
4452
4453 case StringInit:
4454 OS << "String initialization: ";
4455 break;
4456 }
4457
4458 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4459 if (S != step_begin()) {
4460 OS << " -> ";
4461 }
4462
4463 switch (S->Kind) {
4464 case SK_ResolveAddressOfOverloadedFunction:
4465 OS << "resolve address of overloaded function";
4466 break;
4467
4468 case SK_CastDerivedToBaseRValue:
4469 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4470 break;
4471
Sebastian Redl906082e2010-07-20 04:20:21 +00004472 case SK_CastDerivedToBaseXValue:
4473 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4474 break;
4475
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004476 case SK_CastDerivedToBaseLValue:
4477 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4478 break;
4479
4480 case SK_BindReference:
4481 OS << "bind reference to lvalue";
4482 break;
4483
4484 case SK_BindReferenceToTemporary:
4485 OS << "bind reference to a temporary";
4486 break;
4487
Douglas Gregor523d46a2010-04-18 07:40:54 +00004488 case SK_ExtraneousCopyToTemporary:
4489 OS << "extraneous C++03 copy to temporary";
4490 break;
4491
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004492 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004493 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004494 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004495
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004496 case SK_QualificationConversionRValue:
4497 OS << "qualification conversion (rvalue)";
4498
Sebastian Redl906082e2010-07-20 04:20:21 +00004499 case SK_QualificationConversionXValue:
4500 OS << "qualification conversion (xvalue)";
4501
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004502 case SK_QualificationConversionLValue:
4503 OS << "qualification conversion (lvalue)";
4504 break;
4505
4506 case SK_ConversionSequence:
4507 OS << "implicit conversion sequence (";
4508 S->ICS->DebugPrint(); // FIXME: use OS
4509 OS << ")";
4510 break;
4511
4512 case SK_ListInitialization:
4513 OS << "list initialization";
4514 break;
4515
4516 case SK_ConstructorInitialization:
4517 OS << "constructor initialization";
4518 break;
4519
4520 case SK_ZeroInitialization:
4521 OS << "zero initialization";
4522 break;
4523
4524 case SK_CAssignment:
4525 OS << "C assignment";
4526 break;
4527
4528 case SK_StringInit:
4529 OS << "string initialization";
4530 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004531
4532 case SK_ObjCObjectConversion:
4533 OS << "Objective-C object conversion";
4534 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004535 }
4536 }
4537}
4538
4539void InitializationSequence::dump() const {
4540 dump(llvm::errs());
4541}
4542
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004543//===----------------------------------------------------------------------===//
4544// Initialization helper functions
4545//===----------------------------------------------------------------------===//
John McCall60d7b3a2010-08-24 06:29:42 +00004546ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004547Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4548 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004549 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004550 if (Init.isInvalid())
4551 return ExprError();
4552
John McCall15d7d122010-11-11 03:21:53 +00004553 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004554 assert(InitE && "No initialization expression?");
4555
4556 if (EqualLoc.isInvalid())
4557 EqualLoc = InitE->getLocStart();
4558
4559 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4560 EqualLoc);
4561 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4562 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004563 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004564}