blob: 3540cd02e6da8adb8dc5ad9a80014313da8d8906 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor3e1e5272009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregor4e0299b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000020#include "Sema.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000022#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000024#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Chris Lattnerd8b741c82009-02-24 23:10:27 +000035static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000036 const ArrayType *AT = Context.getAsArrayType(DeclType);
37 if (!AT) return 0;
38
Eli Friedman893abe42009-05-29 18:22:49 +000039 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40 return 0;
41
Chris Lattnera9196812009-02-26 23:26:43 +000042 // See if this is a string literal or @encode.
43 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnera9196812009-02-26 23:26:43 +000045 // Handle @encode, which is a narrow string.
46 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
47 return Init;
48
49 // Otherwise we can only handle string literals.
50 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000051 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000052
53 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000054 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
56 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000058
Eli Friedman42a84652009-05-31 10:54:53 +000059 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
60 // correction from DR343): "An array with element type compatible with a
61 // qualified or unqualified version of wchar_t may be initialized by a wide
62 // string literal, optionally enclosed in braces."
63 if (Context.typesAreCompatible(Context.getWCharType(),
64 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000065 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattner0cb78032009-02-24 22:27:37 +000067 return 0;
68}
69
Chris Lattnerd8b741c82009-02-24 23:10:27 +000070static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
71 // Get the length of the string as parsed.
72 uint64_t StrLength =
73 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
74
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnerd8b741c82009-02-24 23:10:27 +000076 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000077 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000078 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000079 // being initialized to a string literal.
80 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000081 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000082 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000083 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
84 ConstVal,
85 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000086 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000087 }
Mike Stump11289f42009-09-09 15:08:12 +000088
Eli Friedman893abe42009-05-29 18:22:49 +000089 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000090
Eli Friedman893abe42009-05-29 18:22:49 +000091 // C99 6.7.8p14. We have an array of character type with known size. However,
92 // the size may be smaller or larger than the string we are initializing.
93 // FIXME: Avoid truncation for 64-bit length strings.
94 if (StrLength-1 > CAT->getSize().getZExtValue())
95 S.Diag(Str->getSourceRange().getBegin(),
96 diag::warn_initializer_string_for_char_array_too_long)
97 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000098
Eli Friedman893abe42009-05-29 18:22:49 +000099 // Set the type to the actual size that we are initializing. If we have
100 // something like:
101 // char x[1] = "foo";
102 // then this will set the string literal's type to char[1].
103 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000104}
105
Chris Lattner0cb78032009-02-24 22:27:37 +0000106//===----------------------------------------------------------------------===//
107// Semantic checking for initializer lists.
108//===----------------------------------------------------------------------===//
109
Douglas Gregorcde232f2009-01-29 01:05:33 +0000110/// @brief Semantic checking for initializer lists.
111///
112/// The InitListChecker class contains a set of routines that each
113/// handle the initialization of a certain kind of entity, e.g.,
114/// arrays, vectors, struct/union types, scalars, etc. The
115/// InitListChecker itself performs a recursive walk of the subobject
116/// structure of the type to be initialized, while stepping through
117/// the initializer list one element at a time. The IList and Index
118/// parameters to each of the Check* routines contain the active
119/// (syntactic) initializer list and the index into that initializer
120/// list that represents the current initializer. Each routine is
121/// responsible for moving that Index forward as it consumes elements.
122///
123/// Each Check* routine also has a StructuredList/StructuredIndex
124/// arguments, which contains the current the "structured" (semantic)
125/// initializer list and the index into that initializer list where we
126/// are copying initializers as we map them over to the semantic
127/// list. Once we have completed our recursive walk of the subobject
128/// structure, we will have constructed a full semantic initializer
129/// list.
130///
131/// C99 designators cause changes in the initializer list traversal,
132/// because they make the initialization "jump" into a specific
133/// subobject and then continue the initialization from that
134/// point. CheckDesignatedInitializer() recursively steps into the
135/// designated subobject and manages backing out the recursion to
136/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000137namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000138class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000139 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000140 bool hadError;
141 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
142 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000143
Anders Carlsson6cabf312010-01-23 23:23:01 +0000144 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000145 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000146 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000147 unsigned &StructuredIndex,
148 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000149 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000150 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000151 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000152 unsigned &StructuredIndex,
153 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000154 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000155 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000156 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000157 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000159 unsigned &StructuredIndex,
160 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000161 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000162 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000163 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000164 InitListExpr *StructuredList,
165 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000166 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000167 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000168 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000169 InitListExpr *StructuredList,
170 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000171 void CheckReferenceType(const InitializedEntity &Entity,
172 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000173 unsigned &Index,
174 InitListExpr *StructuredList,
175 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000180 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000181 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000182 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000183 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000184 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000187 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000189 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000190 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000194 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000195 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000196 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000197 RecordDecl::field_iterator *NextField,
198 llvm::APSInt *NextElementIndex,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000202 bool FinishSubobjectInit,
203 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000204 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
205 QualType CurrentObjectType,
206 InitListExpr *StructuredList,
207 unsigned StructuredIndex,
208 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000209 void UpdateStructuredListElement(InitListExpr *StructuredList,
210 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000211 Expr *expr);
212 int numArrayElements(QualType DeclType);
213 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000214
Douglas Gregor2bb07652009-12-22 00:05:34 +0000215 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
216 const InitializedEntity &ParentEntity,
217 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000218 void FillInValueInitializations(const InitializedEntity &Entity,
219 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000221 InitListChecker(Sema &S, const InitializedEntity &Entity,
222 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000223 bool HadError() { return hadError; }
224
225 // @brief Retrieves the fully-structured initializer list used for
226 // semantic analysis and code generation.
227 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
228};
Chris Lattner9ececce2009-02-24 22:48:58 +0000229} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000230
Douglas Gregor2bb07652009-12-22 00:05:34 +0000231void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
232 const InitializedEntity &ParentEntity,
233 InitListExpr *ILE,
234 bool &RequiresSecondPass) {
235 SourceLocation Loc = ILE->getSourceRange().getBegin();
236 unsigned NumInits = ILE->getNumInits();
237 InitializedEntity MemberEntity
238 = InitializedEntity::InitializeMember(Field, &ParentEntity);
239 if (Init >= NumInits || !ILE->getInit(Init)) {
240 // FIXME: We probably don't need to handle references
241 // specially here, since value-initialization of references is
242 // handled in InitializationSequence.
243 if (Field->getType()->isReferenceType()) {
244 // C++ [dcl.init.aggr]p9:
245 // If an incomplete or empty initializer-list leaves a
246 // member of reference type uninitialized, the program is
247 // ill-formed.
248 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
249 << Field->getType()
250 << ILE->getSyntacticForm()->getSourceRange();
251 SemaRef.Diag(Field->getLocation(),
252 diag::note_uninit_reference_member);
253 hadError = true;
254 return;
255 }
256
257 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
258 true);
259 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
260 if (!InitSeq) {
261 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
262 hadError = true;
263 return;
264 }
265
266 Sema::OwningExprResult MemberInit
267 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
268 Sema::MultiExprArg(SemaRef, 0, 0));
269 if (MemberInit.isInvalid()) {
270 hadError = true;
271 return;
272 }
273
274 if (hadError) {
275 // Do nothing
276 } else if (Init < NumInits) {
277 ILE->setInit(Init, MemberInit.takeAs<Expr>());
278 } else if (InitSeq.getKind()
279 == InitializationSequence::ConstructorInitialization) {
280 // Value-initialization requires a constructor call, so
281 // extend the initializer list to include the constructor
282 // call and make a note that we'll need to take another pass
283 // through the initializer list.
Ted Kremenek013041e2010-02-19 01:50:18 +0000284 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000285 RequiresSecondPass = true;
286 }
287 } else if (InitListExpr *InnerILE
288 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289 FillInValueInitializations(MemberEntity, InnerILE,
290 RequiresSecondPass);
291}
292
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000307 if (RType->getDecl()->isUnion() &&
308 ILE->getInitializedFieldInUnion())
309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310 Entity, ILE, RequiresSecondPass);
311 else {
312 unsigned Init = 0;
313 for (RecordDecl::field_iterator
314 Field = RType->getDecl()->field_begin(),
315 FieldEnd = RType->getDecl()->field_end();
316 Field != FieldEnd; ++Field) {
317 if (Field->isUnnamedBitfield())
318 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000319
Douglas Gregor2bb07652009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000321 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000326
Douglas Gregor2bb07652009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000328
Douglas Gregor2bb07652009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump11289f42009-09-09 15:08:12 +0000336 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000339
Douglas Gregor723796a2009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000354 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor723796a2009-12-16 06:35:08 +0000357
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368 true);
369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370 if (!InitSeq) {
371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
Douglas Gregor723796a2009-12-16 06:35:08 +0000376 Sema::OwningExprResult ElementInit
377 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
378 Sema::MultiExprArg(SemaRef, 0, 0));
379 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000380 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000381 return;
382 }
383
384 if (hadError) {
385 // Do nothing
386 } else if (Init < NumInits) {
387 ILE->setInit(Init, ElementInit.takeAs<Expr>());
388 } else if (InitSeq.getKind()
389 == InitializationSequence::ConstructorInitialization) {
390 // Value-initialization requires a constructor call, so
391 // extend the initializer list to include the constructor
392 // call and make a note that we'll need to take another pass
393 // through the initializer list.
Ted Kremenek013041e2010-02-19 01:50:18 +0000394 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 RequiresSecondPass = true;
396 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000397 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000398 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
399 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000400 }
401}
402
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000403
Douglas Gregor723796a2009-12-16 06:35:08 +0000404InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
405 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000406 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000407 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000408
Eli Friedman23a9e312008-05-19 19:16:24 +0000409 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000410 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000411 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000412 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000413 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000414 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000415 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000416
Douglas Gregor723796a2009-12-16 06:35:08 +0000417 if (!hadError) {
418 bool RequiresSecondPass = false;
419 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000420 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000421 FillInValueInitializations(Entity, FullyStructuredList,
422 RequiresSecondPass);
423 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000424}
425
426int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000427 // FIXME: use a proper constant
428 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000429 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000430 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000431 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
432 }
433 return maxElements;
434}
435
436int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000437 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000438 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000439 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000440 Field = structDecl->field_begin(),
441 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000442 Field != FieldEnd; ++Field) {
443 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
444 ++InitializableMembers;
445 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000446 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000447 return std::min(InitializableMembers, 1);
448 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000449}
450
Anders Carlsson6cabf312010-01-23 23:23:01 +0000451void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000452 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000453 QualType T, unsigned &Index,
454 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000455 unsigned &StructuredIndex,
456 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000457 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000458
Steve Narofff8ecff22008-05-01 22:18:59 +0000459 if (T->isArrayType())
460 maxElements = numArrayElements(T);
461 else if (T->isStructureType() || T->isUnionType())
462 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000463 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000464 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000465 else
466 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000467
Eli Friedmane0f832b2008-05-25 13:49:22 +0000468 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000469 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000470 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000471 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000472 hadError = true;
473 return;
474 }
475
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000476 // Build a structured initializer list corresponding to this subobject.
477 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000478 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
479 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000480 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
481 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000482 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000483
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000484 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000485 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000486 CheckListElementTypes(Entity, ParentIList, T,
487 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000488 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000489 StructuredSubobjectInitIndex,
490 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000491 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000492 StructuredSubobjectInitList->setType(T);
493
Douglas Gregor5741efb2009-03-01 17:12:46 +0000494 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000495 // range corresponds with the end of the last initializer it used.
496 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000497 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000498 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
499 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
500 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000501
502 // Warn about missing braces.
503 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000504 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
505 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000506 << StructuredSubobjectInitList->getSourceRange()
507 << CodeModificationHint::CreateInsertion(
508 StructuredSubobjectInitList->getLocStart(),
Tanya Lattner5cbff482010-03-07 04:40:06 +0000509 "{")
Tanya Lattner5029d562010-03-07 04:17:15 +0000510 << CodeModificationHint::CreateInsertion(
511 SemaRef.PP.getLocForEndOfToken(
Tanya Lattner5cb196e2010-03-07 04:47:12 +0000512 StructuredSubobjectInitList->getLocEnd()),
513 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000514 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000515}
516
Anders Carlsson6cabf312010-01-23 23:23:01 +0000517void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000518 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000519 unsigned &Index,
520 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000521 unsigned &StructuredIndex,
522 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000523 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000524 SyntacticToSemantic[IList] = StructuredList;
525 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000526 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
527 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor34c0a902010-02-09 00:50:06 +0000528 IList->setType(T.getNonReferenceType());
529 StructuredList->setType(T.getNonReferenceType());
Eli Friedman85f54972008-05-25 13:22:35 +0000530 if (hadError)
531 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000532
Eli Friedman85f54972008-05-25 13:22:35 +0000533 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000534 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000535 if (StructuredIndex == 1 &&
536 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000537 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000538 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000539 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000540 hadError = true;
541 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000542 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000543 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000544 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000545 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000546 // Don't complain for incomplete types, since we'll get an error
547 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000548 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000549 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000550 CurrentObjectType->isArrayType()? 0 :
551 CurrentObjectType->isVectorType()? 1 :
552 CurrentObjectType->isScalarType()? 2 :
553 CurrentObjectType->isUnionType()? 3 :
554 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000555
556 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000557 if (SemaRef.getLangOptions().CPlusPlus) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Nate Begeman425038c2009-07-07 21:53:06 +0000561 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
562 DK = diag::err_excess_initializers;
563 hadError = true;
564 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000565
Chris Lattnerb0912a52009-02-24 22:50:46 +0000566 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000567 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000568 }
569 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000570
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000571 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000572 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000573 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000574 << CodeModificationHint::CreateRemoval(IList->getLocStart())
575 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000576}
577
Anders Carlsson6cabf312010-01-23 23:23:01 +0000578void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000579 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000580 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000581 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000582 unsigned &Index,
583 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000584 unsigned &StructuredIndex,
585 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000586 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000587 CheckScalarType(Entity, IList, DeclType, Index,
588 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000589 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000590 CheckVectorType(Entity, IList, DeclType, Index,
591 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000592 } else if (DeclType->isAggregateType()) {
593 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000594 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000595 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000596 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 StructuredList, StructuredIndex,
598 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000599 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000600 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000601 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000602 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000603 CheckArrayType(Entity, IList, DeclType, Zero,
604 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000605 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000607 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000608 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
609 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000610 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000613 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000614 } else if (DeclType->isRecordType()) {
615 // C++ [dcl.init]p14:
616 // [...] If the class is an aggregate (8.5.1), and the initializer
617 // is a brace-enclosed list, see 8.5.1.
618 //
619 // Note: 8.5.1 is handled below; here, we diagnose the case where
620 // we have an initializer list and a destination type that is not
621 // an aggregate.
622 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000623 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000624 << DeclType << IList->getSourceRange();
625 hadError = true;
626 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000627 CheckReferenceType(Entity, IList, DeclType, Index,
628 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000629 } else {
630 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000631 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000632 assert(0 && "Unsupported initializer type");
633 }
634}
635
Anders Carlsson6cabf312010-01-23 23:23:01 +0000636void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000637 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000638 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000639 unsigned &Index,
640 InitListExpr *StructuredList,
641 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000642 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000643 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
644 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000645 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000646 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000647 = getStructuredSubobjectInit(IList, Index, ElemType,
648 StructuredList, StructuredIndex,
649 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000650 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000651 newStructuredList, newStructuredIndex);
652 ++StructuredIndex;
653 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000654 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
655 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000656 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000657 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000658 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000659 CheckScalarType(Entity, IList, ElemType, Index,
660 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000661 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000662 CheckReferenceType(Entity, IList, ElemType, Index,
663 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000664 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000665 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-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 Carlsson03068aa2009-08-27 17:18:13 +0000671
Anders Carlsson0bd52402010-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) {
678 Sema::OwningExprResult Result =
679 Seq.Perform(SemaRef, Entity, Kind,
680 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
681 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000682 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000683
684 UpdateStructuredListElement(StructuredList, StructuredIndex,
685 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000686 ++Index;
687 return;
688 }
689
690 // Fall through for subaggregate initialization
691 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000692 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000693 //
694 // The initializer for a structure or union object that has
695 // automatic storage duration shall be either an initializer
696 // list as described below, or a single expression that has
697 // compatible structure or union type. In the latter case, the
698 // initial value of the object, including unnamed members, is
699 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000700 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000701 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000702 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
703 ++Index;
704 return;
705 }
706
707 // Fall through for subaggregate initialization
708 }
709
710 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000711 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000712 // [...] Otherwise, if the member is itself a non-empty
713 // subaggregate, brace elision is assumed and the initializer is
714 // considered for the initialization of the first member of
715 // the subaggregate.
716 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000717 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000718 StructuredIndex);
719 ++StructuredIndex;
720 } else {
721 // We cannot initialize this element, so let
722 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssona18f0fb2010-01-30 01:56:32 +0000723 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
724 SemaRef.Owned(expr));
725 IList->setInit(Index, 0);
Douglas Gregord14247a2009-01-30 22:09:00 +0000726 hadError = true;
727 ++Index;
728 ++StructuredIndex;
729 }
730 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000731}
732
Anders Carlsson6cabf312010-01-23 23:23:01 +0000733void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000734 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000735 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000736 InitListExpr *StructuredList,
737 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000738 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000739 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000740 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000741 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000742 diag::err_many_braces_around_scalar_init)
743 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000744 hadError = true;
745 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000746 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000747 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000748 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000749 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000750 diag::err_designator_for_scalar_init)
751 << DeclType << expr->getSourceRange();
752 hadError = true;
753 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000754 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000755 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000756 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000757
Anders Carlsson26d05642010-01-23 18:35:41 +0000758 Sema::OwningExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000759 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
760 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000761
Chandler Carruthdfe198b2010-02-13 07:23:01 +0000762 Expr *ResultExpr = 0;
Anders Carlsson26d05642010-01-23 18:35:41 +0000763
764 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000765 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000766 else {
767 ResultExpr = Result.takeAs<Expr>();
768
769 if (ResultExpr != expr) {
770 // The type was promoted, update initializer list.
771 IList->setInit(Index, ResultExpr);
772 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000773 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000774 if (hadError)
775 ++StructuredIndex;
776 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000777 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000778 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000779 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000780 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000781 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000782 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000783 ++Index;
784 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000785 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000786 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000787}
788
Anders Carlsson6cabf312010-01-23 23:23:01 +0000789void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
790 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000791 unsigned &Index,
792 InitListExpr *StructuredList,
793 unsigned &StructuredIndex) {
794 if (Index < IList->getNumInits()) {
795 Expr *expr = IList->getInit(Index);
796 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000797 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000798 << DeclType << IList->getSourceRange();
799 hadError = true;
800 ++Index;
801 ++StructuredIndex;
802 return;
Mike Stump11289f42009-09-09 15:08:12 +0000803 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000804
Anders Carlssona91be642010-01-29 02:47:33 +0000805 Sema::OwningExprResult Result =
806 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
807 SemaRef.Owned(expr));
808
809 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000810 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000811
812 expr = Result.takeAs<Expr>();
813 IList->setInit(Index, expr);
814
Douglas Gregord14247a2009-01-30 22:09:00 +0000815 if (hadError)
816 ++StructuredIndex;
817 else
818 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
819 ++Index;
820 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000821 // FIXME: It would be wonderful if we could point at the actual member. In
822 // general, it would be useful to pass location information down the stack,
823 // so that we know the location (or decl) of the "current object" being
824 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000825 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000826 diag::err_init_reference_member_uninitialized)
827 << DeclType
828 << IList->getSourceRange();
829 hadError = true;
830 ++Index;
831 ++StructuredIndex;
832 return;
833 }
834}
835
Anders Carlsson6cabf312010-01-23 23:23:01 +0000836void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000837 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000838 unsigned &Index,
839 InitListExpr *StructuredList,
840 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000841 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000842 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000843 unsigned maxElements = VT->getNumElements();
844 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000845 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000846
Nate Begeman5ec4b312009-08-10 23:49:36 +0000847 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000848 InitializedEntity ElementEntity =
849 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000850
Anders Carlsson6cabf312010-01-23 23:23:01 +0000851 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
852 // Don't attempt to go past the end of the init list
853 if (Index >= IList->getNumInits())
854 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000855
Anders Carlsson6cabf312010-01-23 23:23:01 +0000856 ElementEntity.setElementIndex(Index);
857 CheckSubElementType(ElementEntity, IList, elementType, Index,
858 StructuredList, StructuredIndex);
859 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000860 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000861 InitializedEntity ElementEntity =
862 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
863
Nate Begeman5ec4b312009-08-10 23:49:36 +0000864 // OpenCL initializers allows vectors to be constructed from vectors.
865 for (unsigned i = 0; i < maxElements; ++i) {
866 // Don't attempt to go past the end of the init list
867 if (Index >= IList->getNumInits())
868 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000869
870 ElementEntity.setElementIndex(Index);
871
Nate Begeman5ec4b312009-08-10 23:49:36 +0000872 QualType IType = IList->getInit(Index)->getType();
873 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000874 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000875 StructuredList, StructuredIndex);
876 ++numEltsInit;
877 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000878 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000879 unsigned numIElts = IVT->getNumElements();
880 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
881 numIElts);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000882 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000883 StructuredList, StructuredIndex);
884 numEltsInit += numIElts;
885 }
886 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000887 }
Mike Stump11289f42009-09-09 15:08:12 +0000888
Nate Begeman5ec4b312009-08-10 23:49:36 +0000889 // OpenCL & AltiVec require all elements to be initialized.
890 if (numEltsInit != maxElements)
891 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
892 SemaRef.Diag(IList->getSourceRange().getBegin(),
893 diag::err_vector_incorrect_num_initializers)
894 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000895 }
896}
897
Anders Carlsson6cabf312010-01-23 23:23:01 +0000898void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000899 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000900 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000901 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000902 unsigned &Index,
903 InitListExpr *StructuredList,
904 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000905 // Check for the special-case of initializing an array with a string.
906 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000907 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
908 SemaRef.Context)) {
909 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000910 // We place the string literal directly into the resulting
911 // initializer list. This is the only place where the structure
912 // of the structured initializer list doesn't match exactly,
913 // because doing so would involve allocating one character
914 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000915 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000916 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000917 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000918 return;
919 }
920 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000921 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000922 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000923 // Check for VLAs; in standard C it would be possible to check this
924 // earlier, but I don't know where clang accepts VLAs (gcc accepts
925 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000926 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000927 diag::err_variable_object_no_init)
928 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000929 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000930 ++Index;
931 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000932 return;
933 }
934
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000935 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000936 llvm::APSInt maxElements(elementIndex.getBitWidth(),
937 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000938 bool maxElementsKnown = false;
939 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000940 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000941 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000942 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000943 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000944 maxElementsKnown = true;
945 }
946
Chris Lattnerb0912a52009-02-24 22:50:46 +0000947 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000948 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000949 while (Index < IList->getNumInits()) {
950 Expr *Init = IList->getInit(Index);
951 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000952 // If we're not the subobject that matches up with the '{' for
953 // the designator, we shouldn't be handling the
954 // designator. Return immediately.
955 if (!SubobjectIsDesignatorContext)
956 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000957
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000958 // Handle this designated initializer. elementIndex will be
959 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000960 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000961 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000962 StructuredList, StructuredIndex, true,
963 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000964 hadError = true;
965 continue;
966 }
967
Douglas Gregor033d1252009-01-23 16:54:12 +0000968 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
969 maxElements.extend(elementIndex.getBitWidth());
970 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
971 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000972 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000973
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000974 // If the array is of incomplete type, keep track of the number of
975 // elements in the initializer.
976 if (!maxElementsKnown && elementIndex > maxElements)
977 maxElements = elementIndex;
978
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000979 continue;
980 }
981
982 // If we know the maximum number of elements, and we've already
983 // hit it, stop consuming elements in the initializer list.
984 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000985 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000986
Anders Carlsson6cabf312010-01-23 23:23:01 +0000987 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000988 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000989 Entity);
990 // Check this element.
991 CheckSubElementType(ElementEntity, IList, elementType, Index,
992 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000993 ++elementIndex;
994
995 // If the array is of incomplete type, keep track of the number of
996 // elements in the initializer.
997 if (!maxElementsKnown && elementIndex > maxElements)
998 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +0000999 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001000 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001001 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001002 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001003 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001004 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001005 // Sizing an array implicitly to zero is not allowed by ISO C,
1006 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001007 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001008 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001009 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001010
Mike Stump11289f42009-09-09 15:08:12 +00001011 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001012 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001013 }
1014}
1015
Anders Carlsson6cabf312010-01-23 23:23:01 +00001016void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001017 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001018 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001019 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001020 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001021 unsigned &Index,
1022 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001023 unsigned &StructuredIndex,
1024 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001025 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001026
Eli Friedman23a9e312008-05-19 19:16:24 +00001027 // If the record is invalid, some of it's members are invalid. To avoid
1028 // confusion, we forgo checking the intializer for the entire record.
1029 if (structDecl->isInvalidDecl()) {
1030 hadError = true;
1031 return;
Mike Stump11289f42009-09-09 15:08:12 +00001032 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001033
1034 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1035 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001036 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001037 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001038 Field != FieldEnd; ++Field) {
1039 if (Field->getDeclName()) {
1040 StructuredList->setInitializedFieldInUnion(*Field);
1041 break;
1042 }
1043 }
1044 return;
1045 }
1046
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001047 // If structDecl is a forward declaration, this loop won't do
1048 // anything except look at designated initializers; That's okay,
1049 // because an error should get printed out elsewhere. It might be
1050 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001051 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001052 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001053 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001054 while (Index < IList->getNumInits()) {
1055 Expr *Init = IList->getInit(Index);
1056
1057 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001058 // If we're not the subobject that matches up with the '{' for
1059 // the designator, we shouldn't be handling the
1060 // designator. Return immediately.
1061 if (!SubobjectIsDesignatorContext)
1062 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001063
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001064 // Handle this designated initializer. Field will be updated to
1065 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001066 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001067 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001068 StructuredList, StructuredIndex,
1069 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001070 hadError = true;
1071
Douglas Gregora9add4e2009-02-12 19:00:39 +00001072 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001073 continue;
1074 }
1075
1076 if (Field == FieldEnd) {
1077 // We've run out of fields. We're done.
1078 break;
1079 }
1080
Douglas Gregora9add4e2009-02-12 19:00:39 +00001081 // We've already initialized a member of a union. We're done.
1082 if (InitializedSomething && DeclType->isUnionType())
1083 break;
1084
Douglas Gregor91f84212008-12-11 16:49:14 +00001085 // If we've hit the flexible array member at the end, we're done.
1086 if (Field->getType()->isIncompleteArrayType())
1087 break;
1088
Douglas Gregor51695702009-01-29 16:53:55 +00001089 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001090 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001091 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001092 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001093 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001094
Anders Carlsson6cabf312010-01-23 23:23:01 +00001095 InitializedEntity MemberEntity =
1096 InitializedEntity::InitializeMember(*Field, &Entity);
1097 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1098 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001099 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001100
1101 if (DeclType->isUnionType()) {
1102 // Initialize the first field within the union.
1103 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001104 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001105
1106 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001107 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001108
Mike Stump11289f42009-09-09 15:08:12 +00001109 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001110 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001111 return;
1112
1113 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001114 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001115 (!isa<InitListExpr>(IList->getInit(Index)) ||
1116 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001117 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001118 diag::err_flexible_array_init_nonempty)
1119 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001120 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001121 << *Field;
1122 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001123 ++Index;
1124 return;
1125 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001126 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001127 diag::ext_flexible_array_init)
1128 << IList->getInit(Index)->getSourceRange().getBegin();
1129 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1130 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001131 }
1132
Anders Carlsson6cabf312010-01-23 23:23:01 +00001133 InitializedEntity MemberEntity =
1134 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001135
Anders Carlsson6cabf312010-01-23 23:23:01 +00001136 if (isa<InitListExpr>(IList->getInit(Index)))
1137 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1138 StructuredList, StructuredIndex);
1139 else
1140 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001141 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001142}
Steve Narofff8ecff22008-05-01 22:18:59 +00001143
Douglas Gregord5846a12009-04-15 06:41:24 +00001144/// \brief Expand a field designator that refers to a member of an
1145/// anonymous struct or union into a series of field designators that
1146/// refers to the field within the appropriate subobject.
1147///
1148/// Field/FieldIndex will be updated to point to the (new)
1149/// currently-designated field.
1150static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001151 DesignatedInitExpr *DIE,
1152 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001153 FieldDecl *Field,
1154 RecordDecl::field_iterator &FieldIter,
1155 unsigned &FieldIndex) {
1156 typedef DesignatedInitExpr::Designator Designator;
1157
1158 // Build the path from the current object to the member of the
1159 // anonymous struct/union (backwards).
1160 llvm::SmallVector<FieldDecl *, 4> Path;
1161 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001162
Douglas Gregord5846a12009-04-15 06:41:24 +00001163 // Build the replacement designators.
1164 llvm::SmallVector<Designator, 4> Replacements;
1165 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1166 FI = Path.rbegin(), FIEnd = Path.rend();
1167 FI != FIEnd; ++FI) {
1168 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001169 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001170 DIE->getDesignator(DesigIdx)->getDotLoc(),
1171 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1172 else
1173 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1174 SourceLocation()));
1175 Replacements.back().setField(*FI);
1176 }
1177
1178 // Expand the current designator into the set of replacement
1179 // designators, so we have a full subobject path down to where the
1180 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001181 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001182 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001183
Douglas Gregord5846a12009-04-15 06:41:24 +00001184 // Update FieldIter/FieldIndex;
1185 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001186 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001187 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001188 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001189 FieldIter != FEnd; ++FieldIter) {
1190 if (FieldIter->isUnnamedBitfield())
1191 continue;
1192
1193 if (*FieldIter == Path.back())
1194 return;
1195
1196 ++FieldIndex;
1197 }
1198
1199 assert(false && "Unable to find anonymous struct/union field");
1200}
1201
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001202/// @brief Check the well-formedness of a C99 designated initializer.
1203///
1204/// Determines whether the designated initializer @p DIE, which
1205/// resides at the given @p Index within the initializer list @p
1206/// IList, is well-formed for a current object of type @p DeclType
1207/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001208/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001209/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001210///
1211/// @param IList The initializer list in which this designated
1212/// initializer occurs.
1213///
Douglas Gregora5324162009-04-15 04:56:10 +00001214/// @param DIE The designated initializer expression.
1215///
1216/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001217///
1218/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1219/// into which the designation in @p DIE should refer.
1220///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001221/// @param NextField If non-NULL and the first designator in @p DIE is
1222/// a field, this will be set to the field declaration corresponding
1223/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001224///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001225/// @param NextElementIndex If non-NULL and the first designator in @p
1226/// DIE is an array designator or GNU array-range designator, this
1227/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001228///
1229/// @param Index Index into @p IList where the designated initializer
1230/// @p DIE occurs.
1231///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001232/// @param StructuredList The initializer list expression that
1233/// describes all of the subobject initializers in the order they'll
1234/// actually be initialized.
1235///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001236/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001237bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001238InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001239 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001240 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001241 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001242 QualType &CurrentObjectType,
1243 RecordDecl::field_iterator *NextField,
1244 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001245 unsigned &Index,
1246 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001247 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001248 bool FinishSubobjectInit,
1249 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001250 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001251 // Check the actual initialization for the designated object type.
1252 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001253
1254 // Temporarily remove the designator expression from the
1255 // initializer list that the child calls see, so that we don't try
1256 // to re-process the designator.
1257 unsigned OldIndex = Index;
1258 IList->setInit(OldIndex, DIE->getInit());
1259
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001260 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001261 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001262
1263 // Restore the designated initializer expression in the syntactic
1264 // form of the initializer list.
1265 if (IList->getInit(OldIndex) != DIE->getInit())
1266 DIE->setInit(IList->getInit(OldIndex));
1267 IList->setInit(OldIndex, DIE);
1268
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001269 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001270 }
1271
Douglas Gregora5324162009-04-15 04:56:10 +00001272 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001273 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001274 "Need a non-designated initializer list to start from");
1275
Douglas Gregora5324162009-04-15 04:56:10 +00001276 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001277 // Determine the structural initializer list that corresponds to the
1278 // current subobject.
1279 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001280 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001281 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001282 SourceRange(D->getStartLocation(),
1283 DIE->getSourceRange().getEnd()));
1284 assert(StructuredList && "Expected a structured initializer list");
1285
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001286 if (D->isFieldDesignator()) {
1287 // C99 6.7.8p7:
1288 //
1289 // If a designator has the form
1290 //
1291 // . identifier
1292 //
1293 // then the current object (defined below) shall have
1294 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001295 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001296 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001297 if (!RT) {
1298 SourceLocation Loc = D->getDotLoc();
1299 if (Loc.isInvalid())
1300 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001301 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1302 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001303 ++Index;
1304 return true;
1305 }
1306
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001307 // Note: we perform a linear search of the fields here, despite
1308 // the fact that we have a faster lookup method, because we always
1309 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001310 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001311 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001312 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001313 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001314 Field = RT->getDecl()->field_begin(),
1315 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001316 for (; Field != FieldEnd; ++Field) {
1317 if (Field->isUnnamedBitfield())
1318 continue;
1319
Douglas Gregord5846a12009-04-15 06:41:24 +00001320 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001321 break;
1322
1323 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001324 }
1325
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001326 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001327 // There was no normal field in the struct with the designated
1328 // name. Perform another lookup for this name, which may find
1329 // something that we can't designate (e.g., a member function),
1330 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001331 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001332 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001333 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001334 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001335 // Name lookup didn't find anything. Determine whether this
1336 // was a typo for another field name.
1337 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1338 Sema::LookupMemberName);
1339 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1340 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1341 ReplacementField->getDeclContext()->getLookupContext()
1342 ->Equals(RT->getDecl())) {
1343 SemaRef.Diag(D->getFieldLoc(),
1344 diag::err_field_designator_unknown_suggest)
1345 << FieldName << CurrentObjectType << R.getLookupName()
1346 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1347 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001348 SemaRef.Diag(ReplacementField->getLocation(),
1349 diag::note_previous_decl)
1350 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001351 } else {
1352 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1353 << FieldName << CurrentObjectType;
1354 ++Index;
1355 return true;
1356 }
1357 } else if (!KnownField) {
1358 // Determine whether we found a field at all.
1359 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1360 }
1361
1362 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001363 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001364 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001365 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001366 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001368 ++Index;
1369 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001370 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001371
1372 if (!KnownField &&
1373 cast<RecordDecl>((ReplacementField)->getDeclContext())
1374 ->isAnonymousStructOrUnion()) {
1375 // Handle an field designator that refers to a member of an
1376 // anonymous struct or union.
1377 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1378 ReplacementField,
1379 Field, FieldIndex);
1380 D = DIE->getDesignator(DesigIdx);
1381 } else if (!KnownField) {
1382 // The replacement field comes from typo correction; find it
1383 // in the list of fields.
1384 FieldIndex = 0;
1385 Field = RT->getDecl()->field_begin();
1386 for (; Field != FieldEnd; ++Field) {
1387 if (Field->isUnnamedBitfield())
1388 continue;
1389
1390 if (ReplacementField == *Field ||
1391 Field->getIdentifier() == ReplacementField->getIdentifier())
1392 break;
1393
1394 ++FieldIndex;
1395 }
1396 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001397 } else if (!KnownField &&
1398 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001399 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001400 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1401 Field, FieldIndex);
1402 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001403 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001404
1405 // All of the fields of a union are located at the same place in
1406 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001407 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001408 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001409 StructuredList->setInitializedFieldInUnion(*Field);
1410 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001411
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001412 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001413 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001414
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001415 // Make sure that our non-designated initializer list has space
1416 // for a subobject corresponding to this field.
1417 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001418 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001419
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001420 // This designator names a flexible array member.
1421 if (Field->getType()->isIncompleteArrayType()) {
1422 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001423 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001424 // We can't designate an object within the flexible array
1425 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001426 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001427 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001428 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001429 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001430 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001431 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001432 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001433 << *Field;
1434 Invalid = true;
1435 }
1436
1437 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1438 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001439 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001440 diag::err_flexible_array_init_needs_braces)
1441 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001442 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001443 << *Field;
1444 Invalid = true;
1445 }
1446
1447 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001448 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001449 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001450 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001451 diag::err_flexible_array_init_nonempty)
1452 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001453 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001454 << *Field;
1455 Invalid = true;
1456 }
1457
1458 if (Invalid) {
1459 ++Index;
1460 return true;
1461 }
1462
1463 // Initialize the array.
1464 bool prevHadError = hadError;
1465 unsigned newStructuredIndex = FieldIndex;
1466 unsigned OldIndex = Index;
1467 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001468
1469 InitializedEntity MemberEntity =
1470 InitializedEntity::InitializeMember(*Field, &Entity);
1471 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001472 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001473
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001474 IList->setInit(OldIndex, DIE);
1475 if (hadError && !prevHadError) {
1476 ++Field;
1477 ++FieldIndex;
1478 if (NextField)
1479 *NextField = Field;
1480 StructuredIndex = FieldIndex;
1481 return true;
1482 }
1483 } else {
1484 // Recurse to check later designated subobjects.
1485 QualType FieldType = (*Field)->getType();
1486 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001487
1488 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001489 InitializedEntity::InitializeMember(*Field, &Entity);
1490 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001491 FieldType, 0, 0, Index,
1492 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001493 true, false))
1494 return true;
1495 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001496
1497 // Find the position of the next field to be initialized in this
1498 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001499 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001500 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001501
1502 // If this the first designator, our caller will continue checking
1503 // the rest of this struct/class/union subobject.
1504 if (IsFirstDesignator) {
1505 if (NextField)
1506 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001507 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001508 return false;
1509 }
1510
Douglas Gregor17bd0942009-01-28 23:36:17 +00001511 if (!FinishSubobjectInit)
1512 return false;
1513
Douglas Gregord5846a12009-04-15 06:41:24 +00001514 // We've already initialized something in the union; we're done.
1515 if (RT->getDecl()->isUnion())
1516 return hadError;
1517
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001518 // Check the remaining fields within this class/struct/union subobject.
1519 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001520
Anders Carlsson6cabf312010-01-23 23:23:01 +00001521 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001522 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001523 return hadError && !prevHadError;
1524 }
1525
1526 // C99 6.7.8p6:
1527 //
1528 // If a designator has the form
1529 //
1530 // [ constant-expression ]
1531 //
1532 // then the current object (defined below) shall have array
1533 // type and the expression shall be an integer constant
1534 // expression. If the array is of unknown size, any
1535 // nonnegative value is valid.
1536 //
1537 // Additionally, cope with the GNU extension that permits
1538 // designators of the form
1539 //
1540 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001541 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001542 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001543 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001544 << CurrentObjectType;
1545 ++Index;
1546 return true;
1547 }
1548
1549 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001550 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1551 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001552 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001553 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001554 DesignatedEndIndex = DesignatedStartIndex;
1555 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001556 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001557
Mike Stump11289f42009-09-09 15:08:12 +00001558
1559 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001560 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001561 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001562 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001563 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001564
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001565 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001566 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001567 }
1568
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001569 if (isa<ConstantArrayType>(AT)) {
1570 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001571 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1572 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1573 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1574 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1575 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001576 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001577 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001578 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001579 << IndexExpr->getSourceRange();
1580 ++Index;
1581 return true;
1582 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001583 } else {
1584 // Make sure the bit-widths and signedness match.
1585 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1586 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001587 else if (DesignatedStartIndex.getBitWidth() <
1588 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001589 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1590 DesignatedStartIndex.setIsUnsigned(true);
1591 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001592 }
Mike Stump11289f42009-09-09 15:08:12 +00001593
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001594 // Make sure that our non-designated initializer list has space
1595 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001596 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001597 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001598 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001599
Douglas Gregor17bd0942009-01-28 23:36:17 +00001600 // Repeatedly perform subobject initializations in the range
1601 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001602
Douglas Gregor17bd0942009-01-28 23:36:17 +00001603 // Move to the next designator
1604 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1605 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001606
1607 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001608 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001609
Douglas Gregor17bd0942009-01-28 23:36:17 +00001610 while (DesignatedStartIndex <= DesignatedEndIndex) {
1611 // Recurse to check later designated subobjects.
1612 QualType ElementType = AT->getElementType();
1613 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001614
1615 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001616 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001617 ElementType, 0, 0, Index,
1618 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001619 (DesignatedStartIndex == DesignatedEndIndex),
1620 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001621 return true;
1622
1623 // Move to the next index in the array that we'll be initializing.
1624 ++DesignatedStartIndex;
1625 ElementIndex = DesignatedStartIndex.getZExtValue();
1626 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001627
1628 // If this the first designator, our caller will continue checking
1629 // the rest of this array subobject.
1630 if (IsFirstDesignator) {
1631 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001632 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001633 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001634 return false;
1635 }
Mike Stump11289f42009-09-09 15:08:12 +00001636
Douglas Gregor17bd0942009-01-28 23:36:17 +00001637 if (!FinishSubobjectInit)
1638 return false;
1639
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001640 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001641 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001642 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001643 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001644 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001645 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001646}
1647
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001648// Get the structured initializer list for a subobject of type
1649// @p CurrentObjectType.
1650InitListExpr *
1651InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1652 QualType CurrentObjectType,
1653 InitListExpr *StructuredList,
1654 unsigned StructuredIndex,
1655 SourceRange InitRange) {
1656 Expr *ExistingInit = 0;
1657 if (!StructuredList)
1658 ExistingInit = SyntacticToSemantic[IList];
1659 else if (StructuredIndex < StructuredList->getNumInits())
1660 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001661
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001662 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1663 return Result;
1664
1665 if (ExistingInit) {
1666 // We are creating an initializer list that initializes the
1667 // subobjects of the current object, but there was already an
1668 // initialization that completely initialized the current
1669 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001670 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001671 // struct X { int a, b; };
1672 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001673 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001674 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1675 // designated initializer re-initializes the whole
1676 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001677 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001678 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001679 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001680 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001681 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001682 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001683 << ExistingInit->getSourceRange();
1684 }
1685
Mike Stump11289f42009-09-09 15:08:12 +00001686 InitListExpr *Result
Ted Kremenek013041e2010-02-19 01:50:18 +00001687 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1688 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001689
Douglas Gregor34c0a902010-02-09 00:50:06 +00001690 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691
Douglas Gregor6d00c992009-03-20 23:58:33 +00001692 // Pre-allocate storage for the structured initializer list.
1693 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001694 unsigned NumInits = 0;
1695 if (!StructuredList)
1696 NumInits = IList->getNumInits();
1697 else if (Index < IList->getNumInits()) {
1698 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1699 NumInits = SubList->getNumInits();
1700 }
1701
Mike Stump11289f42009-09-09 15:08:12 +00001702 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001703 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1704 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1705 NumElements = CAType->getSize().getZExtValue();
1706 // Simple heuristic so that we don't allocate a very large
1707 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001708 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001709 NumElements = 0;
1710 }
John McCall9dd450b2009-09-21 23:43:11 +00001711 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001712 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001713 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001714 RecordDecl *RDecl = RType->getDecl();
1715 if (RDecl->isUnion())
1716 NumElements = 1;
1717 else
Mike Stump11289f42009-09-09 15:08:12 +00001718 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001719 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001720 }
1721
Douglas Gregor221c9a52009-03-21 18:13:52 +00001722 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001723 NumElements = IList->getNumInits();
1724
Ted Kremenek013041e2010-02-19 01:50:18 +00001725 Result->reserveInits(NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001726
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001727 // Link this new initializer list into the structured initializer
1728 // lists.
1729 if (StructuredList)
Ted Kremenek013041e2010-02-19 01:50:18 +00001730 StructuredList->updateInit(StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001731 else {
1732 Result->setSyntacticForm(IList);
1733 SyntacticToSemantic[IList] = Result;
1734 }
1735
1736 return Result;
1737}
1738
1739/// Update the initializer at index @p StructuredIndex within the
1740/// structured initializer list to the value @p expr.
1741void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1742 unsigned &StructuredIndex,
1743 Expr *expr) {
1744 // No structured initializer list to update
1745 if (!StructuredList)
1746 return;
1747
Ted Kremenek013041e2010-02-19 01:50:18 +00001748 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001749 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001750 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001751 diag::warn_initializer_overrides)
1752 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001753 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001754 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001755 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001756 << PrevInit->getSourceRange();
1757 }
Mike Stump11289f42009-09-09 15:08:12 +00001758
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001759 ++StructuredIndex;
1760}
1761
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001762/// Check that the given Index expression is a valid array designator
1763/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001764/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001765/// and produces a reasonable diagnostic if there is a
1766/// failure. Returns true if there was an error, false otherwise. If
1767/// everything went okay, Value will receive the value of the constant
1768/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001769static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001770CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001771 SourceLocation Loc = Index->getSourceRange().getBegin();
1772
1773 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001774 if (S.VerifyIntegerConstantExpression(Index, &Value))
1775 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001776
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001777 if (Value.isSigned() && Value.isNegative())
1778 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001779 << Value.toString(10) << Index->getSourceRange();
1780
Douglas Gregor51650d32009-01-23 21:04:18 +00001781 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001782 return false;
1783}
1784
1785Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1786 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001787 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001788 OwningExprResult Init) {
1789 typedef DesignatedInitExpr::Designator ASTDesignator;
1790
1791 bool Invalid = false;
1792 llvm::SmallVector<ASTDesignator, 32> Designators;
1793 llvm::SmallVector<Expr *, 32> InitExpressions;
1794
1795 // Build designators and check array designator expressions.
1796 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1797 const Designator &D = Desig.getDesignator(Idx);
1798 switch (D.getKind()) {
1799 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001800 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001801 D.getFieldLoc()));
1802 break;
1803
1804 case Designator::ArrayDesignator: {
1805 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1806 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001807 if (!Index->isTypeDependent() &&
1808 !Index->isValueDependent() &&
1809 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001810 Invalid = true;
1811 else {
1812 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001813 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001814 D.getRBracketLoc()));
1815 InitExpressions.push_back(Index);
1816 }
1817 break;
1818 }
1819
1820 case Designator::ArrayRangeDesignator: {
1821 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1822 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1823 llvm::APSInt StartValue;
1824 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001825 bool StartDependent = StartIndex->isTypeDependent() ||
1826 StartIndex->isValueDependent();
1827 bool EndDependent = EndIndex->isTypeDependent() ||
1828 EndIndex->isValueDependent();
1829 if ((!StartDependent &&
1830 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1831 (!EndDependent &&
1832 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001833 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001834 else {
1835 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001836 if (StartDependent || EndDependent) {
1837 // Nothing to compute.
1838 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001839 EndValue.extend(StartValue.getBitWidth());
1840 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1841 StartValue.extend(EndValue.getBitWidth());
1842
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001843 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001844 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001845 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001846 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1847 Invalid = true;
1848 } else {
1849 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001850 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001851 D.getEllipsisLoc(),
1852 D.getRBracketLoc()));
1853 InitExpressions.push_back(StartIndex);
1854 InitExpressions.push_back(EndIndex);
1855 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001856 }
1857 break;
1858 }
1859 }
1860 }
1861
1862 if (Invalid || Init.isInvalid())
1863 return ExprError();
1864
1865 // Clear out the expressions within the designation.
1866 Desig.ClearExprs(*this);
1867
1868 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001869 = DesignatedInitExpr::Create(Context,
1870 Designators.data(), Designators.size(),
1871 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001872 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001873 return Owned(DIE);
1874}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001875
Douglas Gregor723796a2009-12-16 06:35:08 +00001876bool Sema::CheckInitList(const InitializedEntity &Entity,
1877 InitListExpr *&InitList, QualType &DeclType) {
1878 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001879 if (!CheckInitList.HadError())
1880 InitList = CheckInitList.getFullyStructuredList();
1881
1882 return CheckInitList.HadError();
1883}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001884
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001885//===----------------------------------------------------------------------===//
1886// Initialization entity
1887//===----------------------------------------------------------------------===//
1888
Douglas Gregor723796a2009-12-16 06:35:08 +00001889InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1890 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001891 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001892{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001893 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1894 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001895 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001896 } else {
1897 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001898 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001899 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001900}
1901
1902InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1903 CXXBaseSpecifier *Base)
1904{
1905 InitializedEntity Result;
1906 Result.Kind = EK_Base;
1907 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001908 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001909 return Result;
1910}
1911
Douglas Gregor85dabae2009-12-16 01:38:02 +00001912DeclarationName InitializedEntity::getName() const {
1913 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001914 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001915 if (!VariableOrMember)
1916 return DeclarationName();
1917 // Fall through
1918
1919 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001920 case EK_Member:
1921 return VariableOrMember->getDeclName();
1922
1923 case EK_Result:
1924 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001925 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001926 case EK_Temporary:
1927 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001928 case EK_ArrayElement:
1929 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001930 return DeclarationName();
1931 }
1932
1933 // Silence GCC warning
1934 return DeclarationName();
1935}
1936
Douglas Gregora4b592a2009-12-19 03:01:41 +00001937DeclaratorDecl *InitializedEntity::getDecl() const {
1938 switch (getKind()) {
1939 case EK_Variable:
1940 case EK_Parameter:
1941 case EK_Member:
1942 return VariableOrMember;
1943
1944 case EK_Result:
1945 case EK_Exception:
1946 case EK_New:
1947 case EK_Temporary:
1948 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001949 case EK_ArrayElement:
1950 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001951 return 0;
1952 }
1953
1954 // Silence GCC warning
1955 return 0;
1956}
1957
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001958//===----------------------------------------------------------------------===//
1959// Initialization sequence
1960//===----------------------------------------------------------------------===//
1961
1962void InitializationSequence::Step::Destroy() {
1963 switch (Kind) {
1964 case SK_ResolveAddressOfOverloadedFunction:
1965 case SK_CastDerivedToBaseRValue:
1966 case SK_CastDerivedToBaseLValue:
1967 case SK_BindReference:
1968 case SK_BindReferenceToTemporary:
1969 case SK_UserConversion:
1970 case SK_QualificationConversionRValue:
1971 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001972 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001973 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001974 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001975 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001976 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001977 break;
1978
1979 case SK_ConversionSequence:
1980 delete ICS;
1981 }
1982}
1983
1984void InitializationSequence::AddAddressOverloadResolutionStep(
1985 FunctionDecl *Function) {
1986 Step S;
1987 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1988 S.Type = Function->getType();
John McCall760af172010-02-01 03:16:54 +00001989 // Access is currently ignored for these.
1990 S.Function = DeclAccessPair::make(Function, AccessSpecifier(0));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001991 Steps.push_back(S);
1992}
1993
1994void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1995 bool IsLValue) {
1996 Step S;
1997 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1998 S.Type = BaseType;
1999 Steps.push_back(S);
2000}
2001
2002void InitializationSequence::AddReferenceBindingStep(QualType T,
2003 bool BindingTemporary) {
2004 Step S;
2005 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2006 S.Type = T;
2007 Steps.push_back(S);
2008}
2009
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002010void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall760af172010-02-01 03:16:54 +00002011 AccessSpecifier Access,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002012 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002013 Step S;
2014 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002015 S.Type = T;
John McCall760af172010-02-01 03:16:54 +00002016 S.Function = DeclAccessPair::make(Function, Access);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002017 Steps.push_back(S);
2018}
2019
2020void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2021 bool IsLValue) {
2022 Step S;
2023 S.Kind = IsLValue? SK_QualificationConversionLValue
2024 : SK_QualificationConversionRValue;
2025 S.Type = Ty;
2026 Steps.push_back(S);
2027}
2028
2029void InitializationSequence::AddConversionSequenceStep(
2030 const ImplicitConversionSequence &ICS,
2031 QualType T) {
2032 Step S;
2033 S.Kind = SK_ConversionSequence;
2034 S.Type = T;
2035 S.ICS = new ImplicitConversionSequence(ICS);
2036 Steps.push_back(S);
2037}
2038
Douglas Gregor51e77d52009-12-10 17:56:55 +00002039void InitializationSequence::AddListInitializationStep(QualType T) {
2040 Step S;
2041 S.Kind = SK_ListInitialization;
2042 S.Type = T;
2043 Steps.push_back(S);
2044}
2045
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002046void
2047InitializationSequence::AddConstructorInitializationStep(
2048 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002049 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002050 QualType T) {
2051 Step S;
2052 S.Kind = SK_ConstructorInitialization;
2053 S.Type = T;
John McCall760af172010-02-01 03:16:54 +00002054 S.Function = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002055 Steps.push_back(S);
2056}
2057
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002058void InitializationSequence::AddZeroInitializationStep(QualType T) {
2059 Step S;
2060 S.Kind = SK_ZeroInitialization;
2061 S.Type = T;
2062 Steps.push_back(S);
2063}
2064
Douglas Gregore1314a62009-12-18 05:02:21 +00002065void InitializationSequence::AddCAssignmentStep(QualType T) {
2066 Step S;
2067 S.Kind = SK_CAssignment;
2068 S.Type = T;
2069 Steps.push_back(S);
2070}
2071
Eli Friedman78275202009-12-19 08:11:05 +00002072void InitializationSequence::AddStringInitStep(QualType T) {
2073 Step S;
2074 S.Kind = SK_StringInit;
2075 S.Type = T;
2076 Steps.push_back(S);
2077}
2078
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002079void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2080 OverloadingResult Result) {
2081 SequenceKind = FailedSequence;
2082 this->Failure = Failure;
2083 this->FailedOverloadResult = Result;
2084}
2085
2086//===----------------------------------------------------------------------===//
2087// Attempt initialization
2088//===----------------------------------------------------------------------===//
2089
2090/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002091static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002092 const InitializedEntity &Entity,
2093 const InitializationKind &Kind,
2094 InitListExpr *InitList,
2095 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002096 // FIXME: We only perform rudimentary checking of list
2097 // initializations at this point, then assume that any list
2098 // initialization of an array, aggregate, or scalar will be
2099 // well-formed. We we actually "perform" list initialization, we'll
2100 // do all of the necessary checking. C++0x initializer lists will
2101 // force us to perform more checking here.
2102 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2103
Douglas Gregor1b303932009-12-22 15:35:07 +00002104 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002105
2106 // C++ [dcl.init]p13:
2107 // If T is a scalar type, then a declaration of the form
2108 //
2109 // T x = { a };
2110 //
2111 // is equivalent to
2112 //
2113 // T x = a;
2114 if (DestType->isScalarType()) {
2115 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2116 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2117 return;
2118 }
2119
2120 // Assume scalar initialization from a single value works.
2121 } else if (DestType->isAggregateType()) {
2122 // Assume aggregate initialization works.
2123 } else if (DestType->isVectorType()) {
2124 // Assume vector initialization works.
2125 } else if (DestType->isReferenceType()) {
2126 // FIXME: C++0x defines behavior for this.
2127 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2128 return;
2129 } else if (DestType->isRecordType()) {
2130 // FIXME: C++0x defines behavior for this
2131 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2132 }
2133
2134 // Add a general "list initialization" step.
2135 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002136}
2137
2138/// \brief Try a reference initialization that involves calling a conversion
2139/// function.
2140///
2141/// FIXME: look intos DRs 656, 896
2142static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2143 const InitializedEntity &Entity,
2144 const InitializationKind &Kind,
2145 Expr *Initializer,
2146 bool AllowRValues,
2147 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002148 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002149 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2150 QualType T1 = cv1T1.getUnqualifiedType();
2151 QualType cv2T2 = Initializer->getType();
2152 QualType T2 = cv2T2.getUnqualifiedType();
2153
2154 bool DerivedToBase;
2155 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2156 T1, T2, DerivedToBase) &&
2157 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002158 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002159
2160 // Build the candidate set directly in the initialization sequence
2161 // structure, so that it will persist if we fail.
2162 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2163 CandidateSet.clear();
2164
2165 // Determine whether we are allowed to call explicit constructors or
2166 // explicit conversion operators.
2167 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2168
2169 const RecordType *T1RecordType = 0;
2170 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2171 // The type we're converting to is a class type. Enumerate its constructors
2172 // to see if there is a suitable conversion.
2173 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2174
2175 DeclarationName ConstructorName
2176 = S.Context.DeclarationNames.getCXXConstructorName(
2177 S.Context.getCanonicalType(T1).getUnqualifiedType());
2178 DeclContext::lookup_iterator Con, ConEnd;
2179 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2180 Con != ConEnd; ++Con) {
2181 // Find the constructor (which may be a template).
2182 CXXConstructorDecl *Constructor = 0;
2183 FunctionTemplateDecl *ConstructorTmpl
2184 = dyn_cast<FunctionTemplateDecl>(*Con);
2185 if (ConstructorTmpl)
2186 Constructor = cast<CXXConstructorDecl>(
2187 ConstructorTmpl->getTemplatedDecl());
2188 else
2189 Constructor = cast<CXXConstructorDecl>(*Con);
2190
2191 if (!Constructor->isInvalidDecl() &&
2192 Constructor->isConvertingConstructor(AllowExplicit)) {
2193 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002194 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2195 ConstructorTmpl->getAccess(),
2196 /*ExplicitArgs*/ 0,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002197 &Initializer, 1, CandidateSet);
2198 else
John McCallb89836b2010-01-26 01:37:31 +00002199 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2200 &Initializer, 1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002201 }
2202 }
2203 }
2204
2205 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2206 // The type we're converting from is a class type, enumerate its conversion
2207 // functions.
2208 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2209
2210 // Determine the type we are converting to. If we are allowed to
2211 // convert to an rvalue, take the type that the destination type
2212 // refers to.
2213 QualType ToType = AllowRValues? cv1T1 : DestType;
2214
John McCallad371252010-01-20 00:46:10 +00002215 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002216 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002217 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2218 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002219 NamedDecl *D = *I;
2220 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2221 if (isa<UsingShadowDecl>(D))
2222 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2223
2224 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2225 CXXConversionDecl *Conv;
2226 if (ConvTemplate)
2227 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2228 else
2229 Conv = cast<CXXConversionDecl>(*I);
2230
2231 // If the conversion function doesn't return a reference type,
2232 // it can't be considered for this conversion unless we're allowed to
2233 // consider rvalues.
2234 // FIXME: Do we need to make sure that we only consider conversion
2235 // candidates with reference-compatible results? That might be needed to
2236 // break recursion.
2237 if ((AllowExplicit || !Conv->isExplicit()) &&
2238 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2239 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00002240 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2241 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002242 ToType, CandidateSet);
2243 else
John McCallb89836b2010-01-26 01:37:31 +00002244 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002245 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002246 }
2247 }
2248 }
2249
2250 SourceLocation DeclLoc = Initializer->getLocStart();
2251
2252 // Perform overload resolution. If it fails, return the failed result.
2253 OverloadCandidateSet::iterator Best;
2254 if (OverloadingResult Result
2255 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2256 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002257
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002258 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002259
2260 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002261 if (isa<CXXConversionDecl>(Function))
2262 T2 = Function->getResultType();
2263 else
2264 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002265
2266 // Add the user-defined conversion step.
John McCall760af172010-02-01 03:16:54 +00002267 Sequence.AddUserConversionStep(Function, Best->getAccess(),
2268 T2.getNonReferenceType());
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002269
2270 // Determine whether we need to perform derived-to-base or
2271 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002272 bool NewDerivedToBase = false;
2273 Sema::ReferenceCompareResult NewRefRelationship
2274 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2275 NewDerivedToBase);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002276 if (NewRefRelationship == Sema::Ref_Incompatible) {
2277 // If the type we've converted to is not reference-related to the
2278 // type we're looking for, then there is another conversion step
2279 // we need to perform to produce a temporary of the right type
2280 // that we'll be binding to.
2281 ImplicitConversionSequence ICS;
2282 ICS.setStandard();
2283 ICS.Standard = Best->FinalConversion;
2284 T2 = ICS.Standard.getToType(2);
2285 Sequence.AddConversionSequenceStep(ICS, T2);
2286 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002287 Sequence.AddDerivedToBaseCastStep(
2288 S.Context.getQualifiedType(T1,
2289 T2.getNonReferenceType().getQualifiers()),
2290 /*isLValue=*/true);
2291
2292 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2293 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2294
2295 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2296 return OR_Success;
2297}
2298
2299/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2300static void TryReferenceInitialization(Sema &S,
2301 const InitializedEntity &Entity,
2302 const InitializationKind &Kind,
2303 Expr *Initializer,
2304 InitializationSequence &Sequence) {
2305 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2306
Douglas Gregor1b303932009-12-22 15:35:07 +00002307 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002308 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002309 Qualifiers T1Quals;
2310 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002311 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002312 Qualifiers T2Quals;
2313 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002314 SourceLocation DeclLoc = Initializer->getLocStart();
2315
2316 // If the initializer is the address of an overloaded function, try
2317 // to resolve the overloaded function. If all goes well, T2 is the
2318 // type of the resulting function.
2319 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2320 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2321 T1,
2322 false);
2323 if (!Fn) {
2324 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2325 return;
2326 }
2327
2328 Sequence.AddAddressOverloadResolutionStep(Fn);
2329 cv2T2 = Fn->getType();
2330 T2 = cv2T2.getUnqualifiedType();
2331 }
2332
2333 // FIXME: Rvalue references
2334 bool ForceRValue = false;
2335
2336 // Compute some basic properties of the types and the initializer.
2337 bool isLValueRef = DestType->isLValueReferenceType();
2338 bool isRValueRef = !isLValueRef;
2339 bool DerivedToBase = false;
2340 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2341 Initializer->isLvalue(S.Context);
2342 Sema::ReferenceCompareResult RefRelationship
2343 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2344
2345 // C++0x [dcl.init.ref]p5:
2346 // A reference to type "cv1 T1" is initialized by an expression of type
2347 // "cv2 T2" as follows:
2348 //
2349 // - If the reference is an lvalue reference and the initializer
2350 // expression
2351 OverloadingResult ConvOvlResult = OR_Success;
2352 if (isLValueRef) {
2353 if (InitLvalue == Expr::LV_Valid &&
2354 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2355 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2356 // reference-compatible with "cv2 T2," or
2357 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002358 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002359 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002360 // can occur. However, we do pay attention to whether it is a bit-field
2361 // to decide whether we're actually binding to a temporary created from
2362 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002363 if (DerivedToBase)
2364 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002365 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002366 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002367 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002368 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002369 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002370 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002371 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002372 return;
2373 }
2374
2375 // - has a class type (i.e., T2 is a class type), where T1 is not
2376 // reference-related to T2, and can be implicitly converted to an
2377 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2378 // with "cv3 T3" (this conversion is selected by enumerating the
2379 // applicable conversion functions (13.3.1.6) and choosing the best
2380 // one through overload resolution (13.3)),
2381 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2382 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2383 Initializer,
2384 /*AllowRValues=*/false,
2385 Sequence);
2386 if (ConvOvlResult == OR_Success)
2387 return;
John McCall0d1da222010-01-12 00:44:57 +00002388 if (ConvOvlResult != OR_No_Viable_Function) {
2389 Sequence.SetOverloadFailure(
2390 InitializationSequence::FK_ReferenceInitOverloadFailed,
2391 ConvOvlResult);
2392 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002393 }
2394 }
2395
2396 // - Otherwise, the reference shall be an lvalue reference to a
2397 // non-volatile const type (i.e., cv1 shall be const), or the reference
2398 // shall be an rvalue reference and the initializer expression shall
2399 // be an rvalue.
Douglas Gregord1e08642010-01-29 19:39:15 +00002400 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002401 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2402 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2403 Sequence.SetOverloadFailure(
2404 InitializationSequence::FK_ReferenceInitOverloadFailed,
2405 ConvOvlResult);
2406 else if (isLValueRef)
2407 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2408 ? (RefRelationship == Sema::Ref_Related
2409 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2410 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2411 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2412 else
2413 Sequence.SetFailed(
2414 InitializationSequence::FK_RValueReferenceBindingToLValue);
2415
2416 return;
2417 }
2418
2419 // - If T1 and T2 are class types and
2420 if (T1->isRecordType() && T2->isRecordType()) {
2421 // - the initializer expression is an rvalue and "cv1 T1" is
2422 // reference-compatible with "cv2 T2", or
2423 if (InitLvalue != Expr::LV_Valid &&
2424 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2425 if (DerivedToBase)
2426 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002427 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002428 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002429 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002430 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2431 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2432 return;
2433 }
2434
2435 // - T1 is not reference-related to T2 and the initializer expression
2436 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2437 // conversion is selected by enumerating the applicable conversion
2438 // functions (13.3.1.6) and choosing the best one through overload
2439 // resolution (13.3)),
2440 if (RefRelationship == Sema::Ref_Incompatible) {
2441 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2442 Kind, Initializer,
2443 /*AllowRValues=*/true,
2444 Sequence);
2445 if (ConvOvlResult)
2446 Sequence.SetOverloadFailure(
2447 InitializationSequence::FK_ReferenceInitOverloadFailed,
2448 ConvOvlResult);
2449
2450 return;
2451 }
2452
2453 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2454 return;
2455 }
2456
2457 // - If the initializer expression is an rvalue, with T2 an array type,
2458 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2459 // is bound to the object represented by the rvalue (see 3.10).
2460 // FIXME: How can an array type be reference-compatible with anything?
2461 // Don't we mean the element types of T1 and T2?
2462
2463 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2464 // from the initializer expression using the rules for a non-reference
2465 // copy initialization (8.5). The reference is then bound to the
2466 // temporary. [...]
2467 // Determine whether we are allowed to call explicit constructors or
2468 // explicit conversion operators.
2469 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2470 ImplicitConversionSequence ICS
2471 = S.TryImplicitConversion(Initializer, cv1T1,
2472 /*SuppressUserConversions=*/false, AllowExplicit,
2473 /*ForceRValue=*/false,
2474 /*FIXME:InOverloadResolution=*/false,
2475 /*UserCast=*/Kind.isExplicitCast());
2476
John McCall0d1da222010-01-12 00:44:57 +00002477 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002478 // FIXME: Use the conversion function set stored in ICS to turn
2479 // this into an overloading ambiguity diagnostic. However, we need
2480 // to keep that set as an OverloadCandidateSet rather than as some
2481 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002482 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2483 Sequence.SetOverloadFailure(
2484 InitializationSequence::FK_ReferenceInitOverloadFailed,
2485 ConvOvlResult);
2486 else
2487 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 return;
2489 }
2490
2491 // [...] If T1 is reference-related to T2, cv1 must be the
2492 // same cv-qualification as, or greater cv-qualification
2493 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002494 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2495 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002496 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002497 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002498 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2499 return;
2500 }
2501
2502 // Perform the actual conversion.
2503 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2504 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2505 return;
2506}
2507
2508/// \brief Attempt character array initialization from a string literal
2509/// (C++ [dcl.init.string], C99 6.7.8).
2510static void TryStringLiteralInitialization(Sema &S,
2511 const InitializedEntity &Entity,
2512 const InitializationKind &Kind,
2513 Expr *Initializer,
2514 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002515 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002516 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002517}
2518
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002519/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2520/// enumerates the constructors of the initialized entity and performs overload
2521/// resolution to select the best.
2522static void TryConstructorInitialization(Sema &S,
2523 const InitializedEntity &Entity,
2524 const InitializationKind &Kind,
2525 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002526 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002527 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002528 if (Kind.getKind() == InitializationKind::IK_Copy)
2529 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2530 else
2531 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002532
2533 // Build the candidate set directly in the initialization sequence
2534 // structure, so that it will persist if we fail.
2535 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2536 CandidateSet.clear();
2537
2538 // Determine whether we are allowed to call explicit constructors or
2539 // explicit conversion operators.
2540 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2541 Kind.getKind() == InitializationKind::IK_Value ||
2542 Kind.getKind() == InitializationKind::IK_Default);
2543
2544 // The type we're converting to is a class type. Enumerate its constructors
2545 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002546 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2547 assert(DestRecordType && "Constructor initialization requires record type");
2548 CXXRecordDecl *DestRecordDecl
2549 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2550
2551 DeclarationName ConstructorName
2552 = S.Context.DeclarationNames.getCXXConstructorName(
2553 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2554 DeclContext::lookup_iterator Con, ConEnd;
2555 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2556 Con != ConEnd; ++Con) {
2557 // Find the constructor (which may be a template).
2558 CXXConstructorDecl *Constructor = 0;
2559 FunctionTemplateDecl *ConstructorTmpl
2560 = dyn_cast<FunctionTemplateDecl>(*Con);
2561 if (ConstructorTmpl)
2562 Constructor = cast<CXXConstructorDecl>(
2563 ConstructorTmpl->getTemplatedDecl());
2564 else
2565 Constructor = cast<CXXConstructorDecl>(*Con);
2566
2567 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002568 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002569 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002570 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2571 ConstructorTmpl->getAccess(),
2572 /*ExplicitArgs*/ 0,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002573 Args, NumArgs, CandidateSet);
2574 else
John McCallb89836b2010-01-26 01:37:31 +00002575 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2576 Args, NumArgs, CandidateSet);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002577 }
2578 }
2579
2580 SourceLocation DeclLoc = Kind.getLocation();
2581
2582 // Perform overload resolution. If it fails, return the failed result.
2583 OverloadCandidateSet::iterator Best;
2584 if (OverloadingResult Result
2585 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2586 Sequence.SetOverloadFailure(
2587 InitializationSequence::FK_ConstructorOverloadFailed,
2588 Result);
2589 return;
2590 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002591
2592 // C++0x [dcl.init]p6:
2593 // If a program calls for the default initialization of an object
2594 // of a const-qualified type T, T shall be a class type with a
2595 // user-provided default constructor.
2596 if (Kind.getKind() == InitializationKind::IK_Default &&
2597 Entity.getType().isConstQualified() &&
2598 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2599 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2600 return;
2601 }
2602
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002603 // Add the constructor initialization step. Any cv-qualification conversion is
2604 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002605 if (Kind.getKind() == InitializationKind::IK_Copy) {
John McCall760af172010-02-01 03:16:54 +00002606 Sequence.AddUserConversionStep(Best->Function, Best->getAccess(), DestType);
Douglas Gregore1314a62009-12-18 05:02:21 +00002607 } else {
2608 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002609 cast<CXXConstructorDecl>(Best->Function),
John McCall760af172010-02-01 03:16:54 +00002610 Best->getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002611 DestType);
2612 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002613}
2614
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002615/// \brief Attempt value initialization (C++ [dcl.init]p7).
2616static void TryValueInitialization(Sema &S,
2617 const InitializedEntity &Entity,
2618 const InitializationKind &Kind,
2619 InitializationSequence &Sequence) {
2620 // C++ [dcl.init]p5:
2621 //
2622 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002623 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002624
2625 // -- if T is an array type, then each element is value-initialized;
2626 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2627 T = AT->getElementType();
2628
2629 if (const RecordType *RT = T->getAs<RecordType>()) {
2630 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2631 // -- if T is a class type (clause 9) with a user-declared
2632 // constructor (12.1), then the default constructor for T is
2633 // called (and the initialization is ill-formed if T has no
2634 // accessible default constructor);
2635 //
2636 // FIXME: we really want to refer to a single subobject of the array,
2637 // but Entity doesn't have a way to capture that (yet).
2638 if (ClassDecl->hasUserDeclaredConstructor())
2639 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2640
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002641 // -- if T is a (possibly cv-qualified) non-union class type
2642 // without a user-provided constructor, then the object is
2643 // zero-initialized and, if T’s implicitly-declared default
2644 // constructor is non-trivial, that constructor is called.
2645 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2646 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2647 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002648 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002649 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2650 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002651 }
2652 }
2653
Douglas Gregor1b303932009-12-22 15:35:07 +00002654 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002655 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2656}
2657
Douglas Gregor85dabae2009-12-16 01:38:02 +00002658/// \brief Attempt default initialization (C++ [dcl.init]p6).
2659static void TryDefaultInitialization(Sema &S,
2660 const InitializedEntity &Entity,
2661 const InitializationKind &Kind,
2662 InitializationSequence &Sequence) {
2663 assert(Kind.getKind() == InitializationKind::IK_Default);
2664
2665 // C++ [dcl.init]p6:
2666 // To default-initialize an object of type T means:
2667 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002668 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002669 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2670 DestType = Array->getElementType();
2671
2672 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2673 // constructor for T is called (and the initialization is ill-formed if
2674 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002675 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00002676 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2677 Sequence);
2678 }
2679
2680 // - otherwise, no initialization is performed.
2681 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2682
2683 // If a program calls for the default initialization of an object of
2684 // a const-qualified type T, T shall be a class type with a user-provided
2685 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002686 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002687 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2688}
2689
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002690/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2691/// which enumerates all conversion functions and performs overload resolution
2692/// to select the best.
2693static void TryUserDefinedConversion(Sema &S,
2694 const InitializedEntity &Entity,
2695 const InitializationKind &Kind,
2696 Expr *Initializer,
2697 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002698 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2699
Douglas Gregor1b303932009-12-22 15:35:07 +00002700 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002701 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2702 QualType SourceType = Initializer->getType();
2703 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2704 "Must have a class type to perform a user-defined conversion");
2705
2706 // Build the candidate set directly in the initialization sequence
2707 // structure, so that it will persist if we fail.
2708 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2709 CandidateSet.clear();
2710
2711 // Determine whether we are allowed to call explicit constructors or
2712 // explicit conversion operators.
2713 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2714
2715 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2716 // The type we're converting to is a class type. Enumerate its constructors
2717 // to see if there is a suitable conversion.
2718 CXXRecordDecl *DestRecordDecl
2719 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2720
2721 DeclarationName ConstructorName
2722 = S.Context.DeclarationNames.getCXXConstructorName(
2723 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2724 DeclContext::lookup_iterator Con, ConEnd;
2725 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2726 Con != ConEnd; ++Con) {
2727 // Find the constructor (which may be a template).
2728 CXXConstructorDecl *Constructor = 0;
2729 FunctionTemplateDecl *ConstructorTmpl
2730 = dyn_cast<FunctionTemplateDecl>(*Con);
2731 if (ConstructorTmpl)
2732 Constructor = cast<CXXConstructorDecl>(
2733 ConstructorTmpl->getTemplatedDecl());
2734 else
2735 Constructor = cast<CXXConstructorDecl>(*Con);
2736
2737 if (!Constructor->isInvalidDecl() &&
2738 Constructor->isConvertingConstructor(AllowExplicit)) {
2739 if (ConstructorTmpl)
John McCallb89836b2010-01-26 01:37:31 +00002740 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2741 ConstructorTmpl->getAccess(),
2742 /*ExplicitArgs*/ 0,
Douglas Gregor540c3b02009-12-14 17:27:33 +00002743 &Initializer, 1, CandidateSet);
2744 else
John McCallb89836b2010-01-26 01:37:31 +00002745 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2746 &Initializer, 1, CandidateSet);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002747 }
2748 }
2749 }
Eli Friedman78275202009-12-19 08:11:05 +00002750
2751 SourceLocation DeclLoc = Initializer->getLocStart();
2752
Douglas Gregor540c3b02009-12-14 17:27:33 +00002753 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2754 // The type we're converting from is a class type, enumerate its conversion
2755 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002756
Eli Friedman4afe9a32009-12-20 22:12:03 +00002757 // We can only enumerate the conversion functions for a complete type; if
2758 // the type isn't complete, simply skip this step.
2759 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2760 CXXRecordDecl *SourceRecordDecl
2761 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002762
John McCallad371252010-01-20 00:46:10 +00002763 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002764 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002765 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002766 E = Conversions->end();
2767 I != E; ++I) {
2768 NamedDecl *D = *I;
2769 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2770 if (isa<UsingShadowDecl>(D))
2771 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2772
2773 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2774 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002775 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002776 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002777 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002778 Conv = cast<CXXConversionDecl>(*I);
2779
2780 if (AllowExplicit || !Conv->isExplicit()) {
2781 if (ConvTemplate)
John McCallb89836b2010-01-26 01:37:31 +00002782 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2783 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002784 CandidateSet);
2785 else
John McCallb89836b2010-01-26 01:37:31 +00002786 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2787 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002788 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002789 }
2790 }
2791 }
2792
Douglas Gregor540c3b02009-12-14 17:27:33 +00002793 // Perform overload resolution. If it fails, return the failed result.
2794 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002795 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002796 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2797 Sequence.SetOverloadFailure(
2798 InitializationSequence::FK_UserConversionOverloadFailed,
2799 Result);
2800 return;
2801 }
John McCall0d1da222010-01-12 00:44:57 +00002802
Douglas Gregor540c3b02009-12-14 17:27:33 +00002803 FunctionDecl *Function = Best->Function;
2804
2805 if (isa<CXXConstructorDecl>(Function)) {
2806 // Add the user-defined conversion step. Any cv-qualification conversion is
2807 // subsumed by the initialization.
John McCall760af172010-02-01 03:16:54 +00002808 Sequence.AddUserConversionStep(Function, Best->getAccess(), DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002809 return;
2810 }
2811
2812 // Add the user-defined conversion step that calls the conversion function.
2813 QualType ConvType = Function->getResultType().getNonReferenceType();
John McCall760af172010-02-01 03:16:54 +00002814 Sequence.AddUserConversionStep(Function, Best->getAccess(), ConvType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002815
2816 // If the conversion following the call to the conversion function is
2817 // interesting, add it as a separate step.
2818 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2819 Best->FinalConversion.Third) {
2820 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002821 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002822 ICS.Standard = Best->FinalConversion;
2823 Sequence.AddConversionSequenceStep(ICS, DestType);
2824 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002825}
2826
2827/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2828/// non-class type to another.
2829static void TryImplicitConversion(Sema &S,
2830 const InitializedEntity &Entity,
2831 const InitializationKind &Kind,
2832 Expr *Initializer,
2833 InitializationSequence &Sequence) {
2834 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002835 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002836 /*SuppressUserConversions=*/true,
2837 /*AllowExplicit=*/false,
2838 /*ForceRValue=*/false,
2839 /*FIXME:InOverloadResolution=*/false,
2840 /*UserCast=*/Kind.isExplicitCast());
2841
John McCall0d1da222010-01-12 00:44:57 +00002842 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002843 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2844 return;
2845 }
2846
Douglas Gregor1b303932009-12-22 15:35:07 +00002847 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002848}
2849
2850InitializationSequence::InitializationSequence(Sema &S,
2851 const InitializedEntity &Entity,
2852 const InitializationKind &Kind,
2853 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00002854 unsigned NumArgs)
2855 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002856 ASTContext &Context = S.Context;
2857
2858 // C++0x [dcl.init]p16:
2859 // The semantics of initializers are as follows. The destination type is
2860 // the type of the object or reference being initialized and the source
2861 // type is the type of the initializer expression. The source type is not
2862 // defined when the initializer is a braced-init-list or when it is a
2863 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002864 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002865
2866 if (DestType->isDependentType() ||
2867 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2868 SequenceKind = DependentSequence;
2869 return;
2870 }
2871
2872 QualType SourceType;
2873 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002874 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002875 Initializer = Args[0];
2876 if (!isa<InitListExpr>(Initializer))
2877 SourceType = Initializer->getType();
2878 }
2879
2880 // - If the initializer is a braced-init-list, the object is
2881 // list-initialized (8.5.4).
2882 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2883 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002884 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002885 }
2886
2887 // - If the destination type is a reference type, see 8.5.3.
2888 if (DestType->isReferenceType()) {
2889 // C++0x [dcl.init.ref]p1:
2890 // A variable declared to be a T& or T&&, that is, "reference to type T"
2891 // (8.3.2), shall be initialized by an object, or function, of type T or
2892 // by an object that can be converted into a T.
2893 // (Therefore, multiple arguments are not permitted.)
2894 if (NumArgs != 1)
2895 SetFailed(FK_TooManyInitsForReference);
2896 else
2897 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2898 return;
2899 }
2900
2901 // - If the destination type is an array of characters, an array of
2902 // char16_t, an array of char32_t, or an array of wchar_t, and the
2903 // initializer is a string literal, see 8.5.2.
2904 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2905 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2906 return;
2907 }
2908
2909 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002910 if (Kind.getKind() == InitializationKind::IK_Value ||
2911 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002912 TryValueInitialization(S, Entity, Kind, *this);
2913 return;
2914 }
2915
Douglas Gregor85dabae2009-12-16 01:38:02 +00002916 // Handle default initialization.
2917 if (Kind.getKind() == InitializationKind::IK_Default){
2918 TryDefaultInitialization(S, Entity, Kind, *this);
2919 return;
2920 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002922 // - Otherwise, if the destination type is an array, the program is
2923 // ill-formed.
2924 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2925 if (AT->getElementType()->isAnyCharacterType())
2926 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2927 else
2928 SetFailed(FK_ArrayNeedsInitList);
2929
2930 return;
2931 }
Eli Friedman78275202009-12-19 08:11:05 +00002932
2933 // Handle initialization in C
2934 if (!S.getLangOptions().CPlusPlus) {
2935 setSequenceKind(CAssignment);
2936 AddCAssignmentStep(DestType);
2937 return;
2938 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002939
2940 // - If the destination type is a (possibly cv-qualified) class type:
2941 if (DestType->isRecordType()) {
2942 // - If the initialization is direct-initialization, or if it is
2943 // copy-initialization where the cv-unqualified version of the
2944 // source type is the same class as, or a derived class of, the
2945 // class of the destination, constructors are considered. [...]
2946 if (Kind.getKind() == InitializationKind::IK_Direct ||
2947 (Kind.getKind() == InitializationKind::IK_Copy &&
2948 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2949 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002950 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002951 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002952 // - Otherwise (i.e., for the remaining copy-initialization cases),
2953 // user-defined conversion sequences that can convert from the source
2954 // type to the destination type or (when a conversion function is
2955 // used) to a derived class thereof are enumerated as described in
2956 // 13.3.1.4, and the best one is chosen through overload resolution
2957 // (13.3).
2958 else
2959 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2960 return;
2961 }
2962
Douglas Gregor85dabae2009-12-16 01:38:02 +00002963 if (NumArgs > 1) {
2964 SetFailed(FK_TooManyInitsForScalar);
2965 return;
2966 }
2967 assert(NumArgs == 1 && "Zero-argument case handled above");
2968
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002969 // - Otherwise, if the source type is a (possibly cv-qualified) class
2970 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002971 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002972 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2973 return;
2974 }
2975
2976 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002977 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002978 // conversions (Clause 4) will be used, if necessary, to convert the
2979 // initializer expression to the cv-unqualified version of the
2980 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002981 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002982 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2983}
2984
2985InitializationSequence::~InitializationSequence() {
2986 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2987 StepEnd = Steps.end();
2988 Step != StepEnd; ++Step)
2989 Step->Destroy();
2990}
2991
2992//===----------------------------------------------------------------------===//
2993// Perform initialization
2994//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002995static Sema::AssignmentAction
2996getAssignmentAction(const InitializedEntity &Entity) {
2997 switch(Entity.getKind()) {
2998 case InitializedEntity::EK_Variable:
2999 case InitializedEntity::EK_New:
3000 return Sema::AA_Initializing;
3001
3002 case InitializedEntity::EK_Parameter:
3003 // FIXME: Can we tell when we're sending vs. passing?
3004 return Sema::AA_Passing;
3005
3006 case InitializedEntity::EK_Result:
3007 return Sema::AA_Returning;
3008
3009 case InitializedEntity::EK_Exception:
3010 case InitializedEntity::EK_Base:
3011 llvm_unreachable("No assignment action for C++-specific initialization");
3012 break;
3013
3014 case InitializedEntity::EK_Temporary:
3015 // FIXME: Can we tell apart casting vs. converting?
3016 return Sema::AA_Casting;
3017
3018 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003019 case InitializedEntity::EK_ArrayElement:
3020 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003021 return Sema::AA_Initializing;
3022 }
3023
3024 return Sema::AA_Converting;
3025}
3026
3027static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3028 bool IsCopy) {
3029 switch (Entity.getKind()) {
3030 case InitializedEntity::EK_Result:
Anders Carlsson0bd52402010-01-24 00:19:41 +00003031 case InitializedEntity::EK_ArrayElement:
3032 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003033 return !IsCopy;
3034
3035 case InitializedEntity::EK_New:
3036 case InitializedEntity::EK_Variable:
3037 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003038 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003039 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003040 return false;
3041
3042 case InitializedEntity::EK_Parameter:
3043 case InitializedEntity::EK_Temporary:
3044 return true;
3045 }
3046
3047 llvm_unreachable("missed an InitializedEntity kind?");
3048}
3049
3050/// \brief If we need to perform an additional copy of the initialized object
3051/// for this kind of entity (e.g., the result of a function or an object being
3052/// thrown), make the copy.
3053static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3054 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003055 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003056 Sema::OwningExprResult CurInit) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003057 Expr *CurInitExpr = (Expr *)CurInit.get();
3058
Douglas Gregore1314a62009-12-18 05:02:21 +00003059 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003060
3061 switch (Entity.getKind()) {
3062 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003063 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003064 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003065 Loc = Entity.getReturnLoc();
3066 break;
3067
3068 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003069 Loc = Entity.getThrowLoc();
3070 break;
3071
3072 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003073 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003074 Kind.getKind() != InitializationKind::IK_Copy)
3075 return move(CurInit);
3076 Loc = Entity.getDecl()->getLocation();
3077 break;
3078
Anders Carlsson0bd52402010-01-24 00:19:41 +00003079 case InitializedEntity::EK_ArrayElement:
3080 case InitializedEntity::EK_Member:
3081 if (Entity.getType()->isReferenceType() ||
3082 Kind.getKind() != InitializationKind::IK_Copy)
3083 return move(CurInit);
3084 Loc = CurInitExpr->getLocStart();
3085 break;
3086
Douglas Gregore1314a62009-12-18 05:02:21 +00003087 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003088 // FIXME: Do we need this initialization for a parameter?
3089 return move(CurInit);
3090
Douglas Gregore1314a62009-12-18 05:02:21 +00003091 case InitializedEntity::EK_New:
3092 case InitializedEntity::EK_Temporary:
3093 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003094 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003095 // We don't need to copy for any of these initialized entities.
3096 return move(CurInit);
3097 }
3098
Douglas Gregore1314a62009-12-18 05:02:21 +00003099 CXXRecordDecl *Class = 0;
3100 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3101 Class = cast<CXXRecordDecl>(Record->getDecl());
3102 if (!Class)
3103 return move(CurInit);
3104
3105 // Perform overload resolution using the class's copy constructors.
3106 DeclarationName ConstructorName
3107 = S.Context.DeclarationNames.getCXXConstructorName(
3108 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3109 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003110 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003111 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3112 Con != ConEnd; ++Con) {
3113 // Find the constructor (which may be a template).
3114 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3115 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003116 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003117 continue;
3118
John McCallb89836b2010-01-26 01:37:31 +00003119 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
3120 &CurInitExpr, 1, CandidateSet);
Douglas Gregore1314a62009-12-18 05:02:21 +00003121 }
3122
3123 OverloadCandidateSet::iterator Best;
3124 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3125 case OR_Success:
3126 break;
3127
3128 case OR_No_Viable_Function:
3129 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003130 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003131 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003132 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3133 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003134 return S.ExprError();
3135
3136 case OR_Ambiguous:
3137 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003138 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003139 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003140 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3141 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003142 return S.ExprError();
3143
3144 case OR_Deleted:
3145 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003146 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003147 << CurInitExpr->getSourceRange();
3148 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3149 << Best->Function->isDeleted();
3150 return S.ExprError();
3151 }
3152
3153 CurInit.release();
3154 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3155 cast<CXXConstructorDecl>(Best->Function),
3156 /*Elidable=*/true,
3157 Sema::MultiExprArg(S,
3158 (void**)&CurInitExpr, 1));
3159}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003160
3161Action::OwningExprResult
3162InitializationSequence::Perform(Sema &S,
3163 const InitializedEntity &Entity,
3164 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003165 Action::MultiExprArg Args,
3166 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003167 if (SequenceKind == FailedSequence) {
3168 unsigned NumArgs = Args.size();
3169 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3170 return S.ExprError();
3171 }
3172
3173 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003174 // If the declaration is a non-dependent, incomplete array type
3175 // that has an initializer, then its type will be completed once
3176 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003177 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003178 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003179 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003180 if (const IncompleteArrayType *ArrayT
3181 = S.Context.getAsIncompleteArrayType(DeclType)) {
3182 // FIXME: We don't currently have the ability to accurately
3183 // compute the length of an initializer list without
3184 // performing full type-checking of the initializer list
3185 // (since we have to determine where braces are implicitly
3186 // introduced and such). So, we fall back to making the array
3187 // type a dependently-sized array type with no specified
3188 // bound.
3189 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3190 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003191
Douglas Gregor51e77d52009-12-10 17:56:55 +00003192 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003193 if (DeclaratorDecl *DD = Entity.getDecl()) {
3194 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3195 TypeLoc TL = TInfo->getTypeLoc();
3196 if (IncompleteArrayTypeLoc *ArrayLoc
3197 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3198 Brackets = ArrayLoc->getBracketsRange();
3199 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003200 }
3201
3202 *ResultType
3203 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3204 /*NumElts=*/0,
3205 ArrayT->getSizeModifier(),
3206 ArrayT->getIndexTypeCVRQualifiers(),
3207 Brackets);
3208 }
3209
3210 }
3211 }
3212
Eli Friedmana553d4a2009-12-22 02:35:53 +00003213 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003214 return Sema::OwningExprResult(S, Args.release()[0]);
3215
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003216 if (Args.size() == 0)
3217 return S.Owned((Expr *)0);
3218
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003219 unsigned NumArgs = Args.size();
3220 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3221 SourceLocation(),
3222 (Expr **)Args.release(),
3223 NumArgs,
3224 SourceLocation()));
3225 }
3226
Douglas Gregor85dabae2009-12-16 01:38:02 +00003227 if (SequenceKind == NoInitialization)
3228 return S.Owned((Expr *)0);
3229
Douglas Gregor1b303932009-12-22 15:35:07 +00003230 QualType DestType = Entity.getType().getNonReferenceType();
3231 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003232 // the same as Entity.getDecl()->getType() in cases involving type merging,
3233 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003234 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003235 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003236 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003237
Douglas Gregor85dabae2009-12-16 01:38:02 +00003238 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3239
3240 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3241
3242 // For initialization steps that start with a single initializer,
3243 // grab the only argument out the Args and place it into the "current"
3244 // initializer.
3245 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003246 case SK_ResolveAddressOfOverloadedFunction:
3247 case SK_CastDerivedToBaseRValue:
3248 case SK_CastDerivedToBaseLValue:
3249 case SK_BindReference:
3250 case SK_BindReferenceToTemporary:
3251 case SK_UserConversion:
3252 case SK_QualificationConversionLValue:
3253 case SK_QualificationConversionRValue:
3254 case SK_ConversionSequence:
3255 case SK_ListInitialization:
3256 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003257 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003258 assert(Args.size() == 1);
3259 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3260 if (CurInit.isInvalid())
3261 return S.ExprError();
3262 break;
3263
3264 case SK_ConstructorInitialization:
3265 case SK_ZeroInitialization:
3266 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 }
3268
3269 // Walk through the computed steps for the initialization sequence,
3270 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003271 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003272 for (step_iterator Step = step_begin(), StepEnd = step_end();
3273 Step != StepEnd; ++Step) {
3274 if (CurInit.isInvalid())
3275 return S.ExprError();
3276
3277 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003278 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003279
3280 switch (Step->Kind) {
3281 case SK_ResolveAddressOfOverloadedFunction:
3282 // Overload resolution determined which function invoke; update the
3283 // initializer to reflect that choice.
John McCall760af172010-02-01 03:16:54 +00003284 // Access control was done in overload resolution.
3285 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
3286 cast<FunctionDecl>(Step->Function.getDecl()));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003287 break;
3288
3289 case SK_CastDerivedToBaseRValue:
3290 case SK_CastDerivedToBaseLValue: {
3291 // We have a derived-to-base cast that produces either an rvalue or an
3292 // lvalue. Perform that cast.
3293
3294 // Casts to inaccessible base classes are allowed with C-style casts.
3295 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3296 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3297 CurInitExpr->getLocStart(),
3298 CurInitExpr->getSourceRange(),
3299 IgnoreBaseAccess))
3300 return S.ExprError();
3301
3302 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3303 CastExpr::CK_DerivedToBase,
3304 (Expr*)CurInit.release(),
3305 Step->Kind == SK_CastDerivedToBaseLValue));
3306 break;
3307 }
3308
3309 case SK_BindReference:
3310 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3311 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3312 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003313 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003314 << BitField->getDeclName()
3315 << CurInitExpr->getSourceRange();
3316 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3317 return S.ExprError();
3318 }
Anders Carlssona91be642010-01-29 02:47:33 +00003319
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003320 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003321 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003322 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3323 << Entity.getType().isVolatileQualified()
3324 << CurInitExpr->getSourceRange();
3325 return S.ExprError();
3326 }
3327
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003328 // Reference binding does not have any corresponding ASTs.
3329
3330 // Check exception specifications
3331 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3332 return S.ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003333
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003334 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003335
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003336 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003337 // Reference binding does not have any corresponding ASTs.
3338
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003339 // Check exception specifications
3340 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3341 return S.ExprError();
3342
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003343 break;
3344
3345 case SK_UserConversion: {
3346 // We have a user-defined conversion that invokes either a constructor
3347 // or a conversion function.
3348 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003349 bool IsCopy = false;
John McCall760af172010-02-01 03:16:54 +00003350 FunctionDecl *Fn = cast<FunctionDecl>(Step->Function.getDecl());
3351 AccessSpecifier FnAccess = Step->Function.getAccess();
3352 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003353 // Build a call to the selected constructor.
3354 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3355 SourceLocation Loc = CurInitExpr->getLocStart();
3356 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003357
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003358 // Determine the arguments required to actually perform the constructor
3359 // call.
3360 if (S.CompleteConstructorCall(Constructor,
3361 Sema::MultiExprArg(S,
3362 (void **)&CurInitExpr,
3363 1),
3364 Loc, ConstructorArgs))
3365 return S.ExprError();
3366
3367 // Build the an expression that constructs a temporary.
3368 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3369 move_arg(ConstructorArgs));
3370 if (CurInit.isInvalid())
3371 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003372
3373 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FnAccess);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003374
3375 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003376 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3377 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3378 S.IsDerivedFrom(SourceType, Class))
3379 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003380 } else {
3381 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003382 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregore1314a62009-12-18 05:02:21 +00003383
John McCall760af172010-02-01 03:16:54 +00003384 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr,
3385 Conversion, FnAccess);
3386
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003387 // FIXME: Should we move this initialization into a separate
3388 // derived-to-base conversion? I believe the answer is "no", because
3389 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003390 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
3391 Conversion))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003392 return S.ExprError();
3393
3394 // Do a little dance to make sure that CurInit has the proper
3395 // pointer.
3396 CurInit.release();
3397
3398 // Build the actual call to the conversion function.
3399 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3400 if (CurInit.isInvalid() || !CurInit.get())
3401 return S.ExprError();
3402
3403 CastKind = CastExpr::CK_UserDefinedConversion;
3404 }
3405
Douglas Gregore1314a62009-12-18 05:02:21 +00003406 if (shouldBindAsTemporary(Entity, IsCopy))
3407 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3408
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003409 CurInitExpr = CurInit.takeAs<Expr>();
3410 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3411 CastKind,
3412 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003413 false));
3414
3415 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003416 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003417 break;
3418 }
3419
3420 case SK_QualificationConversionLValue:
3421 case SK_QualificationConversionRValue:
3422 // Perform a qualification conversion; these can never go wrong.
3423 S.ImpCastExprToType(CurInitExpr, Step->Type,
3424 CastExpr::CK_NoOp,
3425 Step->Kind == SK_QualificationConversionLValue);
3426 CurInit.release();
3427 CurInit = S.Owned(CurInitExpr);
3428 break;
3429
3430 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003431 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003432 false, false, *Step->ICS))
3433 return S.ExprError();
3434
3435 CurInit.release();
3436 CurInit = S.Owned(CurInitExpr);
3437 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003438
3439 case SK_ListInitialization: {
3440 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3441 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003442 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003443 return S.ExprError();
3444
3445 CurInit.release();
3446 CurInit = S.Owned(InitList);
3447 break;
3448 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003449
3450 case SK_ConstructorInitialization: {
3451 CXXConstructorDecl *Constructor
John McCall760af172010-02-01 03:16:54 +00003452 = cast<CXXConstructorDecl>(Step->Function.getDecl());
3453
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003454 // Build a call to the selected constructor.
3455 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3456 SourceLocation Loc = Kind.getLocation();
3457
3458 // Determine the arguments required to actually perform the constructor
3459 // call.
3460 if (S.CompleteConstructorCall(Constructor, move(Args),
3461 Loc, ConstructorArgs))
3462 return S.ExprError();
3463
3464 // Build the an expression that constructs a temporary.
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003465 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
3466 (Kind.getKind() == InitializationKind::IK_Direct ||
3467 Kind.getKind() == InitializationKind::IK_Value)) {
3468 // An explicitly-constructed temporary, e.g., X(1, 2).
3469 unsigned NumExprs = ConstructorArgs.size();
3470 Expr **Exprs = (Expr **)ConstructorArgs.take();
3471 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3472 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3473 Constructor,
3474 Entity.getType(),
3475 Kind.getLocation(),
3476 Exprs,
3477 NumExprs,
3478 Kind.getParenRange().getEnd()));
3479 } else
3480 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3481 Constructor,
3482 move_arg(ConstructorArgs),
3483 ConstructorInitRequiresZeroInit,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003484 Entity.getKind() == InitializedEntity::EK_Base);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003485 if (CurInit.isInvalid())
3486 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003487
3488 // Only check access if all of that succeeded.
3489 S.CheckConstructorAccess(Loc, Constructor, Step->Function.getAccess());
Douglas Gregore1314a62009-12-18 05:02:21 +00003490
3491 bool Elidable
3492 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3493 if (shouldBindAsTemporary(Entity, Elidable))
3494 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3495
3496 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003497 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003498 break;
3499 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003500
3501 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003502 step_iterator NextStep = Step;
3503 ++NextStep;
3504 if (NextStep != StepEnd &&
3505 NextStep->Kind == SK_ConstructorInitialization) {
3506 // The need for zero-initialization is recorded directly into
3507 // the call to the object's constructor within the next step.
3508 ConstructorInitRequiresZeroInit = true;
3509 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3510 S.getLangOptions().CPlusPlus &&
3511 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003512 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3513 Kind.getRange().getBegin(),
3514 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003515 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003516 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003517 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003518 break;
3519 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003520
3521 case SK_CAssignment: {
3522 QualType SourceType = CurInitExpr->getType();
3523 Sema::AssignConvertType ConvTy =
3524 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003525
3526 // If this is a call, allow conversion to a transparent union.
3527 if (ConvTy != Sema::Compatible &&
3528 Entity.getKind() == InitializedEntity::EK_Parameter &&
3529 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3530 == Sema::Compatible)
3531 ConvTy = Sema::Compatible;
3532
Douglas Gregore1314a62009-12-18 05:02:21 +00003533 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3534 Step->Type, SourceType,
3535 CurInitExpr, getAssignmentAction(Entity)))
3536 return S.ExprError();
3537
3538 CurInit.release();
3539 CurInit = S.Owned(CurInitExpr);
3540 break;
3541 }
Eli Friedman78275202009-12-19 08:11:05 +00003542
3543 case SK_StringInit: {
3544 QualType Ty = Step->Type;
3545 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3546 break;
3547 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003548 }
3549 }
3550
3551 return move(CurInit);
3552}
3553
3554//===----------------------------------------------------------------------===//
3555// Diagnose initialization failures
3556//===----------------------------------------------------------------------===//
3557bool InitializationSequence::Diagnose(Sema &S,
3558 const InitializedEntity &Entity,
3559 const InitializationKind &Kind,
3560 Expr **Args, unsigned NumArgs) {
3561 if (SequenceKind != FailedSequence)
3562 return false;
3563
Douglas Gregor1b303932009-12-22 15:35:07 +00003564 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003565 switch (Failure) {
3566 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003567 // FIXME: Customize for the initialized entity?
3568 if (NumArgs == 0)
3569 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3570 << DestType.getNonReferenceType();
3571 else // FIXME: diagnostic below could be better!
3572 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3573 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003574 break;
3575
3576 case FK_ArrayNeedsInitList:
3577 case FK_ArrayNeedsInitListOrStringLiteral:
3578 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3579 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3580 break;
3581
3582 case FK_AddressOfOverloadFailed:
3583 S.ResolveAddressOfOverloadedFunction(Args[0],
3584 DestType.getNonReferenceType(),
3585 true);
3586 break;
3587
3588 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003589 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003590 switch (FailedOverloadResult) {
3591 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003592 if (Failure == FK_UserConversionOverloadFailed)
3593 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3594 << Args[0]->getType() << DestType
3595 << Args[0]->getSourceRange();
3596 else
3597 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3598 << DestType << Args[0]->getType()
3599 << Args[0]->getSourceRange();
3600
John McCallad907772010-01-12 07:18:19 +00003601 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3602 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003603 break;
3604
3605 case OR_No_Viable_Function:
3606 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3607 << Args[0]->getType() << DestType.getNonReferenceType()
3608 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003609 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3610 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003611 break;
3612
3613 case OR_Deleted: {
3614 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3615 << Args[0]->getType() << DestType.getNonReferenceType()
3616 << Args[0]->getSourceRange();
3617 OverloadCandidateSet::iterator Best;
3618 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3619 Kind.getLocation(),
3620 Best);
3621 if (Ovl == OR_Deleted) {
3622 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3623 << Best->Function->isDeleted();
3624 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003625 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003626 }
3627 break;
3628 }
3629
3630 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003631 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003632 break;
3633 }
3634 break;
3635
3636 case FK_NonConstLValueReferenceBindingToTemporary:
3637 case FK_NonConstLValueReferenceBindingToUnrelated:
3638 S.Diag(Kind.getLocation(),
3639 Failure == FK_NonConstLValueReferenceBindingToTemporary
3640 ? diag::err_lvalue_reference_bind_to_temporary
3641 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00003642 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003643 << DestType.getNonReferenceType()
3644 << Args[0]->getType()
3645 << Args[0]->getSourceRange();
3646 break;
3647
3648 case FK_RValueReferenceBindingToLValue:
3649 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3650 << Args[0]->getSourceRange();
3651 break;
3652
3653 case FK_ReferenceInitDropsQualifiers:
3654 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3655 << DestType.getNonReferenceType()
3656 << Args[0]->getType()
3657 << Args[0]->getSourceRange();
3658 break;
3659
3660 case FK_ReferenceInitFailed:
3661 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3662 << DestType.getNonReferenceType()
3663 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3664 << Args[0]->getType()
3665 << Args[0]->getSourceRange();
3666 break;
3667
3668 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003669 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3670 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003671 << DestType
3672 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3673 << Args[0]->getType()
3674 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003675 break;
3676
3677 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003678 SourceRange R;
3679
3680 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3681 R = SourceRange(InitList->getInit(1)->getLocStart(),
3682 InitList->getLocEnd());
3683 else
3684 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003685
3686 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003687 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003688 break;
3689 }
3690
3691 case FK_ReferenceBindingToInitList:
3692 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3693 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3694 break;
3695
3696 case FK_InitListBadDestinationType:
3697 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3698 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3699 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003700
3701 case FK_ConstructorOverloadFailed: {
3702 SourceRange ArgsRange;
3703 if (NumArgs)
3704 ArgsRange = SourceRange(Args[0]->getLocStart(),
3705 Args[NumArgs - 1]->getLocEnd());
3706
3707 // FIXME: Using "DestType" for the entity we're printing is probably
3708 // bad.
3709 switch (FailedOverloadResult) {
3710 case OR_Ambiguous:
3711 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3712 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003713 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003714 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003715 break;
3716
3717 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003718 if (Kind.getKind() == InitializationKind::IK_Default &&
3719 (Entity.getKind() == InitializedEntity::EK_Base ||
3720 Entity.getKind() == InitializedEntity::EK_Member) &&
3721 isa<CXXConstructorDecl>(S.CurContext)) {
3722 // This is implicit default initialization of a member or
3723 // base within a constructor. If no viable function was
3724 // found, notify the user that she needs to explicitly
3725 // initialize this base/member.
3726 CXXConstructorDecl *Constructor
3727 = cast<CXXConstructorDecl>(S.CurContext);
3728 if (Entity.getKind() == InitializedEntity::EK_Base) {
3729 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3730 << Constructor->isImplicit()
3731 << S.Context.getTypeDeclType(Constructor->getParent())
3732 << /*base=*/0
3733 << Entity.getType();
3734
3735 RecordDecl *BaseDecl
3736 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
3737 ->getDecl();
3738 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
3739 << S.Context.getTagDeclType(BaseDecl);
3740 } else {
3741 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3742 << Constructor->isImplicit()
3743 << S.Context.getTypeDeclType(Constructor->getParent())
3744 << /*member=*/1
3745 << Entity.getName();
3746 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
3747
3748 if (const RecordType *Record
3749 = Entity.getType()->getAs<RecordType>())
3750 S.Diag(Record->getDecl()->getLocation(),
3751 diag::note_previous_decl)
3752 << S.Context.getTagDeclType(Record->getDecl());
3753 }
3754 break;
3755 }
3756
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003757 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3758 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003759 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3760 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003761 break;
3762
3763 case OR_Deleted: {
3764 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3765 << true << DestType << ArgsRange;
3766 OverloadCandidateSet::iterator Best;
3767 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3768 Kind.getLocation(),
3769 Best);
3770 if (Ovl == OR_Deleted) {
3771 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3772 << Best->Function->isDeleted();
3773 } else {
3774 llvm_unreachable("Inconsistent overload resolution?");
3775 }
3776 break;
3777 }
3778
3779 case OR_Success:
3780 llvm_unreachable("Conversion did not fail!");
3781 break;
3782 }
3783 break;
3784 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003785
3786 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003787 if (Entity.getKind() == InitializedEntity::EK_Member &&
3788 isa<CXXConstructorDecl>(S.CurContext)) {
3789 // This is implicit default-initialization of a const member in
3790 // a constructor. Complain that it needs to be explicitly
3791 // initialized.
3792 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
3793 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
3794 << Constructor->isImplicit()
3795 << S.Context.getTypeDeclType(Constructor->getParent())
3796 << /*const=*/1
3797 << Entity.getName();
3798 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
3799 << Entity.getName();
3800 } else {
3801 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3802 << DestType << (bool)DestType->getAs<RecordType>();
3803 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003804 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003805 }
3806
3807 return true;
3808}
Douglas Gregore1314a62009-12-18 05:02:21 +00003809
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003810void InitializationSequence::dump(llvm::raw_ostream &OS) const {
3811 switch (SequenceKind) {
3812 case FailedSequence: {
3813 OS << "Failed sequence: ";
3814 switch (Failure) {
3815 case FK_TooManyInitsForReference:
3816 OS << "too many initializers for reference";
3817 break;
3818
3819 case FK_ArrayNeedsInitList:
3820 OS << "array requires initializer list";
3821 break;
3822
3823 case FK_ArrayNeedsInitListOrStringLiteral:
3824 OS << "array requires initializer list or string literal";
3825 break;
3826
3827 case FK_AddressOfOverloadFailed:
3828 OS << "address of overloaded function failed";
3829 break;
3830
3831 case FK_ReferenceInitOverloadFailed:
3832 OS << "overload resolution for reference initialization failed";
3833 break;
3834
3835 case FK_NonConstLValueReferenceBindingToTemporary:
3836 OS << "non-const lvalue reference bound to temporary";
3837 break;
3838
3839 case FK_NonConstLValueReferenceBindingToUnrelated:
3840 OS << "non-const lvalue reference bound to unrelated type";
3841 break;
3842
3843 case FK_RValueReferenceBindingToLValue:
3844 OS << "rvalue reference bound to an lvalue";
3845 break;
3846
3847 case FK_ReferenceInitDropsQualifiers:
3848 OS << "reference initialization drops qualifiers";
3849 break;
3850
3851 case FK_ReferenceInitFailed:
3852 OS << "reference initialization failed";
3853 break;
3854
3855 case FK_ConversionFailed:
3856 OS << "conversion failed";
3857 break;
3858
3859 case FK_TooManyInitsForScalar:
3860 OS << "too many initializers for scalar";
3861 break;
3862
3863 case FK_ReferenceBindingToInitList:
3864 OS << "referencing binding to initializer list";
3865 break;
3866
3867 case FK_InitListBadDestinationType:
3868 OS << "initializer list for non-aggregate, non-scalar type";
3869 break;
3870
3871 case FK_UserConversionOverloadFailed:
3872 OS << "overloading failed for user-defined conversion";
3873 break;
3874
3875 case FK_ConstructorOverloadFailed:
3876 OS << "constructor overloading failed";
3877 break;
3878
3879 case FK_DefaultInitOfConst:
3880 OS << "default initialization of a const variable";
3881 break;
3882 }
3883 OS << '\n';
3884 return;
3885 }
3886
3887 case DependentSequence:
3888 OS << "Dependent sequence: ";
3889 return;
3890
3891 case UserDefinedConversion:
3892 OS << "User-defined conversion sequence: ";
3893 break;
3894
3895 case ConstructorInitialization:
3896 OS << "Constructor initialization sequence: ";
3897 break;
3898
3899 case ReferenceBinding:
3900 OS << "Reference binding: ";
3901 break;
3902
3903 case ListInitialization:
3904 OS << "List initialization: ";
3905 break;
3906
3907 case ZeroInitialization:
3908 OS << "Zero initialization\n";
3909 return;
3910
3911 case NoInitialization:
3912 OS << "No initialization\n";
3913 return;
3914
3915 case StandardConversion:
3916 OS << "Standard conversion: ";
3917 break;
3918
3919 case CAssignment:
3920 OS << "C assignment: ";
3921 break;
3922
3923 case StringInit:
3924 OS << "String initialization: ";
3925 break;
3926 }
3927
3928 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
3929 if (S != step_begin()) {
3930 OS << " -> ";
3931 }
3932
3933 switch (S->Kind) {
3934 case SK_ResolveAddressOfOverloadedFunction:
3935 OS << "resolve address of overloaded function";
3936 break;
3937
3938 case SK_CastDerivedToBaseRValue:
3939 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
3940 break;
3941
3942 case SK_CastDerivedToBaseLValue:
3943 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
3944 break;
3945
3946 case SK_BindReference:
3947 OS << "bind reference to lvalue";
3948 break;
3949
3950 case SK_BindReferenceToTemporary:
3951 OS << "bind reference to a temporary";
3952 break;
3953
3954 case SK_UserConversion:
3955 OS << "user-defined conversion via " << S->Function->getNameAsString();
3956 break;
3957
3958 case SK_QualificationConversionRValue:
3959 OS << "qualification conversion (rvalue)";
3960
3961 case SK_QualificationConversionLValue:
3962 OS << "qualification conversion (lvalue)";
3963 break;
3964
3965 case SK_ConversionSequence:
3966 OS << "implicit conversion sequence (";
3967 S->ICS->DebugPrint(); // FIXME: use OS
3968 OS << ")";
3969 break;
3970
3971 case SK_ListInitialization:
3972 OS << "list initialization";
3973 break;
3974
3975 case SK_ConstructorInitialization:
3976 OS << "constructor initialization";
3977 break;
3978
3979 case SK_ZeroInitialization:
3980 OS << "zero initialization";
3981 break;
3982
3983 case SK_CAssignment:
3984 OS << "C assignment";
3985 break;
3986
3987 case SK_StringInit:
3988 OS << "string initialization";
3989 break;
3990 }
3991 }
3992}
3993
3994void InitializationSequence::dump() const {
3995 dump(llvm::errs());
3996}
3997
Douglas Gregore1314a62009-12-18 05:02:21 +00003998//===----------------------------------------------------------------------===//
3999// Initialization helper functions
4000//===----------------------------------------------------------------------===//
4001Sema::OwningExprResult
4002Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4003 SourceLocation EqualLoc,
4004 OwningExprResult Init) {
4005 if (Init.isInvalid())
4006 return ExprError();
4007
4008 Expr *InitE = (Expr *)Init.get();
4009 assert(InitE && "No initialization expression?");
4010
4011 if (EqualLoc.isInvalid())
4012 EqualLoc = InitE->getLocStart();
4013
4014 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4015 EqualLoc);
4016 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4017 Init.release();
4018 return Seq.Perform(*this, Entity, Kind,
4019 MultiExprArg(*this, (void**)&InitE, 1));
4020}