blob: 5571c1b3824e6d0097274de93eba805506e599da [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregorc171e3b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "Sema.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000022#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000024#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Chris Lattner79e079d2009-02-24 23:10:27 +000035static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000036 const ArrayType *AT = Context.getAsArrayType(DeclType);
37 if (!AT) return 0;
38
Eli Friedman8718a6a2009-05-29 18:22:49 +000039 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40 return 0;
41
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // See if this is a string literal or @encode.
43 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattner8879e3b2009-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 Lattner220b6362009-02-26 23:42:47 +000051 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000052
53 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-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 Friedmanbb6415c2009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000058
Eli Friedmanbb6415c2009-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 Lattner8879e3b2009-02-26 23:26:43 +000065 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattnerdd8e0062009-02-24 22:27:37 +000067 return 0;
68}
69
Chris Lattner79e079d2009-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 Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner79e079d2009-02-24 23:10:27 +000076 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000077 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000078 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000079 // being initialized to a string literal.
80 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000081 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000082 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000083 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
84 ConstVal,
85 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000086 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000087 }
Mike Stump1eb44332009-09-09 15:08:12 +000088
Eli Friedman8718a6a2009-05-29 18:22:49 +000089 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000090
Eli Friedman8718a6a2009-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 Stump1eb44332009-09-09 15:08:12 +000098
Eli Friedman8718a6a2009-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 Lattnerdd8e0062009-02-24 22:27:37 +0000104}
105
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000106//===----------------------------------------------------------------------===//
107// Semantic checking for initializer lists.
108//===----------------------------------------------------------------------===//
109
Douglas Gregor9e80f722009-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 Lattner8b419b92009-02-24 22:48:58 +0000137namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000138class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000139 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000140 bool hadError;
141 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
142 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000144 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000145 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000146 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000147 unsigned &StructuredIndex,
148 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000149 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000150 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000151 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000152 unsigned &StructuredIndex,
153 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000154 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000155 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000156 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000157 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000159 unsigned &StructuredIndex,
160 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000161 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000162 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000163 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000164 InitListExpr *StructuredList,
165 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000166 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000167 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000168 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000169 InitListExpr *StructuredList,
170 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000171 void CheckReferenceType(const InitializedEntity &Entity,
172 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000173 unsigned &Index,
174 InitListExpr *StructuredList,
175 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000181 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000182 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000183 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000194 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000195 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000196 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000197 RecordDecl::field_iterator *NextField,
198 llvm::APSInt *NextElementIndex,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000202 bool FinishSubobjectInit,
203 bool TopLevelObject);
Douglas Gregorc34ee5e2009-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 Gregor9e80f722009-01-29 01:05:33 +0000209 void UpdateStructuredListElement(InitListExpr *StructuredList,
210 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000211 Expr *expr);
212 int numArrayElements(QualType DeclType);
213 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000214
Douglas Gregord6d37de2009-12-22 00:05:34 +0000215 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
216 const InitializedEntity &ParentEntity,
217 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000218 void FillInValueInitializations(const InitializedEntity &Entity,
219 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000220public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000221 InitListChecker(Sema &S, const InitializedEntity &Entity,
222 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-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 Lattner8b419b92009-02-24 22:48:58 +0000229} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000230
Douglas Gregord6d37de2009-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 Kremenek709210f2010-04-13 23:39:13 +0000284 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-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 Gregor4c678342009-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 Gregorcb57fb92009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Ted Kremenek6217b802009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-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 Gregor4c678342009-01-28 21:54:33 +0000319
Douglas Gregord6d37de2009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000321 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000325 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000326
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000336 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000354 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000357
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssond3d824d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregor87fd7032009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-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 Gregor87fd7032009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
Douglas Gregorcb57fb92009-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 Gregor16006c92009-12-16 18:50:27 +0000380 hadError = true;
Douglas Gregorcb57fb92009-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 Kremenek709210f2010-04-13 23:39:13 +0000394 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 RequiresSecondPass = true;
396 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000397 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
399 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000400 }
401}
402
Chris Lattner68355a52009-01-29 05:10:57 +0000403
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
405 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000406 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000407 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000408
Eli Friedmanb85f7072008-05-19 19:16:24 +0000409 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000410 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000411 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000412 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000413 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000414 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000415 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000416
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000417 if (!hadError) {
418 bool RequiresSecondPass = false;
419 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000420 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000421 FillInValueInitializations(Entity, FullyStructuredList,
422 RequiresSecondPass);
423 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000424}
425
426int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000427 // FIXME: use a proper constant
428 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000429 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000430 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-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 Kremenek6217b802009-07-29 21:53:49 +0000437 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000438 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000439 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000440 Field = structDecl->field_begin(),
441 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000442 Field != FieldEnd; ++Field) {
443 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
444 ++InitializableMembers;
445 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000446 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000447 return std::min(InitializableMembers, 1);
448 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000449}
450
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000451void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000452 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000453 QualType T, unsigned &Index,
454 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000455 unsigned &StructuredIndex,
456 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000457 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 if (T->isArrayType())
460 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000461 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000462 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000463 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000464 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000465 else
466 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000467
Eli Friedman402256f2008-05-25 13:49:22 +0000468 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000469 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000470 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000471 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000472 hadError = true;
473 return;
474 }
475
Douglas Gregor4c678342009-01-28 21:54:33 +0000476 // Build a structured initializer list corresponding to this subobject.
477 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000478 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
479 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000480 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
481 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000482 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000483
Douglas Gregor4c678342009-01-28 21:54:33 +0000484 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000485 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000486 CheckListElementTypes(Entity, ParentIList, T,
487 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000488 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000489 StructuredSubobjectInitIndex,
490 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000491 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000492 StructuredSubobjectInitList->setType(T);
493
Douglas Gregored8a93d2009-03-01 17:12:46 +0000494 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000495 // range corresponds with the end of the last initializer it used.
496 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000497 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000498 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
499 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
500 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000501
502 // Warn about missing braces.
503 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000504 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
505 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000506 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000507 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
508 "{")
509 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner1dcd0612010-03-07 04:47:12 +0000510 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000511 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000512 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000513}
514
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000515void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000516 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000517 unsigned &Index,
518 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000519 unsigned &StructuredIndex,
520 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000521 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000522 SyntacticToSemantic[IList] = StructuredList;
523 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000524 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
525 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor2c792812010-02-09 00:50:06 +0000526 IList->setType(T.getNonReferenceType());
527 StructuredList->setType(T.getNonReferenceType());
Eli Friedman638e1442008-05-25 13:22:35 +0000528 if (hadError)
529 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000530
Eli Friedman638e1442008-05-25 13:22:35 +0000531 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000532 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000533 if (StructuredIndex == 1 &&
534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000536 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000537 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000538 hadError = true;
539 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000540 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000542 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000543 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000544 // Don't complain for incomplete types, since we'll get an error
545 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000547 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000548 CurrentObjectType->isArrayType()? 0 :
549 CurrentObjectType->isVectorType()? 1 :
550 CurrentObjectType->isScalarType()? 2 :
551 CurrentObjectType->isUnionType()? 3 :
552 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000553
554 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Nate Begeman08634522009-07-07 21:53:06 +0000559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000563
Chris Lattner08202542009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000565 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000566 }
567 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000568
Eli Friedman759f2522009-05-16 11:45:48 +0000569 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000571 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000572 << FixItHint::CreateRemoval(IList->getLocStart())
573 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000574}
575
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000577 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000578 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000579 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000580 unsigned &Index,
581 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000582 unsigned &StructuredIndex,
583 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000584 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000585 CheckScalarType(Entity, IList, DeclType, Index,
586 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000588 CheckVectorType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000590 } else if (DeclType->isAggregateType()) {
591 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000592 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000593 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000595 StructuredList, StructuredIndex,
596 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000597 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000598 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000599 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000600 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000601 CheckArrayType(Entity, IList, DeclType, Zero,
602 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000604 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000605 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000608 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000610 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000611 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000612 } else if (DeclType->isRecordType()) {
613 // C++ [dcl.init]p14:
614 // [...] If the class is an aggregate (8.5.1), and the initializer
615 // is a brace-enclosed list, see 8.5.1.
616 //
617 // Note: 8.5.1 is handled below; here, we diagnose the case where
618 // we have an initializer list and a destination type that is not
619 // an aggregate.
620 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000622 << DeclType << IList->getSourceRange();
623 hadError = true;
624 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000625 CheckReferenceType(Entity, IList, DeclType, Index,
626 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000627 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000628 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
629 << DeclType;
630 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000631 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000632 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
633 << DeclType;
634 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000635 }
636}
637
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000638void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000639 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000640 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000641 unsigned &Index,
642 InitListExpr *StructuredList,
643 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000644 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000645 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
646 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000648 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 = getStructuredSubobjectInit(IList, Index, ElemType,
650 StructuredList, StructuredIndex,
651 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000652 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000653 newStructuredList, newStructuredIndex);
654 ++StructuredIndex;
655 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000656 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
657 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000658 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000659 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000660 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000661 CheckScalarType(Entity, IList, ElemType, Index,
662 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000663 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000664 CheckReferenceType(Entity, IList, ElemType, Index,
665 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000666 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000667 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000668 // C++ [dcl.init.aggr]p12:
669 // All implicit type conversions (clause 4) are considered when
670 // initializing the aggregate member with an ini- tializer from
671 // an initializer-list. If the initializer can initialize a
672 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000673
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000674 // FIXME: Better EqualLoc?
675 InitializationKind Kind =
676 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
677 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
678
679 if (Seq) {
680 Sema::OwningExprResult Result =
681 Seq.Perform(SemaRef, Entity, Kind,
682 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
683 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000684 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000685
686 UpdateStructuredListElement(StructuredList, StructuredIndex,
687 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000688 ++Index;
689 return;
690 }
691
692 // Fall through for subaggregate initialization
693 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000694 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000695 //
696 // The initializer for a structure or union object that has
697 // automatic storage duration shall be either an initializer
698 // list as described below, or a single expression that has
699 // compatible structure or union type. In the latter case, the
700 // initial value of the object, including unnamed members, is
701 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000702 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000703 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000704 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
705 ++Index;
706 return;
707 }
708
709 // Fall through for subaggregate initialization
710 }
711
712 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000713 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000714 // [...] Otherwise, if the member is itself a non-empty
715 // subaggregate, brace elision is assumed and the initializer is
716 // considered for the initialization of the first member of
717 // the subaggregate.
718 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000719 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000720 StructuredIndex);
721 ++StructuredIndex;
722 } else {
723 // We cannot initialize this element, so let
724 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000725 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
726 SemaRef.Owned(expr));
727 IList->setInit(Index, 0);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000728 hadError = true;
729 ++Index;
730 ++StructuredIndex;
731 }
732 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000733}
734
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000735void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000736 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000737 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000738 InitListExpr *StructuredList,
739 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000740 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000741 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000742 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000743 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000744 diag::err_many_braces_around_scalar_init)
745 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000746 hadError = true;
747 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000748 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000749 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000750 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000751 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000752 diag::err_designator_for_scalar_init)
753 << DeclType << expr->getSourceRange();
754 hadError = true;
755 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000756 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000757 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000758 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000759
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000760 Sema::OwningExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000761 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
762 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000763
Chandler Carruthb5719242010-02-13 07:23:01 +0000764 Expr *ResultExpr = 0;
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000765
766 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000767 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000768 else {
769 ResultExpr = Result.takeAs<Expr>();
770
771 if (ResultExpr != expr) {
772 // The type was promoted, update initializer list.
773 IList->setInit(Index, ResultExpr);
774 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000775 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000776 if (hadError)
777 ++StructuredIndex;
778 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000779 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000780 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000781 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000782 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000783 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000784 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000785 ++Index;
786 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000787 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000788 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000789}
790
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000791void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
792 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000793 unsigned &Index,
794 InitListExpr *StructuredList,
795 unsigned &StructuredIndex) {
796 if (Index < IList->getNumInits()) {
797 Expr *expr = IList->getInit(Index);
798 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000799 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000800 << DeclType << IList->getSourceRange();
801 hadError = true;
802 ++Index;
803 ++StructuredIndex;
804 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000805 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000806
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000807 Sema::OwningExprResult Result =
808 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
809 SemaRef.Owned(expr));
810
811 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000812 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000813
814 expr = Result.takeAs<Expr>();
815 IList->setInit(Index, expr);
816
Douglas Gregor930d8b52009-01-30 22:09:00 +0000817 if (hadError)
818 ++StructuredIndex;
819 else
820 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
821 ++Index;
822 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000823 // FIXME: It would be wonderful if we could point at the actual member. In
824 // general, it would be useful to pass location information down the stack,
825 // so that we know the location (or decl) of the "current object" being
826 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000827 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000828 diag::err_init_reference_member_uninitialized)
829 << DeclType
830 << IList->getSourceRange();
831 hadError = true;
832 ++Index;
833 ++StructuredIndex;
834 return;
835 }
836}
837
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000838void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000839 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000840 unsigned &Index,
841 InitListExpr *StructuredList,
842 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000843 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000844 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000845 unsigned maxElements = VT->getNumElements();
846 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000847 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Nate Begeman2ef13e52009-08-10 23:49:36 +0000849 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000850 InitializedEntity ElementEntity =
851 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000852
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000853 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
854 // Don't attempt to go past the end of the init list
855 if (Index >= IList->getNumInits())
856 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000857
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000858 ElementEntity.setElementIndex(Index);
859 CheckSubElementType(ElementEntity, IList, elementType, Index,
860 StructuredList, StructuredIndex);
861 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000862 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000863 InitializedEntity ElementEntity =
864 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
865
Nate Begeman2ef13e52009-08-10 23:49:36 +0000866 // OpenCL initializers allows vectors to be constructed from vectors.
867 for (unsigned i = 0; i < maxElements; ++i) {
868 // Don't attempt to go past the end of the init list
869 if (Index >= IList->getNumInits())
870 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000871
872 ElementEntity.setElementIndex(Index);
873
Nate Begeman2ef13e52009-08-10 23:49:36 +0000874 QualType IType = IList->getInit(Index)->getType();
875 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000876 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000877 StructuredList, StructuredIndex);
878 ++numEltsInit;
879 } else {
Nate Begeman3e315522010-07-07 22:26:56 +0000880 QualType VecType;
John McCall183700f2009-09-21 23:43:11 +0000881 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000882 unsigned numIElts = IVT->getNumElements();
Nate Begeman3e315522010-07-07 22:26:56 +0000883
884 if (IType->isExtVectorType())
885 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
886 else
887 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
888 IVT->getAltiVecSpecific());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000889 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000890 StructuredList, StructuredIndex);
891 numEltsInit += numIElts;
892 }
893 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000894 }
Mike Stump1eb44332009-09-09 15:08:12 +0000895
John Thompsonf3afbea2010-04-20 23:21:17 +0000896 // OpenCL requires all elements to be initialized.
Nate Begeman2ef13e52009-08-10 23:49:36 +0000897 if (numEltsInit != maxElements)
Chris Lattnere12a7792010-04-20 05:19:10 +0000898 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman2ef13e52009-08-10 23:49:36 +0000899 SemaRef.Diag(IList->getSourceRange().getBegin(),
900 diag::err_vector_incorrect_num_initializers)
901 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000902 }
903}
904
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000905void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000906 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000907 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000908 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000909 unsigned &Index,
910 InitListExpr *StructuredList,
911 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000912 // Check for the special-case of initializing an array with a string.
913 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000914 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
915 SemaRef.Context)) {
916 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000917 // We place the string literal directly into the resulting
918 // initializer list. This is the only place where the structure
919 // of the structured initializer list doesn't match exactly,
920 // because doing so would involve allocating one character
921 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000922 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000923 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000924 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000925 return;
926 }
927 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000928 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000929 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000930 // Check for VLAs; in standard C it would be possible to check this
931 // earlier, but I don't know where clang accepts VLAs (gcc accepts
932 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000933 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000934 diag::err_variable_object_no_init)
935 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000936 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000937 ++Index;
938 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000939 return;
940 }
941
Douglas Gregor05c13a32009-01-22 00:58:24 +0000942 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000943 llvm::APSInt maxElements(elementIndex.getBitWidth(),
944 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000945 bool maxElementsKnown = false;
946 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000947 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000948 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000949 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000950 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000951 maxElementsKnown = true;
952 }
953
Chris Lattner08202542009-02-24 22:50:46 +0000954 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000955 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000956 while (Index < IList->getNumInits()) {
957 Expr *Init = IList->getInit(Index);
958 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000959 // If we're not the subobject that matches up with the '{' for
960 // the designator, we shouldn't be handling the
961 // designator. Return immediately.
962 if (!SubobjectIsDesignatorContext)
963 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000964
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000965 // Handle this designated initializer. elementIndex will be
966 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000967 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000968 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000969 StructuredList, StructuredIndex, true,
970 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000971 hadError = true;
972 continue;
973 }
974
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000975 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
976 maxElements.extend(elementIndex.getBitWidth());
977 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
978 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000979 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000980
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000981 // If the array is of incomplete type, keep track of the number of
982 // elements in the initializer.
983 if (!maxElementsKnown && elementIndex > maxElements)
984 maxElements = elementIndex;
985
Douglas Gregor05c13a32009-01-22 00:58:24 +0000986 continue;
987 }
988
989 // If we know the maximum number of elements, and we've already
990 // hit it, stop consuming elements in the initializer list.
991 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000992 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000993
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000994 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000995 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000996 Entity);
997 // Check this element.
998 CheckSubElementType(ElementEntity, IList, elementType, Index,
999 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001000 ++elementIndex;
1001
1002 // If the array is of incomplete type, keep track of the number of
1003 // elements in the initializer.
1004 if (!maxElementsKnown && elementIndex > maxElements)
1005 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001006 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001007 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001008 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001009 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001010 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001011 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001012 // Sizing an array implicitly to zero is not allowed by ISO C,
1013 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001014 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001015 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001016 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001017
Mike Stump1eb44332009-09-09 15:08:12 +00001018 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001019 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001020 }
1021}
1022
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001023void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001024 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001025 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001026 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001027 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001028 unsigned &Index,
1029 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001030 unsigned &StructuredIndex,
1031 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001032 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Eli Friedmanb85f7072008-05-19 19:16:24 +00001034 // If the record is invalid, some of it's members are invalid. To avoid
1035 // confusion, we forgo checking the intializer for the entire record.
1036 if (structDecl->isInvalidDecl()) {
1037 hadError = true;
1038 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001039 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001040
1041 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1042 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001043 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001044 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001045 Field != FieldEnd; ++Field) {
1046 if (Field->getDeclName()) {
1047 StructuredList->setInitializedFieldInUnion(*Field);
1048 break;
1049 }
1050 }
1051 return;
1052 }
1053
Douglas Gregor05c13a32009-01-22 00:58:24 +00001054 // If structDecl is a forward declaration, this loop won't do
1055 // anything except look at designated initializers; That's okay,
1056 // because an error should get printed out elsewhere. It might be
1057 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001058 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001059 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001060 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001061 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001062 while (Index < IList->getNumInits()) {
1063 Expr *Init = IList->getInit(Index);
1064
1065 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001066 // If we're not the subobject that matches up with the '{' for
1067 // the designator, we shouldn't be handling the
1068 // designator. Return immediately.
1069 if (!SubobjectIsDesignatorContext)
1070 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001071
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001072 // Handle this designated initializer. Field will be updated to
1073 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001074 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001075 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001076 StructuredList, StructuredIndex,
1077 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001078 hadError = true;
1079
Douglas Gregordfb5e592009-02-12 19:00:39 +00001080 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001081
1082 // Disable check for missing fields when designators are used.
1083 // This matches gcc behaviour.
1084 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001085 continue;
1086 }
1087
1088 if (Field == FieldEnd) {
1089 // We've run out of fields. We're done.
1090 break;
1091 }
1092
Douglas Gregordfb5e592009-02-12 19:00:39 +00001093 // We've already initialized a member of a union. We're done.
1094 if (InitializedSomething && DeclType->isUnionType())
1095 break;
1096
Douglas Gregor44b43212008-12-11 16:49:14 +00001097 // If we've hit the flexible array member at the end, we're done.
1098 if (Field->getType()->isIncompleteArrayType())
1099 break;
1100
Douglas Gregor0bb76892009-01-29 16:53:55 +00001101 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001102 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001103 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001104 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001105 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001106
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001107 InitializedEntity MemberEntity =
1108 InitializedEntity::InitializeMember(*Field, &Entity);
1109 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1110 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001111 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001112
1113 if (DeclType->isUnionType()) {
1114 // Initialize the first field within the union.
1115 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001116 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001117
1118 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001119 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001120
John McCall80639de2010-03-11 19:32:38 +00001121 // Emit warnings for missing struct field initializers.
Douglas Gregor8e198902010-06-18 21:43:10 +00001122 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001123 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1124 // It is possible we have one or more unnamed bitfields remaining.
1125 // Find first (if any) named field and emit warning.
1126 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1127 it != end; ++it) {
1128 if (!it->isUnnamedBitfield()) {
1129 SemaRef.Diag(IList->getSourceRange().getEnd(),
1130 diag::warn_missing_field_initializers) << it->getName();
1131 break;
1132 }
1133 }
1134 }
1135
Mike Stump1eb44332009-09-09 15:08:12 +00001136 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001137 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001138 return;
1139
1140 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001141 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001142 (!isa<InitListExpr>(IList->getInit(Index)) ||
1143 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001144 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001145 diag::err_flexible_array_init_nonempty)
1146 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001147 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001148 << *Field;
1149 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001150 ++Index;
1151 return;
1152 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001153 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001154 diag::ext_flexible_array_init)
1155 << IList->getInit(Index)->getSourceRange().getBegin();
1156 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1157 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001158 }
1159
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001160 InitializedEntity MemberEntity =
1161 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001162
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001163 if (isa<InitListExpr>(IList->getInit(Index)))
1164 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1165 StructuredList, StructuredIndex);
1166 else
1167 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001168 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001169}
Steve Naroff0cca7492008-05-01 22:18:59 +00001170
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001171/// \brief Expand a field designator that refers to a member of an
1172/// anonymous struct or union into a series of field designators that
1173/// refers to the field within the appropriate subobject.
1174///
1175/// Field/FieldIndex will be updated to point to the (new)
1176/// currently-designated field.
1177static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001178 DesignatedInitExpr *DIE,
1179 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001180 FieldDecl *Field,
1181 RecordDecl::field_iterator &FieldIter,
1182 unsigned &FieldIndex) {
1183 typedef DesignatedInitExpr::Designator Designator;
1184
1185 // Build the path from the current object to the member of the
1186 // anonymous struct/union (backwards).
1187 llvm::SmallVector<FieldDecl *, 4> Path;
1188 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001190 // Build the replacement designators.
1191 llvm::SmallVector<Designator, 4> Replacements;
1192 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1193 FI = Path.rbegin(), FIEnd = Path.rend();
1194 FI != FIEnd; ++FI) {
1195 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001196 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001197 DIE->getDesignator(DesigIdx)->getDotLoc(),
1198 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1199 else
1200 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1201 SourceLocation()));
1202 Replacements.back().setField(*FI);
1203 }
1204
1205 // Expand the current designator into the set of replacement
1206 // designators, so we have a full subobject path down to where the
1207 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001208 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001209 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001211 // Update FieldIter/FieldIndex;
1212 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001213 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001214 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001215 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001216 FieldIter != FEnd; ++FieldIter) {
1217 if (FieldIter->isUnnamedBitfield())
1218 continue;
1219
1220 if (*FieldIter == Path.back())
1221 return;
1222
1223 ++FieldIndex;
1224 }
1225
1226 assert(false && "Unable to find anonymous struct/union field");
1227}
1228
Douglas Gregor05c13a32009-01-22 00:58:24 +00001229/// @brief Check the well-formedness of a C99 designated initializer.
1230///
1231/// Determines whether the designated initializer @p DIE, which
1232/// resides at the given @p Index within the initializer list @p
1233/// IList, is well-formed for a current object of type @p DeclType
1234/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001235/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001236/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001237///
1238/// @param IList The initializer list in which this designated
1239/// initializer occurs.
1240///
Douglas Gregor71199712009-04-15 04:56:10 +00001241/// @param DIE The designated initializer expression.
1242///
1243/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001244///
1245/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1246/// into which the designation in @p DIE should refer.
1247///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001248/// @param NextField If non-NULL and the first designator in @p DIE is
1249/// a field, this will be set to the field declaration corresponding
1250/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001251///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001252/// @param NextElementIndex If non-NULL and the first designator in @p
1253/// DIE is an array designator or GNU array-range designator, this
1254/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001255///
1256/// @param Index Index into @p IList where the designated initializer
1257/// @p DIE occurs.
1258///
Douglas Gregor4c678342009-01-28 21:54:33 +00001259/// @param StructuredList The initializer list expression that
1260/// describes all of the subobject initializers in the order they'll
1261/// actually be initialized.
1262///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001263/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001264bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001265InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001266 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001267 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001268 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001269 QualType &CurrentObjectType,
1270 RecordDecl::field_iterator *NextField,
1271 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001272 unsigned &Index,
1273 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001274 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001275 bool FinishSubobjectInit,
1276 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001277 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001278 // Check the actual initialization for the designated object type.
1279 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001280
1281 // Temporarily remove the designator expression from the
1282 // initializer list that the child calls see, so that we don't try
1283 // to re-process the designator.
1284 unsigned OldIndex = Index;
1285 IList->setInit(OldIndex, DIE->getInit());
1286
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001287 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001288 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001289
1290 // Restore the designated initializer expression in the syntactic
1291 // form of the initializer list.
1292 if (IList->getInit(OldIndex) != DIE->getInit())
1293 DIE->setInit(IList->getInit(OldIndex));
1294 IList->setInit(OldIndex, DIE);
1295
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001296 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001297 }
1298
Douglas Gregor71199712009-04-15 04:56:10 +00001299 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001300 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001301 "Need a non-designated initializer list to start from");
1302
Douglas Gregor71199712009-04-15 04:56:10 +00001303 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001304 // Determine the structural initializer list that corresponds to the
1305 // current subobject.
1306 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001307 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001308 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001309 SourceRange(D->getStartLocation(),
1310 DIE->getSourceRange().getEnd()));
1311 assert(StructuredList && "Expected a structured initializer list");
1312
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001313 if (D->isFieldDesignator()) {
1314 // C99 6.7.8p7:
1315 //
1316 // If a designator has the form
1317 //
1318 // . identifier
1319 //
1320 // then the current object (defined below) shall have
1321 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001322 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001323 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001324 if (!RT) {
1325 SourceLocation Loc = D->getDotLoc();
1326 if (Loc.isInvalid())
1327 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001328 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1329 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001330 ++Index;
1331 return true;
1332 }
1333
Douglas Gregor4c678342009-01-28 21:54:33 +00001334 // Note: we perform a linear search of the fields here, despite
1335 // the fact that we have a faster lookup method, because we always
1336 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001337 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001338 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001339 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001340 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001341 Field = RT->getDecl()->field_begin(),
1342 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001343 for (; Field != FieldEnd; ++Field) {
1344 if (Field->isUnnamedBitfield())
1345 continue;
1346
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001347 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001348 break;
1349
1350 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001351 }
1352
Douglas Gregor4c678342009-01-28 21:54:33 +00001353 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001354 // There was no normal field in the struct with the designated
1355 // name. Perform another lookup for this name, which may find
1356 // something that we can't designate (e.g., a member function),
1357 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001358 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001359 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001360 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001361 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001362 // Name lookup didn't find anything. Determine whether this
1363 // was a typo for another field name.
1364 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1365 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001366 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1367 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001368 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1369 ReplacementField->getDeclContext()->getLookupContext()
1370 ->Equals(RT->getDecl())) {
1371 SemaRef.Diag(D->getFieldLoc(),
1372 diag::err_field_designator_unknown_suggest)
1373 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001374 << FixItHint::CreateReplacement(D->getFieldLoc(),
1375 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001376 SemaRef.Diag(ReplacementField->getLocation(),
1377 diag::note_previous_decl)
1378 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001379 } else {
1380 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1381 << FieldName << CurrentObjectType;
1382 ++Index;
1383 return true;
1384 }
1385 } else if (!KnownField) {
1386 // Determine whether we found a field at all.
1387 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1388 }
1389
1390 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001391 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001392 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001394 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001395 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001396 ++Index;
1397 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001398 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001399
1400 if (!KnownField &&
1401 cast<RecordDecl>((ReplacementField)->getDeclContext())
1402 ->isAnonymousStructOrUnion()) {
1403 // Handle an field designator that refers to a member of an
1404 // anonymous struct or union.
1405 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1406 ReplacementField,
1407 Field, FieldIndex);
1408 D = DIE->getDesignator(DesigIdx);
1409 } else if (!KnownField) {
1410 // The replacement field comes from typo correction; find it
1411 // in the list of fields.
1412 FieldIndex = 0;
1413 Field = RT->getDecl()->field_begin();
1414 for (; Field != FieldEnd; ++Field) {
1415 if (Field->isUnnamedBitfield())
1416 continue;
1417
1418 if (ReplacementField == *Field ||
1419 Field->getIdentifier() == ReplacementField->getIdentifier())
1420 break;
1421
1422 ++FieldIndex;
1423 }
1424 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001425 } else if (!KnownField &&
1426 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001427 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001428 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1429 Field, FieldIndex);
1430 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001431 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001432
1433 // All of the fields of a union are located at the same place in
1434 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001435 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001436 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001437 StructuredList->setInitializedFieldInUnion(*Field);
1438 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001439
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001440 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001441 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Douglas Gregor4c678342009-01-28 21:54:33 +00001443 // Make sure that our non-designated initializer list has space
1444 // for a subobject corresponding to this field.
1445 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001446 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001447
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001448 // This designator names a flexible array member.
1449 if (Field->getType()->isIncompleteArrayType()) {
1450 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001451 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001452 // We can't designate an object within the flexible array
1453 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001454 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001455 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001456 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001457 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001458 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001459 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001460 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001461 << *Field;
1462 Invalid = true;
1463 }
1464
1465 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1466 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001467 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001468 diag::err_flexible_array_init_needs_braces)
1469 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001470 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001471 << *Field;
1472 Invalid = true;
1473 }
1474
1475 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001476 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001477 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001478 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001479 diag::err_flexible_array_init_nonempty)
1480 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001481 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001482 << *Field;
1483 Invalid = true;
1484 }
1485
1486 if (Invalid) {
1487 ++Index;
1488 return true;
1489 }
1490
1491 // Initialize the array.
1492 bool prevHadError = hadError;
1493 unsigned newStructuredIndex = FieldIndex;
1494 unsigned OldIndex = Index;
1495 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001496
1497 InitializedEntity MemberEntity =
1498 InitializedEntity::InitializeMember(*Field, &Entity);
1499 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001500 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001501
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001502 IList->setInit(OldIndex, DIE);
1503 if (hadError && !prevHadError) {
1504 ++Field;
1505 ++FieldIndex;
1506 if (NextField)
1507 *NextField = Field;
1508 StructuredIndex = FieldIndex;
1509 return true;
1510 }
1511 } else {
1512 // Recurse to check later designated subobjects.
1513 QualType FieldType = (*Field)->getType();
1514 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001515
1516 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001517 InitializedEntity::InitializeMember(*Field, &Entity);
1518 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001519 FieldType, 0, 0, Index,
1520 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001521 true, false))
1522 return true;
1523 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001524
1525 // Find the position of the next field to be initialized in this
1526 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001528 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001529
1530 // If this the first designator, our caller will continue checking
1531 // the rest of this struct/class/union subobject.
1532 if (IsFirstDesignator) {
1533 if (NextField)
1534 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001535 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001536 return false;
1537 }
1538
Douglas Gregor34e79462009-01-28 23:36:17 +00001539 if (!FinishSubobjectInit)
1540 return false;
1541
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001542 // We've already initialized something in the union; we're done.
1543 if (RT->getDecl()->isUnion())
1544 return hadError;
1545
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001546 // Check the remaining fields within this class/struct/union subobject.
1547 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001548
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001549 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001550 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001551 return hadError && !prevHadError;
1552 }
1553
1554 // C99 6.7.8p6:
1555 //
1556 // If a designator has the form
1557 //
1558 // [ constant-expression ]
1559 //
1560 // then the current object (defined below) shall have array
1561 // type and the expression shall be an integer constant
1562 // expression. If the array is of unknown size, any
1563 // nonnegative value is valid.
1564 //
1565 // Additionally, cope with the GNU extension that permits
1566 // designators of the form
1567 //
1568 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001569 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001570 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001571 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001572 << CurrentObjectType;
1573 ++Index;
1574 return true;
1575 }
1576
1577 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001578 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1579 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001580 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001581 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001582 DesignatedEndIndex = DesignatedStartIndex;
1583 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001584 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001585
Mike Stump1eb44332009-09-09 15:08:12 +00001586
1587 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001588 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001589 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001590 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001591 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001592
Chris Lattner3bf68932009-04-25 21:59:05 +00001593 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001594 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001595 }
1596
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001597 if (isa<ConstantArrayType>(AT)) {
1598 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001599 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1600 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1601 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1602 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1603 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001604 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001605 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001606 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001607 << IndexExpr->getSourceRange();
1608 ++Index;
1609 return true;
1610 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001611 } else {
1612 // Make sure the bit-widths and signedness match.
1613 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1614 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001615 else if (DesignatedStartIndex.getBitWidth() <
1616 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001617 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1618 DesignatedStartIndex.setIsUnsigned(true);
1619 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001620 }
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Douglas Gregor4c678342009-01-28 21:54:33 +00001622 // Make sure that our non-designated initializer list has space
1623 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001624 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001625 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001626 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001627
Douglas Gregor34e79462009-01-28 23:36:17 +00001628 // Repeatedly perform subobject initializations in the range
1629 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001630
Douglas Gregor34e79462009-01-28 23:36:17 +00001631 // Move to the next designator
1632 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1633 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001634
1635 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001636 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001637
Douglas Gregor34e79462009-01-28 23:36:17 +00001638 while (DesignatedStartIndex <= DesignatedEndIndex) {
1639 // Recurse to check later designated subobjects.
1640 QualType ElementType = AT->getElementType();
1641 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001642
1643 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001644 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001645 ElementType, 0, 0, Index,
1646 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001647 (DesignatedStartIndex == DesignatedEndIndex),
1648 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001649 return true;
1650
1651 // Move to the next index in the array that we'll be initializing.
1652 ++DesignatedStartIndex;
1653 ElementIndex = DesignatedStartIndex.getZExtValue();
1654 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001655
1656 // If this the first designator, our caller will continue checking
1657 // the rest of this array subobject.
1658 if (IsFirstDesignator) {
1659 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001660 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001661 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001662 return false;
1663 }
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Douglas Gregor34e79462009-01-28 23:36:17 +00001665 if (!FinishSubobjectInit)
1666 return false;
1667
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001668 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001669 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001670 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001671 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001672 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001673 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001674}
1675
Douglas Gregor4c678342009-01-28 21:54:33 +00001676// Get the structured initializer list for a subobject of type
1677// @p CurrentObjectType.
1678InitListExpr *
1679InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1680 QualType CurrentObjectType,
1681 InitListExpr *StructuredList,
1682 unsigned StructuredIndex,
1683 SourceRange InitRange) {
1684 Expr *ExistingInit = 0;
1685 if (!StructuredList)
1686 ExistingInit = SyntacticToSemantic[IList];
1687 else if (StructuredIndex < StructuredList->getNumInits())
1688 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Douglas Gregor4c678342009-01-28 21:54:33 +00001690 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1691 return Result;
1692
1693 if (ExistingInit) {
1694 // We are creating an initializer list that initializes the
1695 // subobjects of the current object, but there was already an
1696 // initialization that completely initialized the current
1697 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001698 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001699 // struct X { int a, b; };
1700 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001701 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001702 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1703 // designated initializer re-initializes the whole
1704 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001705 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001706 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001707 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001708 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001709 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001710 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001711 << ExistingInit->getSourceRange();
1712 }
1713
Mike Stump1eb44332009-09-09 15:08:12 +00001714 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001715 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1716 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001717 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001718
Douglas Gregor2c792812010-02-09 00:50:06 +00001719 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor4c678342009-01-28 21:54:33 +00001720
Douglas Gregorfa219202009-03-20 23:58:33 +00001721 // Pre-allocate storage for the structured initializer list.
1722 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001723 unsigned NumInits = 0;
1724 if (!StructuredList)
1725 NumInits = IList->getNumInits();
1726 else if (Index < IList->getNumInits()) {
1727 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1728 NumInits = SubList->getNumInits();
1729 }
1730
Mike Stump1eb44332009-09-09 15:08:12 +00001731 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001732 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1733 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1734 NumElements = CAType->getSize().getZExtValue();
1735 // Simple heuristic so that we don't allocate a very large
1736 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001737 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001738 NumElements = 0;
1739 }
John McCall183700f2009-09-21 23:43:11 +00001740 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001741 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001742 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001743 RecordDecl *RDecl = RType->getDecl();
1744 if (RDecl->isUnion())
1745 NumElements = 1;
1746 else
Mike Stump1eb44332009-09-09 15:08:12 +00001747 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001748 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001749 }
1750
Douglas Gregor08457732009-03-21 18:13:52 +00001751 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001752 NumElements = IList->getNumInits();
1753
Ted Kremenek709210f2010-04-13 23:39:13 +00001754 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001755
Douglas Gregor4c678342009-01-28 21:54:33 +00001756 // Link this new initializer list into the structured initializer
1757 // lists.
1758 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001759 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001760 else {
1761 Result->setSyntacticForm(IList);
1762 SyntacticToSemantic[IList] = Result;
1763 }
1764
1765 return Result;
1766}
1767
1768/// Update the initializer at index @p StructuredIndex within the
1769/// structured initializer list to the value @p expr.
1770void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1771 unsigned &StructuredIndex,
1772 Expr *expr) {
1773 // No structured initializer list to update
1774 if (!StructuredList)
1775 return;
1776
Ted Kremenek709210f2010-04-13 23:39:13 +00001777 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1778 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001780 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001781 diag::warn_initializer_overrides)
1782 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001783 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001784 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001785 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001786 << PrevInit->getSourceRange();
1787 }
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Douglas Gregor4c678342009-01-28 21:54:33 +00001789 ++StructuredIndex;
1790}
1791
Douglas Gregor05c13a32009-01-22 00:58:24 +00001792/// Check that the given Index expression is a valid array designator
1793/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001794/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001795/// and produces a reasonable diagnostic if there is a
1796/// failure. Returns true if there was an error, false otherwise. If
1797/// everything went okay, Value will receive the value of the constant
1798/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001799static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001800CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001801 SourceLocation Loc = Index->getSourceRange().getBegin();
1802
1803 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001804 if (S.VerifyIntegerConstantExpression(Index, &Value))
1805 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001806
Chris Lattner3bf68932009-04-25 21:59:05 +00001807 if (Value.isSigned() && Value.isNegative())
1808 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001809 << Value.toString(10) << Index->getSourceRange();
1810
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001811 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001812 return false;
1813}
1814
1815Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1816 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001817 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001818 OwningExprResult Init) {
1819 typedef DesignatedInitExpr::Designator ASTDesignator;
1820
1821 bool Invalid = false;
1822 llvm::SmallVector<ASTDesignator, 32> Designators;
1823 llvm::SmallVector<Expr *, 32> InitExpressions;
1824
1825 // Build designators and check array designator expressions.
1826 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1827 const Designator &D = Desig.getDesignator(Idx);
1828 switch (D.getKind()) {
1829 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001830 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001831 D.getFieldLoc()));
1832 break;
1833
1834 case Designator::ArrayDesignator: {
1835 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1836 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001837 if (!Index->isTypeDependent() &&
1838 !Index->isValueDependent() &&
1839 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001840 Invalid = true;
1841 else {
1842 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001843 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001844 D.getRBracketLoc()));
1845 InitExpressions.push_back(Index);
1846 }
1847 break;
1848 }
1849
1850 case Designator::ArrayRangeDesignator: {
1851 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1852 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1853 llvm::APSInt StartValue;
1854 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001855 bool StartDependent = StartIndex->isTypeDependent() ||
1856 StartIndex->isValueDependent();
1857 bool EndDependent = EndIndex->isTypeDependent() ||
1858 EndIndex->isValueDependent();
1859 if ((!StartDependent &&
1860 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1861 (!EndDependent &&
1862 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001863 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001864 else {
1865 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001866 if (StartDependent || EndDependent) {
1867 // Nothing to compute.
1868 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001869 EndValue.extend(StartValue.getBitWidth());
1870 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1871 StartValue.extend(EndValue.getBitWidth());
1872
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001873 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001874 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001875 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001876 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1877 Invalid = true;
1878 } else {
1879 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001880 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001881 D.getEllipsisLoc(),
1882 D.getRBracketLoc()));
1883 InitExpressions.push_back(StartIndex);
1884 InitExpressions.push_back(EndIndex);
1885 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001886 }
1887 break;
1888 }
1889 }
1890 }
1891
1892 if (Invalid || Init.isInvalid())
1893 return ExprError();
1894
1895 // Clear out the expressions within the designation.
1896 Desig.ClearExprs(*this);
1897
1898 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001899 = DesignatedInitExpr::Create(Context,
1900 Designators.data(), Designators.size(),
1901 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001902 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001903 return Owned(DIE);
1904}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001905
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001906bool Sema::CheckInitList(const InitializedEntity &Entity,
1907 InitListExpr *&InitList, QualType &DeclType) {
1908 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001909 if (!CheckInitList.HadError())
1910 InitList = CheckInitList.getFullyStructuredList();
1911
1912 return CheckInitList.HadError();
1913}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001914
Douglas Gregor20093b42009-12-09 23:02:17 +00001915//===----------------------------------------------------------------------===//
1916// Initialization entity
1917//===----------------------------------------------------------------------===//
1918
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001919InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1920 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001921 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001922{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001923 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1924 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001925 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001926 } else {
1927 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001928 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001929 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001930}
1931
1932InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001933 CXXBaseSpecifier *Base,
1934 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001935{
1936 InitializedEntity Result;
1937 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001938 Result.Base = reinterpret_cast<uintptr_t>(Base);
1939 if (IsInheritedVirtualBase)
1940 Result.Base |= 0x01;
1941
Douglas Gregord6542d82009-12-22 15:35:07 +00001942 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001943 return Result;
1944}
1945
Douglas Gregor99a2e602009-12-16 01:38:02 +00001946DeclarationName InitializedEntity::getName() const {
1947 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001948 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001949 if (!VariableOrMember)
1950 return DeclarationName();
1951 // Fall through
1952
1953 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001954 case EK_Member:
1955 return VariableOrMember->getDeclName();
1956
1957 case EK_Result:
1958 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001959 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001960 case EK_Temporary:
1961 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001962 case EK_ArrayElement:
1963 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001964 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001965 return DeclarationName();
1966 }
1967
1968 // Silence GCC warning
1969 return DeclarationName();
1970}
1971
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001972DeclaratorDecl *InitializedEntity::getDecl() const {
1973 switch (getKind()) {
1974 case EK_Variable:
1975 case EK_Parameter:
1976 case EK_Member:
1977 return VariableOrMember;
1978
1979 case EK_Result:
1980 case EK_Exception:
1981 case EK_New:
1982 case EK_Temporary:
1983 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001984 case EK_ArrayElement:
1985 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001986 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001987 return 0;
1988 }
1989
1990 // Silence GCC warning
1991 return 0;
1992}
1993
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001994bool InitializedEntity::allowsNRVO() const {
1995 switch (getKind()) {
1996 case EK_Result:
1997 case EK_Exception:
1998 return LocAndNRVO.NRVO;
1999
2000 case EK_Variable:
2001 case EK_Parameter:
2002 case EK_Member:
2003 case EK_New:
2004 case EK_Temporary:
2005 case EK_Base:
2006 case EK_ArrayElement:
2007 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002008 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002009 break;
2010 }
2011
2012 return false;
2013}
2014
Douglas Gregor20093b42009-12-09 23:02:17 +00002015//===----------------------------------------------------------------------===//
2016// Initialization sequence
2017//===----------------------------------------------------------------------===//
2018
2019void InitializationSequence::Step::Destroy() {
2020 switch (Kind) {
2021 case SK_ResolveAddressOfOverloadedFunction:
2022 case SK_CastDerivedToBaseRValue:
2023 case SK_CastDerivedToBaseLValue:
2024 case SK_BindReference:
2025 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002026 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002027 case SK_UserConversion:
2028 case SK_QualificationConversionRValue:
2029 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002030 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002031 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002032 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002033 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002034 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00002035 break;
2036
2037 case SK_ConversionSequence:
2038 delete ICS;
2039 }
2040}
2041
Douglas Gregorb70cf442010-03-26 20:14:36 +00002042bool InitializationSequence::isDirectReferenceBinding() const {
2043 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2044}
2045
2046bool InitializationSequence::isAmbiguous() const {
2047 if (getKind() != FailedSequence)
2048 return false;
2049
2050 switch (getFailureKind()) {
2051 case FK_TooManyInitsForReference:
2052 case FK_ArrayNeedsInitList:
2053 case FK_ArrayNeedsInitListOrStringLiteral:
2054 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2055 case FK_NonConstLValueReferenceBindingToTemporary:
2056 case FK_NonConstLValueReferenceBindingToUnrelated:
2057 case FK_RValueReferenceBindingToLValue:
2058 case FK_ReferenceInitDropsQualifiers:
2059 case FK_ReferenceInitFailed:
2060 case FK_ConversionFailed:
2061 case FK_TooManyInitsForScalar:
2062 case FK_ReferenceBindingToInitList:
2063 case FK_InitListBadDestinationType:
2064 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002065 case FK_Incomplete:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002066 return false;
2067
2068 case FK_ReferenceInitOverloadFailed:
2069 case FK_UserConversionOverloadFailed:
2070 case FK_ConstructorOverloadFailed:
2071 return FailedOverloadResult == OR_Ambiguous;
2072 }
2073
2074 return false;
2075}
2076
Douglas Gregord6e44a32010-04-16 22:09:46 +00002077bool InitializationSequence::isConstructorInitialization() const {
2078 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2079}
2080
Douglas Gregor20093b42009-12-09 23:02:17 +00002081void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002082 FunctionDecl *Function,
2083 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002084 Step S;
2085 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2086 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002087 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002088 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002089 Steps.push_back(S);
2090}
2091
2092void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2093 bool IsLValue) {
2094 Step S;
2095 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2096 S.Type = BaseType;
2097 Steps.push_back(S);
2098}
2099
2100void InitializationSequence::AddReferenceBindingStep(QualType T,
2101 bool BindingTemporary) {
2102 Step S;
2103 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2104 S.Type = T;
2105 Steps.push_back(S);
2106}
2107
Douglas Gregor523d46a2010-04-18 07:40:54 +00002108void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2109 Step S;
2110 S.Kind = SK_ExtraneousCopyToTemporary;
2111 S.Type = T;
2112 Steps.push_back(S);
2113}
2114
Eli Friedman03981012009-12-11 02:42:07 +00002115void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002116 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002117 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002118 Step S;
2119 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002120 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002121 S.Function.Function = Function;
2122 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002123 Steps.push_back(S);
2124}
2125
2126void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2127 bool IsLValue) {
2128 Step S;
2129 S.Kind = IsLValue? SK_QualificationConversionLValue
2130 : SK_QualificationConversionRValue;
2131 S.Type = Ty;
2132 Steps.push_back(S);
2133}
2134
2135void InitializationSequence::AddConversionSequenceStep(
2136 const ImplicitConversionSequence &ICS,
2137 QualType T) {
2138 Step S;
2139 S.Kind = SK_ConversionSequence;
2140 S.Type = T;
2141 S.ICS = new ImplicitConversionSequence(ICS);
2142 Steps.push_back(S);
2143}
2144
Douglas Gregord87b61f2009-12-10 17:56:55 +00002145void InitializationSequence::AddListInitializationStep(QualType T) {
2146 Step S;
2147 S.Kind = SK_ListInitialization;
2148 S.Type = T;
2149 Steps.push_back(S);
2150}
2151
Douglas Gregor51c56d62009-12-14 20:49:26 +00002152void
2153InitializationSequence::AddConstructorInitializationStep(
2154 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002155 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002156 QualType T) {
2157 Step S;
2158 S.Kind = SK_ConstructorInitialization;
2159 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002160 S.Function.Function = Constructor;
2161 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002162 Steps.push_back(S);
2163}
2164
Douglas Gregor71d17402009-12-15 00:01:57 +00002165void InitializationSequence::AddZeroInitializationStep(QualType T) {
2166 Step S;
2167 S.Kind = SK_ZeroInitialization;
2168 S.Type = T;
2169 Steps.push_back(S);
2170}
2171
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002172void InitializationSequence::AddCAssignmentStep(QualType T) {
2173 Step S;
2174 S.Kind = SK_CAssignment;
2175 S.Type = T;
2176 Steps.push_back(S);
2177}
2178
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002179void InitializationSequence::AddStringInitStep(QualType T) {
2180 Step S;
2181 S.Kind = SK_StringInit;
2182 S.Type = T;
2183 Steps.push_back(S);
2184}
2185
Douglas Gregor20093b42009-12-09 23:02:17 +00002186void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2187 OverloadingResult Result) {
2188 SequenceKind = FailedSequence;
2189 this->Failure = Failure;
2190 this->FailedOverloadResult = Result;
2191}
2192
2193//===----------------------------------------------------------------------===//
2194// Attempt initialization
2195//===----------------------------------------------------------------------===//
2196
2197/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002198static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002199 const InitializedEntity &Entity,
2200 const InitializationKind &Kind,
2201 InitListExpr *InitList,
2202 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002203 // FIXME: We only perform rudimentary checking of list
2204 // initializations at this point, then assume that any list
2205 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002206 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002207 // do all of the necessary checking. C++0x initializer lists will
2208 // force us to perform more checking here.
2209 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2210
Douglas Gregord6542d82009-12-22 15:35:07 +00002211 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002212
2213 // C++ [dcl.init]p13:
2214 // If T is a scalar type, then a declaration of the form
2215 //
2216 // T x = { a };
2217 //
2218 // is equivalent to
2219 //
2220 // T x = a;
2221 if (DestType->isScalarType()) {
2222 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2223 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2224 return;
2225 }
2226
2227 // Assume scalar initialization from a single value works.
2228 } else if (DestType->isAggregateType()) {
2229 // Assume aggregate initialization works.
2230 } else if (DestType->isVectorType()) {
2231 // Assume vector initialization works.
2232 } else if (DestType->isReferenceType()) {
2233 // FIXME: C++0x defines behavior for this.
2234 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2235 return;
2236 } else if (DestType->isRecordType()) {
2237 // FIXME: C++0x defines behavior for this
2238 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2239 }
2240
2241 // Add a general "list initialization" step.
2242 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002243}
2244
2245/// \brief Try a reference initialization that involves calling a conversion
2246/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002247static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2248 const InitializedEntity &Entity,
2249 const InitializationKind &Kind,
2250 Expr *Initializer,
2251 bool AllowRValues,
2252 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002253 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002254 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2255 QualType T1 = cv1T1.getUnqualifiedType();
2256 QualType cv2T2 = Initializer->getType();
2257 QualType T2 = cv2T2.getUnqualifiedType();
2258
2259 bool DerivedToBase;
2260 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2261 T1, T2, DerivedToBase) &&
2262 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002263 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002264
2265 // Build the candidate set directly in the initialization sequence
2266 // structure, so that it will persist if we fail.
2267 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2268 CandidateSet.clear();
2269
2270 // Determine whether we are allowed to call explicit constructors or
2271 // explicit conversion operators.
2272 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2273
2274 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002275 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2276 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002277 // The type we're converting to is a class type. Enumerate its constructors
2278 // to see if there is a suitable conversion.
2279 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
Douglas Gregor20093b42009-12-09 23:02:17 +00002280 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002281 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002282 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002283 NamedDecl *D = *Con;
2284 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2285
Douglas Gregor20093b42009-12-09 23:02:17 +00002286 // Find the constructor (which may be a template).
2287 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002288 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002289 if (ConstructorTmpl)
2290 Constructor = cast<CXXConstructorDecl>(
2291 ConstructorTmpl->getTemplatedDecl());
2292 else
John McCall9aa472c2010-03-19 07:35:19 +00002293 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002294
2295 if (!Constructor->isInvalidDecl() &&
2296 Constructor->isConvertingConstructor(AllowExplicit)) {
2297 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002298 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002299 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002300 &Initializer, 1, CandidateSet);
2301 else
John McCall9aa472c2010-03-19 07:35:19 +00002302 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002303 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002304 }
2305 }
2306 }
2307
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002308 const RecordType *T2RecordType = 0;
2309 if ((T2RecordType = T2->getAs<RecordType>()) &&
2310 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002311 // The type we're converting from is a class type, enumerate its conversion
2312 // functions.
2313 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2314
2315 // Determine the type we are converting to. If we are allowed to
2316 // convert to an rvalue, take the type that the destination type
2317 // refers to.
2318 QualType ToType = AllowRValues? cv1T1 : DestType;
2319
John McCalleec51cf2010-01-20 00:46:10 +00002320 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002321 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002322 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2323 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002324 NamedDecl *D = *I;
2325 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2326 if (isa<UsingShadowDecl>(D))
2327 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2328
2329 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2330 CXXConversionDecl *Conv;
2331 if (ConvTemplate)
2332 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2333 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002334 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002335
2336 // If the conversion function doesn't return a reference type,
2337 // it can't be considered for this conversion unless we're allowed to
2338 // consider rvalues.
2339 // FIXME: Do we need to make sure that we only consider conversion
2340 // candidates with reference-compatible results? That might be needed to
2341 // break recursion.
2342 if ((AllowExplicit || !Conv->isExplicit()) &&
2343 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2344 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002345 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002346 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002347 ToType, CandidateSet);
2348 else
John McCall9aa472c2010-03-19 07:35:19 +00002349 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002350 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002351 }
2352 }
2353 }
2354
2355 SourceLocation DeclLoc = Initializer->getLocStart();
2356
2357 // Perform overload resolution. If it fails, return the failed result.
2358 OverloadCandidateSet::iterator Best;
2359 if (OverloadingResult Result
2360 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2361 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002362
Douglas Gregor20093b42009-12-09 23:02:17 +00002363 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002364
2365 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002366 if (isa<CXXConversionDecl>(Function))
2367 T2 = Function->getResultType();
2368 else
2369 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002370
2371 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002372 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
John McCallb13b7372010-02-01 03:16:54 +00002373 T2.getNonReferenceType());
Eli Friedman03981012009-12-11 02:42:07 +00002374
2375 // Determine whether we need to perform derived-to-base or
2376 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002377 bool NewDerivedToBase = false;
2378 Sema::ReferenceCompareResult NewRefRelationship
2379 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2380 NewDerivedToBase);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002381 if (NewRefRelationship == Sema::Ref_Incompatible) {
2382 // If the type we've converted to is not reference-related to the
2383 // type we're looking for, then there is another conversion step
2384 // we need to perform to produce a temporary of the right type
2385 // that we'll be binding to.
2386 ImplicitConversionSequence ICS;
2387 ICS.setStandard();
2388 ICS.Standard = Best->FinalConversion;
2389 T2 = ICS.Standard.getToType(2);
2390 Sequence.AddConversionSequenceStep(ICS, T2);
2391 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002392 Sequence.AddDerivedToBaseCastStep(
2393 S.Context.getQualifiedType(T1,
2394 T2.getNonReferenceType().getQualifiers()),
2395 /*isLValue=*/true);
2396
2397 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2398 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2399
2400 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2401 return OR_Success;
2402}
2403
Sebastian Redl4680bf22010-06-30 18:13:39 +00002404/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor20093b42009-12-09 23:02:17 +00002405static void TryReferenceInitialization(Sema &S,
2406 const InitializedEntity &Entity,
2407 const InitializationKind &Kind,
2408 Expr *Initializer,
2409 InitializationSequence &Sequence) {
2410 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002411
Douglas Gregord6542d82009-12-22 15:35:07 +00002412 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002413 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002414 Qualifiers T1Quals;
2415 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002416 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002417 Qualifiers T2Quals;
2418 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002419 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002420
Douglas Gregor20093b42009-12-09 23:02:17 +00002421 // If the initializer is the address of an overloaded function, try
2422 // to resolve the overloaded function. If all goes well, T2 is the
2423 // type of the resulting function.
2424 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002425 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002426 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2427 T1,
John McCall6bb80172010-03-30 21:47:33 +00002428 false,
2429 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002430 if (!Fn) {
2431 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2432 return;
2433 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002434
John McCall6bb80172010-03-30 21:47:33 +00002435 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002436 cv2T2 = Fn->getType();
2437 T2 = cv2T2.getUnqualifiedType();
2438 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002439
Douglas Gregor20093b42009-12-09 23:02:17 +00002440 // Compute some basic properties of the types and the initializer.
2441 bool isLValueRef = DestType->isLValueReferenceType();
2442 bool isRValueRef = !isLValueRef;
2443 bool DerivedToBase = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002444 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002445 Sema::ReferenceCompareResult RefRelationship
2446 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002447
Douglas Gregor20093b42009-12-09 23:02:17 +00002448 // C++0x [dcl.init.ref]p5:
2449 // A reference to type "cv1 T1" is initialized by an expression of type
2450 // "cv2 T2" as follows:
2451 //
2452 // - If the reference is an lvalue reference and the initializer
2453 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002454 // Note the analogous bullet points for rvlaue refs to functions. Because
2455 // there are no function rvalues in C++, rvalue refs to functions are treated
2456 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002457 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002458 bool T1Function = T1->isFunctionType();
2459 if (isLValueRef || T1Function) {
2460 if (InitCategory.isLValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002461 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2462 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2463 // reference-compatible with "cv2 T2," or
2464 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002465 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002466 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002467 // can occur. However, we do pay attention to whether it is a bit-field
2468 // to decide whether we're actually binding to a temporary created from
2469 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002470 if (DerivedToBase)
2471 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002472 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002473 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002474 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002475 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002476 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002477 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002478 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002479 return;
2480 }
2481
2482 // - has a class type (i.e., T2 is a class type), where T1 is not
2483 // reference-related to T2, and can be implicitly converted to an
2484 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2485 // with "cv3 T3" (this conversion is selected by enumerating the
2486 // applicable conversion functions (13.3.1.6) and choosing the best
2487 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002488 // If we have an rvalue ref to function type here, the rhs must be
2489 // an rvalue.
2490 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2491 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002492 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2493 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002494 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002495 Sequence);
2496 if (ConvOvlResult == OR_Success)
2497 return;
John McCall1d318332010-01-12 00:44:57 +00002498 if (ConvOvlResult != OR_No_Viable_Function) {
2499 Sequence.SetOverloadFailure(
2500 InitializationSequence::FK_ReferenceInitOverloadFailed,
2501 ConvOvlResult);
2502 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002503 }
2504 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002505
Douglas Gregor20093b42009-12-09 23:02:17 +00002506 // - Otherwise, the reference shall be an lvalue reference to a
2507 // non-volatile const type (i.e., cv1 shall be const), or the reference
2508 // shall be an rvalue reference and the initializer expression shall
Sebastian Redl4680bf22010-06-30 18:13:39 +00002509 // be an rvalue or have a function type.
2510 // We handled the function type stuff above.
Douglas Gregoref06e242010-01-29 19:39:15 +00002511 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redl4680bf22010-06-30 18:13:39 +00002512 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002513 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2514 Sequence.SetOverloadFailure(
2515 InitializationSequence::FK_ReferenceInitOverloadFailed,
2516 ConvOvlResult);
2517 else if (isLValueRef)
Sebastian Redl4680bf22010-06-30 18:13:39 +00002518 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002519 ? (RefRelationship == Sema::Ref_Related
2520 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2521 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2522 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2523 else
2524 Sequence.SetFailed(
2525 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002526
Douglas Gregor20093b42009-12-09 23:02:17 +00002527 return;
2528 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002529
2530 // - [If T1 is not a function type], if T2 is a class type and
2531 if (!T1Function && T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002532 // - the initializer expression is an rvalue and "cv1 T1" is
2533 // reference-compatible with "cv2 T2", or
Sebastian Redl4680bf22010-06-30 18:13:39 +00002534 if (InitCategory.isRValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002535 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002536 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2537 // compiler the freedom to perform a copy here or bind to the
2538 // object, while C++0x requires that we bind directly to the
2539 // object. Hence, we always bind to the object without making an
2540 // extra copy. However, in C++03 requires that we check for the
2541 // presence of a suitable copy constructor:
2542 //
2543 // The constructor that would be used to make the copy shall
2544 // be callable whether or not the copy is actually done.
2545 if (!S.getLangOptions().CPlusPlus0x)
2546 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2547
Douglas Gregor20093b42009-12-09 23:02:17 +00002548 if (DerivedToBase)
2549 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002550 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002551 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002552 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002553 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2554 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2555 return;
2556 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002557
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 // - T1 is not reference-related to T2 and the initializer expression
2559 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2560 // conversion is selected by enumerating the applicable conversion
2561 // functions (13.3.1.6) and choosing the best one through overload
2562 // resolution (13.3)),
2563 if (RefRelationship == Sema::Ref_Incompatible) {
2564 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2565 Kind, Initializer,
2566 /*AllowRValues=*/true,
2567 Sequence);
2568 if (ConvOvlResult)
2569 Sequence.SetOverloadFailure(
2570 InitializationSequence::FK_ReferenceInitOverloadFailed,
2571 ConvOvlResult);
2572
2573 return;
2574 }
2575
2576 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2577 return;
2578 }
2579
2580 // - If the initializer expression is an rvalue, with T2 an array type,
2581 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2582 // is bound to the object represented by the rvalue (see 3.10).
2583 // FIXME: How can an array type be reference-compatible with anything?
2584 // Don't we mean the element types of T1 and T2?
2585
2586 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2587 // from the initializer expression using the rules for a non-reference
2588 // copy initialization (8.5). The reference is then bound to the
2589 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002590
Douglas Gregor20093b42009-12-09 23:02:17 +00002591 // Determine whether we are allowed to call explicit constructors or
2592 // explicit conversion operators.
2593 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002594
2595 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2596
2597 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2598 /*SuppressUserConversions*/ false,
2599 AllowExplicit,
2600 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002601 // FIXME: Use the conversion function set stored in ICS to turn
2602 // this into an overloading ambiguity diagnostic. However, we need
2603 // to keep that set as an OverloadCandidateSet rather than as some
2604 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002605 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2606 Sequence.SetOverloadFailure(
2607 InitializationSequence::FK_ReferenceInitOverloadFailed,
2608 ConvOvlResult);
2609 else
2610 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002611 return;
2612 }
2613
2614 // [...] If T1 is reference-related to T2, cv1 must be the
2615 // same cv-qualification as, or greater cv-qualification
2616 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002617 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2618 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002619 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002620 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002621 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2622 return;
2623 }
2624
Douglas Gregor20093b42009-12-09 23:02:17 +00002625 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2626 return;
2627}
2628
2629/// \brief Attempt character array initialization from a string literal
2630/// (C++ [dcl.init.string], C99 6.7.8).
2631static void TryStringLiteralInitialization(Sema &S,
2632 const InitializedEntity &Entity,
2633 const InitializationKind &Kind,
2634 Expr *Initializer,
2635 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002636 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002637 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002638}
2639
Douglas Gregor20093b42009-12-09 23:02:17 +00002640/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2641/// enumerates the constructors of the initialized entity and performs overload
2642/// resolution to select the best.
2643static void TryConstructorInitialization(Sema &S,
2644 const InitializedEntity &Entity,
2645 const InitializationKind &Kind,
2646 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002647 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002648 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002649 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002650
2651 // Build the candidate set directly in the initialization sequence
2652 // structure, so that it will persist if we fail.
2653 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2654 CandidateSet.clear();
2655
2656 // Determine whether we are allowed to call explicit constructors or
2657 // explicit conversion operators.
2658 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2659 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002660 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002661
2662 // The type we're constructing needs to be complete.
2663 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002664 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002665 return;
2666 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002667
2668 // The type we're converting to is a class type. Enumerate its constructors
2669 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002670 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2671 assert(DestRecordType && "Constructor initialization requires record type");
2672 CXXRecordDecl *DestRecordDecl
2673 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2674
Douglas Gregor51c56d62009-12-14 20:49:26 +00002675 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002676 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002677 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002678 NamedDecl *D = *Con;
2679 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002680 bool SuppressUserConversions = false;
2681
Douglas Gregor51c56d62009-12-14 20:49:26 +00002682 // Find the constructor (which may be a template).
2683 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002684 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002685 if (ConstructorTmpl)
2686 Constructor = cast<CXXConstructorDecl>(
2687 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002688 else {
John McCall9aa472c2010-03-19 07:35:19 +00002689 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002690
2691 // If we're performing copy initialization using a copy constructor, we
2692 // suppress user-defined conversions on the arguments.
2693 // FIXME: Move constructors?
2694 if (Kind.getKind() == InitializationKind::IK_Copy &&
2695 Constructor->isCopyConstructor())
2696 SuppressUserConversions = true;
2697 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002698
2699 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002700 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002701 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002702 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002703 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002704 Args, NumArgs, CandidateSet,
2705 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002706 else
John McCall9aa472c2010-03-19 07:35:19 +00002707 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002708 Args, NumArgs, CandidateSet,
2709 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002710 }
2711 }
2712
2713 SourceLocation DeclLoc = Kind.getLocation();
2714
2715 // Perform overload resolution. If it fails, return the failed result.
2716 OverloadCandidateSet::iterator Best;
2717 if (OverloadingResult Result
2718 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2719 Sequence.SetOverloadFailure(
2720 InitializationSequence::FK_ConstructorOverloadFailed,
2721 Result);
2722 return;
2723 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002724
2725 // C++0x [dcl.init]p6:
2726 // If a program calls for the default initialization of an object
2727 // of a const-qualified type T, T shall be a class type with a
2728 // user-provided default constructor.
2729 if (Kind.getKind() == InitializationKind::IK_Default &&
2730 Entity.getType().isConstQualified() &&
2731 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2732 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2733 return;
2734 }
2735
Douglas Gregor51c56d62009-12-14 20:49:26 +00002736 // Add the constructor initialization step. Any cv-qualification conversion is
2737 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002738 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002739 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002740 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002741 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002742}
2743
Douglas Gregor71d17402009-12-15 00:01:57 +00002744/// \brief Attempt value initialization (C++ [dcl.init]p7).
2745static void TryValueInitialization(Sema &S,
2746 const InitializedEntity &Entity,
2747 const InitializationKind &Kind,
2748 InitializationSequence &Sequence) {
2749 // C++ [dcl.init]p5:
2750 //
2751 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002752 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002753
2754 // -- if T is an array type, then each element is value-initialized;
2755 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2756 T = AT->getElementType();
2757
2758 if (const RecordType *RT = T->getAs<RecordType>()) {
2759 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2760 // -- if T is a class type (clause 9) with a user-declared
2761 // constructor (12.1), then the default constructor for T is
2762 // called (and the initialization is ill-formed if T has no
2763 // accessible default constructor);
2764 //
2765 // FIXME: we really want to refer to a single subobject of the array,
2766 // but Entity doesn't have a way to capture that (yet).
2767 if (ClassDecl->hasUserDeclaredConstructor())
2768 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2769
Douglas Gregor16006c92009-12-16 18:50:27 +00002770 // -- if T is a (possibly cv-qualified) non-union class type
2771 // without a user-provided constructor, then the object is
2772 // zero-initialized and, if T’s implicitly-declared default
2773 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002774 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor63ef4642010-07-07 22:35:13 +00002775 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002776 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002777 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2778 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002779 }
2780 }
2781
Douglas Gregord6542d82009-12-22 15:35:07 +00002782 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002783 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2784}
2785
Douglas Gregor99a2e602009-12-16 01:38:02 +00002786/// \brief Attempt default initialization (C++ [dcl.init]p6).
2787static void TryDefaultInitialization(Sema &S,
2788 const InitializedEntity &Entity,
2789 const InitializationKind &Kind,
2790 InitializationSequence &Sequence) {
2791 assert(Kind.getKind() == InitializationKind::IK_Default);
2792
2793 // C++ [dcl.init]p6:
2794 // To default-initialize an object of type T means:
2795 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002796 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002797 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2798 DestType = Array->getElementType();
2799
2800 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2801 // constructor for T is called (and the initialization is ill-formed if
2802 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002803 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002804 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2805 Sequence);
2806 }
2807
2808 // - otherwise, no initialization is performed.
2809 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2810
2811 // If a program calls for the default initialization of an object of
2812 // a const-qualified type T, T shall be a class type with a user-provided
2813 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002814 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002815 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2816}
2817
Douglas Gregor20093b42009-12-09 23:02:17 +00002818/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2819/// which enumerates all conversion functions and performs overload resolution
2820/// to select the best.
2821static void TryUserDefinedConversion(Sema &S,
2822 const InitializedEntity &Entity,
2823 const InitializationKind &Kind,
2824 Expr *Initializer,
2825 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002826 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2827
Douglas Gregord6542d82009-12-22 15:35:07 +00002828 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002829 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2830 QualType SourceType = Initializer->getType();
2831 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2832 "Must have a class type to perform a user-defined conversion");
2833
2834 // Build the candidate set directly in the initialization sequence
2835 // structure, so that it will persist if we fail.
2836 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2837 CandidateSet.clear();
2838
2839 // Determine whether we are allowed to call explicit constructors or
2840 // explicit conversion operators.
2841 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2842
2843 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2844 // The type we're converting to is a class type. Enumerate its constructors
2845 // to see if there is a suitable conversion.
2846 CXXRecordDecl *DestRecordDecl
2847 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2848
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002849 // Try to complete the type we're converting to.
2850 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002851 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002852 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002853 Con != ConEnd; ++Con) {
2854 NamedDecl *D = *Con;
2855 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002856
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002857 // Find the constructor (which may be a template).
2858 CXXConstructorDecl *Constructor = 0;
2859 FunctionTemplateDecl *ConstructorTmpl
2860 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002861 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002862 Constructor = cast<CXXConstructorDecl>(
2863 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002864 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002865 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002866
2867 if (!Constructor->isInvalidDecl() &&
2868 Constructor->isConvertingConstructor(AllowExplicit)) {
2869 if (ConstructorTmpl)
2870 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2871 /*ExplicitArgs*/ 0,
2872 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002873 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002874 else
2875 S.AddOverloadCandidate(Constructor, FoundDecl,
2876 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002877 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002878 }
2879 }
2880 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002881 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002882
2883 SourceLocation DeclLoc = Initializer->getLocStart();
2884
Douglas Gregor4a520a22009-12-14 17:27:33 +00002885 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2886 // The type we're converting from is a class type, enumerate its conversion
2887 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002888
Eli Friedman33c2da92009-12-20 22:12:03 +00002889 // We can only enumerate the conversion functions for a complete type; if
2890 // the type isn't complete, simply skip this step.
2891 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2892 CXXRecordDecl *SourceRecordDecl
2893 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002894
John McCalleec51cf2010-01-20 00:46:10 +00002895 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002896 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002897 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002898 E = Conversions->end();
2899 I != E; ++I) {
2900 NamedDecl *D = *I;
2901 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2902 if (isa<UsingShadowDecl>(D))
2903 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2904
2905 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2906 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002907 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002908 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002909 else
John McCall32daa422010-03-31 01:36:47 +00002910 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00002911
2912 if (AllowExplicit || !Conv->isExplicit()) {
2913 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002914 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002915 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002916 CandidateSet);
2917 else
John McCall9aa472c2010-03-19 07:35:19 +00002918 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00002919 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002920 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002921 }
2922 }
2923 }
2924
Douglas Gregor4a520a22009-12-14 17:27:33 +00002925 // Perform overload resolution. If it fails, return the failed result.
2926 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002927 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002928 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2929 Sequence.SetOverloadFailure(
2930 InitializationSequence::FK_UserConversionOverloadFailed,
2931 Result);
2932 return;
2933 }
John McCall1d318332010-01-12 00:44:57 +00002934
Douglas Gregor4a520a22009-12-14 17:27:33 +00002935 FunctionDecl *Function = Best->Function;
2936
2937 if (isa<CXXConstructorDecl>(Function)) {
2938 // Add the user-defined conversion step. Any cv-qualification conversion is
2939 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00002940 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002941 return;
2942 }
2943
2944 // Add the user-defined conversion step that calls the conversion function.
2945 QualType ConvType = Function->getResultType().getNonReferenceType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002946 if (ConvType->getAs<RecordType>()) {
2947 // If we're converting to a class type, there may be an copy if
2948 // the resulting temporary object (possible to create an object of
2949 // a base class type). That copy is not a separate conversion, so
2950 // we just make a note of the actual destination type (possibly a
2951 // base class of the type returned by the conversion function) and
2952 // let the user-defined conversion step handle the conversion.
2953 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
2954 return;
2955 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002956
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002957 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
2958
2959 // If the conversion following the call to the conversion function
2960 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00002961 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2962 Best->FinalConversion.Third) {
2963 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002964 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002965 ICS.Standard = Best->FinalConversion;
2966 Sequence.AddConversionSequenceStep(ICS, DestType);
2967 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002968}
2969
John McCall369371c2010-06-04 02:29:22 +00002970bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
2971 const InitializedEntity &Entity,
2972 Expr *Initializer,
2973 bool SuppressUserConversions,
2974 bool AllowExplicitConversions,
2975 bool InOverloadResolution) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002976 ImplicitConversionSequence ICS
John McCall369371c2010-06-04 02:29:22 +00002977 = TryImplicitConversion(Initializer, Entity.getType(),
2978 SuppressUserConversions,
2979 AllowExplicitConversions,
2980 InOverloadResolution);
2981 if (ICS.isBad()) return true;
2982
2983 // Perform the actual conversion.
Douglas Gregord6542d82009-12-22 15:35:07 +00002984 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
John McCall369371c2010-06-04 02:29:22 +00002985 return false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002986}
2987
2988InitializationSequence::InitializationSequence(Sema &S,
2989 const InitializedEntity &Entity,
2990 const InitializationKind &Kind,
2991 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00002992 unsigned NumArgs)
2993 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002994 ASTContext &Context = S.Context;
2995
2996 // C++0x [dcl.init]p16:
2997 // The semantics of initializers are as follows. The destination type is
2998 // the type of the object or reference being initialized and the source
2999 // type is the type of the initializer expression. The source type is not
3000 // defined when the initializer is a braced-init-list or when it is a
3001 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003002 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003003
3004 if (DestType->isDependentType() ||
3005 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3006 SequenceKind = DependentSequence;
3007 return;
3008 }
3009
3010 QualType SourceType;
3011 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003012 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003013 Initializer = Args[0];
3014 if (!isa<InitListExpr>(Initializer))
3015 SourceType = Initializer->getType();
3016 }
3017
3018 // - If the initializer is a braced-init-list, the object is
3019 // list-initialized (8.5.4).
3020 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3021 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003022 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003023 }
3024
3025 // - If the destination type is a reference type, see 8.5.3.
3026 if (DestType->isReferenceType()) {
3027 // C++0x [dcl.init.ref]p1:
3028 // A variable declared to be a T& or T&&, that is, "reference to type T"
3029 // (8.3.2), shall be initialized by an object, or function, of type T or
3030 // by an object that can be converted into a T.
3031 // (Therefore, multiple arguments are not permitted.)
3032 if (NumArgs != 1)
3033 SetFailed(FK_TooManyInitsForReference);
3034 else
3035 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3036 return;
3037 }
3038
3039 // - If the destination type is an array of characters, an array of
3040 // char16_t, an array of char32_t, or an array of wchar_t, and the
3041 // initializer is a string literal, see 8.5.2.
3042 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3043 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3044 return;
3045 }
3046
3047 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003048 if (Kind.getKind() == InitializationKind::IK_Value ||
3049 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003050 TryValueInitialization(S, Entity, Kind, *this);
3051 return;
3052 }
3053
Douglas Gregor99a2e602009-12-16 01:38:02 +00003054 // Handle default initialization.
3055 if (Kind.getKind() == InitializationKind::IK_Default){
3056 TryDefaultInitialization(S, Entity, Kind, *this);
3057 return;
3058 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003059
Douglas Gregor20093b42009-12-09 23:02:17 +00003060 // - Otherwise, if the destination type is an array, the program is
3061 // ill-formed.
3062 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3063 if (AT->getElementType()->isAnyCharacterType())
3064 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3065 else
3066 SetFailed(FK_ArrayNeedsInitList);
3067
3068 return;
3069 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003070
3071 // Handle initialization in C
3072 if (!S.getLangOptions().CPlusPlus) {
3073 setSequenceKind(CAssignment);
3074 AddCAssignmentStep(DestType);
3075 return;
3076 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003077
3078 // - If the destination type is a (possibly cv-qualified) class type:
3079 if (DestType->isRecordType()) {
3080 // - If the initialization is direct-initialization, or if it is
3081 // copy-initialization where the cv-unqualified version of the
3082 // source type is the same class as, or a derived class of, the
3083 // class of the destination, constructors are considered. [...]
3084 if (Kind.getKind() == InitializationKind::IK_Direct ||
3085 (Kind.getKind() == InitializationKind::IK_Copy &&
3086 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3087 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003088 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003089 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003090 // - Otherwise (i.e., for the remaining copy-initialization cases),
3091 // user-defined conversion sequences that can convert from the source
3092 // type to the destination type or (when a conversion function is
3093 // used) to a derived class thereof are enumerated as described in
3094 // 13.3.1.4, and the best one is chosen through overload resolution
3095 // (13.3).
3096 else
3097 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3098 return;
3099 }
3100
Douglas Gregor99a2e602009-12-16 01:38:02 +00003101 if (NumArgs > 1) {
3102 SetFailed(FK_TooManyInitsForScalar);
3103 return;
3104 }
3105 assert(NumArgs == 1 && "Zero-argument case handled above");
3106
Douglas Gregor20093b42009-12-09 23:02:17 +00003107 // - Otherwise, if the source type is a (possibly cv-qualified) class
3108 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003109 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003110 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3111 return;
3112 }
3113
3114 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003115 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003116 // conversions (Clause 4) will be used, if necessary, to convert the
3117 // initializer expression to the cv-unqualified version of the
3118 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003119 if (S.TryImplicitConversion(*this, Entity, Initializer,
3120 /*SuppressUserConversions*/ true,
3121 /*AllowExplicitConversions*/ false,
3122 /*InOverloadResolution*/ false))
3123 SetFailed(InitializationSequence::FK_ConversionFailed);
3124 else
3125 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003126}
3127
3128InitializationSequence::~InitializationSequence() {
3129 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3130 StepEnd = Steps.end();
3131 Step != StepEnd; ++Step)
3132 Step->Destroy();
3133}
3134
3135//===----------------------------------------------------------------------===//
3136// Perform initialization
3137//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003138static Sema::AssignmentAction
3139getAssignmentAction(const InitializedEntity &Entity) {
3140 switch(Entity.getKind()) {
3141 case InitializedEntity::EK_Variable:
3142 case InitializedEntity::EK_New:
3143 return Sema::AA_Initializing;
3144
3145 case InitializedEntity::EK_Parameter:
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003146 if (Entity.getDecl() &&
3147 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3148 return Sema::AA_Sending;
3149
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003150 return Sema::AA_Passing;
3151
3152 case InitializedEntity::EK_Result:
3153 return Sema::AA_Returning;
3154
3155 case InitializedEntity::EK_Exception:
3156 case InitializedEntity::EK_Base:
3157 llvm_unreachable("No assignment action for C++-specific initialization");
3158 break;
3159
3160 case InitializedEntity::EK_Temporary:
3161 // FIXME: Can we tell apart casting vs. converting?
3162 return Sema::AA_Casting;
3163
3164 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003165 case InitializedEntity::EK_ArrayElement:
3166 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003167 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003168 return Sema::AA_Initializing;
3169 }
3170
3171 return Sema::AA_Converting;
3172}
3173
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003174/// \brief Whether we should binding a created object as a temporary when
3175/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003176static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003177 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003178 case InitializedEntity::EK_ArrayElement:
3179 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003180 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003181 case InitializedEntity::EK_New:
3182 case InitializedEntity::EK_Variable:
3183 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003184 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003185 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003186 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003187 return false;
3188
3189 case InitializedEntity::EK_Parameter:
3190 case InitializedEntity::EK_Temporary:
3191 return true;
3192 }
3193
3194 llvm_unreachable("missed an InitializedEntity kind?");
3195}
3196
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003197/// \brief Whether the given entity, when initialized with an object
3198/// created for that initialization, requires destruction.
3199static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3200 switch (Entity.getKind()) {
3201 case InitializedEntity::EK_Member:
3202 case InitializedEntity::EK_Result:
3203 case InitializedEntity::EK_New:
3204 case InitializedEntity::EK_Base:
3205 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003206 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003207 return false;
3208
3209 case InitializedEntity::EK_Variable:
3210 case InitializedEntity::EK_Parameter:
3211 case InitializedEntity::EK_Temporary:
3212 case InitializedEntity::EK_ArrayElement:
3213 case InitializedEntity::EK_Exception:
3214 return true;
3215 }
3216
3217 llvm_unreachable("missed an InitializedEntity kind?");
3218}
3219
Douglas Gregor523d46a2010-04-18 07:40:54 +00003220/// \brief Make a (potentially elidable) temporary copy of the object
3221/// provided by the given initializer by calling the appropriate copy
3222/// constructor.
3223///
3224/// \param S The Sema object used for type-checking.
3225///
3226/// \param T The type of the temporary object, which must either by
3227/// the type of the initializer expression or a superclass thereof.
3228///
3229/// \param Enter The entity being initialized.
3230///
3231/// \param CurInit The initializer expression.
3232///
3233/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3234/// is permitted in C++03 (but not C++0x) when binding a reference to
3235/// an rvalue.
3236///
3237/// \returns An expression that copies the initializer expression into
3238/// a temporary object, or an error expression if a copy could not be
3239/// created.
Douglas Gregor2f599792010-04-02 18:24:57 +00003240static Sema::OwningExprResult CopyObject(Sema &S,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003241 QualType T,
Douglas Gregor2f599792010-04-02 18:24:57 +00003242 const InitializedEntity &Entity,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003243 Sema::OwningExprResult CurInit,
3244 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003245 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003246 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003247 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003248 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003249 Class = cast<CXXRecordDecl>(Record->getDecl());
3250 if (!Class)
3251 return move(CurInit);
3252
3253 // C++0x [class.copy]p34:
3254 // When certain criteria are met, an implementation is allowed to
3255 // omit the copy/move construction of a class object, even if the
3256 // copy/move constructor and/or destructor for the object have
3257 // side effects. [...]
3258 // - when a temporary class object that has not been bound to a
3259 // reference (12.2) would be copied/moved to a class object
3260 // with the same cv-unqualified type, the copy/move operation
3261 // can be omitted by constructing the temporary object
3262 // directly into the target of the omitted copy/move
3263 //
3264 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003265 // elision for return statements and throw expressions are handled as part
3266 // of constructor initialization, while copy elision for exception handlers
3267 // is handled by the run-time.
Douglas Gregor2f599792010-04-02 18:24:57 +00003268 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregor523d46a2010-04-18 07:40:54 +00003269 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003270 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003271 switch (Entity.getKind()) {
3272 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003273 Loc = Entity.getReturnLoc();
3274 break;
3275
3276 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003277 Loc = Entity.getThrowLoc();
3278 break;
3279
3280 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003281 Loc = Entity.getDecl()->getLocation();
3282 break;
3283
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003284 case InitializedEntity::EK_ArrayElement:
3285 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003286 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003287 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003288 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003289 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003290 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003291 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003292 Loc = CurInitExpr->getLocStart();
3293 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003294 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003295
3296 // Make sure that the type we are copying is complete.
3297 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3298 return move(CurInit);
3299
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003300 // Perform overload resolution using the class's copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003301 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003302 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003303 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003304 Con != ConEnd; ++Con) {
Douglas Gregor2f599792010-04-02 18:24:57 +00003305 // Only consider copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003306 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3307 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor153b3ba2010-04-18 02:16:12 +00003308 !Constructor->isCopyConstructor() ||
3309 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003310 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003311
3312 DeclAccessPair FoundDecl
3313 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3314 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003315 &CurInitExpr, 1, CandidateSet);
Douglas Gregor2f599792010-04-02 18:24:57 +00003316 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003317
3318 OverloadCandidateSet::iterator Best;
3319 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3320 case OR_Success:
3321 break;
3322
3323 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003324 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3325 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3326 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003327 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003328 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003329 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3330 &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003331 if (!IsExtraneousCopy || S.isSFINAEContext())
3332 return S.ExprError();
3333 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003334
3335 case OR_Ambiguous:
3336 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003337 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003338 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003339 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3340 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003341 return S.ExprError();
3342
3343 case OR_Deleted:
3344 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003345 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003346 << CurInitExpr->getSourceRange();
3347 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3348 << Best->Function->isDeleted();
3349 return S.ExprError();
3350 }
3351
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003352 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3353 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3354 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003355
Anders Carlsson9a68a672010-04-21 18:47:17 +00003356 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003357 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003358
3359 if (IsExtraneousCopy) {
3360 // If this is a totally extraneous copy for C++03 reference
3361 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003362 // expression. We don't generate an (elided) copy operation here
3363 // because doing so would require us to pass down a flag to avoid
3364 // infinite recursion, where each step adds another extraneous,
3365 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003366
Douglas Gregor2559a702010-04-18 07:57:34 +00003367 // Instantiate the default arguments of any extra parameters in
3368 // the selected copy constructor, as if we were going to create a
3369 // proper call to the copy constructor.
3370 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3371 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3372 if (S.RequireCompleteType(Loc, Parm->getType(),
3373 S.PDiag(diag::err_call_incomplete_argument)))
3374 break;
3375
3376 // Build the default argument expression; we don't actually care
3377 // if this succeeds or not, because this routine will complain
3378 // if there was a problem.
3379 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3380 }
3381
Douglas Gregor523d46a2010-04-18 07:40:54 +00003382 return S.Owned(CurInitExpr);
3383 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003384
3385 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003386 // constructor call (we might have derived-to-base conversions, or
3387 // the copy constructor may have default arguments).
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003388 if (S.CompleteConstructorCall(Constructor,
3389 Sema::MultiExprArg(S,
3390 (void **)&CurInitExpr,
3391 1),
3392 Loc, ConstructorArgs))
3393 return S.ExprError();
3394
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003395 // Actually perform the constructor call.
3396 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
3397 move_arg(ConstructorArgs));
3398
3399 // If we're supposed to bind temporaries, do so.
3400 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3401 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3402 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003403}
Douglas Gregor20093b42009-12-09 23:02:17 +00003404
Douglas Gregora41a8c52010-04-22 00:20:18 +00003405void InitializationSequence::PrintInitLocationNote(Sema &S,
3406 const InitializedEntity &Entity) {
3407 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3408 if (Entity.getDecl()->getLocation().isInvalid())
3409 return;
3410
3411 if (Entity.getDecl()->getDeclName())
3412 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3413 << Entity.getDecl()->getDeclName();
3414 else
3415 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3416 }
3417}
3418
Douglas Gregor20093b42009-12-09 23:02:17 +00003419Action::OwningExprResult
3420InitializationSequence::Perform(Sema &S,
3421 const InitializedEntity &Entity,
3422 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003423 Action::MultiExprArg Args,
3424 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003425 if (SequenceKind == FailedSequence) {
3426 unsigned NumArgs = Args.size();
3427 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3428 return S.ExprError();
3429 }
3430
3431 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003432 // If the declaration is a non-dependent, incomplete array type
3433 // that has an initializer, then its type will be completed once
3434 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003435 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003436 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003437 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003438 if (const IncompleteArrayType *ArrayT
3439 = S.Context.getAsIncompleteArrayType(DeclType)) {
3440 // FIXME: We don't currently have the ability to accurately
3441 // compute the length of an initializer list without
3442 // performing full type-checking of the initializer list
3443 // (since we have to determine where braces are implicitly
3444 // introduced and such). So, we fall back to making the array
3445 // type a dependently-sized array type with no specified
3446 // bound.
3447 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3448 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003449
Douglas Gregord87b61f2009-12-10 17:56:55 +00003450 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003451 if (DeclaratorDecl *DD = Entity.getDecl()) {
3452 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3453 TypeLoc TL = TInfo->getTypeLoc();
3454 if (IncompleteArrayTypeLoc *ArrayLoc
3455 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3456 Brackets = ArrayLoc->getBracketsRange();
3457 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003458 }
3459
3460 *ResultType
3461 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3462 /*NumElts=*/0,
3463 ArrayT->getSizeModifier(),
3464 ArrayT->getIndexTypeCVRQualifiers(),
3465 Brackets);
3466 }
3467
3468 }
3469 }
3470
Eli Friedman08544622009-12-22 02:35:53 +00003471 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003472 return Sema::OwningExprResult(S, Args.release()[0]);
3473
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003474 if (Args.size() == 0)
3475 return S.Owned((Expr *)0);
3476
Douglas Gregor20093b42009-12-09 23:02:17 +00003477 unsigned NumArgs = Args.size();
3478 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3479 SourceLocation(),
3480 (Expr **)Args.release(),
3481 NumArgs,
3482 SourceLocation()));
3483 }
3484
Douglas Gregor99a2e602009-12-16 01:38:02 +00003485 if (SequenceKind == NoInitialization)
3486 return S.Owned((Expr *)0);
3487
Douglas Gregord6542d82009-12-22 15:35:07 +00003488 QualType DestType = Entity.getType().getNonReferenceType();
3489 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003490 // the same as Entity.getDecl()->getType() in cases involving type merging,
3491 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003492 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003493 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003494 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003495
Douglas Gregor99a2e602009-12-16 01:38:02 +00003496 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3497
3498 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3499
3500 // For initialization steps that start with a single initializer,
3501 // grab the only argument out the Args and place it into the "current"
3502 // initializer.
3503 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003504 case SK_ResolveAddressOfOverloadedFunction:
3505 case SK_CastDerivedToBaseRValue:
3506 case SK_CastDerivedToBaseLValue:
3507 case SK_BindReference:
3508 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003509 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003510 case SK_UserConversion:
3511 case SK_QualificationConversionLValue:
3512 case SK_QualificationConversionRValue:
3513 case SK_ConversionSequence:
3514 case SK_ListInitialization:
3515 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003516 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003517 assert(Args.size() == 1);
3518 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3519 if (CurInit.isInvalid())
3520 return S.ExprError();
3521 break;
3522
3523 case SK_ConstructorInitialization:
3524 case SK_ZeroInitialization:
3525 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003526 }
3527
3528 // Walk through the computed steps for the initialization sequence,
3529 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003530 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003531 for (step_iterator Step = step_begin(), StepEnd = step_end();
3532 Step != StepEnd; ++Step) {
3533 if (CurInit.isInvalid())
3534 return S.ExprError();
3535
3536 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003537 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003538
3539 switch (Step->Kind) {
3540 case SK_ResolveAddressOfOverloadedFunction:
3541 // Overload resolution determined which function invoke; update the
3542 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003543 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003544 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003545 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003546 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003547 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003548 break;
3549
3550 case SK_CastDerivedToBaseRValue:
3551 case SK_CastDerivedToBaseLValue: {
3552 // We have a derived-to-base cast that produces either an rvalue or an
3553 // lvalue. Perform that cast.
3554
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003555 CXXBaseSpecifierArray BasePath;
3556
Douglas Gregor20093b42009-12-09 23:02:17 +00003557 // Casts to inaccessible base classes are allowed with C-style casts.
3558 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3559 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3560 CurInitExpr->getLocStart(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003561 CurInitExpr->getSourceRange(),
3562 &BasePath, IgnoreBaseAccess))
Douglas Gregor20093b42009-12-09 23:02:17 +00003563 return S.ExprError();
3564
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003565 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3566 QualType T = SourceType;
3567 if (const PointerType *Pointer = T->getAs<PointerType>())
3568 T = Pointer->getPointeeType();
3569 if (const RecordType *RecordTy = T->getAs<RecordType>())
3570 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3571 cast<CXXRecordDecl>(RecordTy->getDecl()));
3572 }
3573
Douglas Gregor20093b42009-12-09 23:02:17 +00003574 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3575 CastExpr::CK_DerivedToBase,
Anders Carlsson88465d32010-04-23 22:18:37 +00003576 (Expr*)CurInit.release(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003577 BasePath,
Douglas Gregor20093b42009-12-09 23:02:17 +00003578 Step->Kind == SK_CastDerivedToBaseLValue));
3579 break;
3580 }
3581
3582 case SK_BindReference:
3583 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3584 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3585 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003586 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003587 << BitField->getDeclName()
3588 << CurInitExpr->getSourceRange();
3589 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3590 return S.ExprError();
3591 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003592
Anders Carlsson09380262010-01-31 17:18:49 +00003593 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003594 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003595 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3596 << Entity.getType().isVolatileQualified()
3597 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003598 PrintInitLocationNote(S, Entity);
Anders Carlsson09380262010-01-31 17:18:49 +00003599 return S.ExprError();
3600 }
3601
Douglas Gregor20093b42009-12-09 23:02:17 +00003602 // Reference binding does not have any corresponding ASTs.
3603
3604 // Check exception specifications
3605 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3606 return S.ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003607
Douglas Gregor20093b42009-12-09 23:02:17 +00003608 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003609
Douglas Gregor20093b42009-12-09 23:02:17 +00003610 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003611 // Reference binding does not have any corresponding ASTs.
3612
Douglas Gregor20093b42009-12-09 23:02:17 +00003613 // Check exception specifications
3614 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3615 return S.ExprError();
3616
Douglas Gregor20093b42009-12-09 23:02:17 +00003617 break;
3618
Douglas Gregor523d46a2010-04-18 07:40:54 +00003619 case SK_ExtraneousCopyToTemporary:
3620 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3621 /*IsExtraneousCopy=*/true);
3622 break;
3623
Douglas Gregor20093b42009-12-09 23:02:17 +00003624 case SK_UserConversion: {
3625 // We have a user-defined conversion that invokes either a constructor
3626 // or a conversion function.
3627 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003628 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003629 FunctionDecl *Fn = Step->Function.Function;
3630 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003631 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003632 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003633 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003634 // Build a call to the selected constructor.
3635 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3636 SourceLocation Loc = CurInitExpr->getLocStart();
3637 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003638
Douglas Gregor20093b42009-12-09 23:02:17 +00003639 // Determine the arguments required to actually perform the constructor
3640 // call.
3641 if (S.CompleteConstructorCall(Constructor,
3642 Sema::MultiExprArg(S,
3643 (void **)&CurInitExpr,
3644 1),
3645 Loc, ConstructorArgs))
3646 return S.ExprError();
3647
3648 // Build the an expression that constructs a temporary.
3649 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3650 move_arg(ConstructorArgs));
3651 if (CurInit.isInvalid())
3652 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003653
Anders Carlsson9a68a672010-04-21 18:47:17 +00003654 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003655 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003656 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor20093b42009-12-09 23:02:17 +00003657
3658 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003659 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3660 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3661 S.IsDerivedFrom(SourceType, Class))
3662 IsCopy = true;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003663
3664 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003665 } else {
3666 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003667 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003668 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003669 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003670 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003671 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003672
Douglas Gregor20093b42009-12-09 23:02:17 +00003673 // FIXME: Should we move this initialization into a separate
3674 // derived-to-base conversion? I believe the answer is "no", because
3675 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003676 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003677 FoundFn, Conversion))
Douglas Gregor20093b42009-12-09 23:02:17 +00003678 return S.ExprError();
3679
3680 // Do a little dance to make sure that CurInit has the proper
3681 // pointer.
3682 CurInit.release();
3683
3684 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003685 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3686 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003687 if (CurInit.isInvalid() || !CurInit.get())
3688 return S.ExprError();
3689
3690 CastKind = CastExpr::CK_UserDefinedConversion;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003691
3692 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003693 }
3694
Douglas Gregor2f599792010-04-02 18:24:57 +00003695 bool RequiresCopy = !IsCopy &&
3696 getKind() != InitializationSequence::ReferenceBinding;
3697 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003698 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003699 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3700 CurInitExpr = static_cast<Expr *>(CurInit.get());
3701 QualType T = CurInitExpr->getType();
3702 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00003703 CXXDestructorDecl *Destructor
3704 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003705 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3706 S.PDiag(diag::err_access_dtor_temp) << T);
3707 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3708 }
3709 }
3710
Douglas Gregor20093b42009-12-09 23:02:17 +00003711 CurInitExpr = CurInit.takeAs<Expr>();
3712 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003713 CastKind,
3714 CurInitExpr,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003715 CXXBaseSpecifierArray(),
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003716 IsLvalue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003717
Douglas Gregor2f599792010-04-02 18:24:57 +00003718 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003719 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3720 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003721
Douglas Gregor20093b42009-12-09 23:02:17 +00003722 break;
3723 }
3724
3725 case SK_QualificationConversionLValue:
3726 case SK_QualificationConversionRValue:
3727 // Perform a qualification conversion; these can never go wrong.
3728 S.ImpCastExprToType(CurInitExpr, Step->Type,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003729 CastExpr::CK_NoOp,
Douglas Gregor20093b42009-12-09 23:02:17 +00003730 Step->Kind == SK_QualificationConversionLValue);
3731 CurInit.release();
3732 CurInit = S.Owned(CurInitExpr);
3733 break;
3734
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003735 case SK_ConversionSequence: {
3736 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3737
3738 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3739 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor20093b42009-12-09 23:02:17 +00003740 return S.ExprError();
3741
3742 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003743 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003744 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003745 }
3746
Douglas Gregord87b61f2009-12-10 17:56:55 +00003747 case SK_ListInitialization: {
3748 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3749 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003750 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003751 return S.ExprError();
3752
3753 CurInit.release();
3754 CurInit = S.Owned(InitList);
3755 break;
3756 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003757
3758 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003759 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003760 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003761 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003762
Douglas Gregor51c56d62009-12-14 20:49:26 +00003763 // Build a call to the selected constructor.
3764 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3765 SourceLocation Loc = Kind.getLocation();
3766
3767 // Determine the arguments required to actually perform the constructor
3768 // call.
3769 if (S.CompleteConstructorCall(Constructor, move(Args),
3770 Loc, ConstructorArgs))
3771 return S.ExprError();
3772
Douglas Gregord6e44a32010-04-16 22:09:46 +00003773 // Build the expression that constructs a temporary.
Douglas Gregor91be6f52010-03-02 17:18:33 +00003774 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003775 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003776 (Kind.getKind() == InitializationKind::IK_Direct ||
3777 Kind.getKind() == InitializationKind::IK_Value)) {
3778 // An explicitly-constructed temporary, e.g., X(1, 2).
3779 unsigned NumExprs = ConstructorArgs.size();
3780 Expr **Exprs = (Expr **)ConstructorArgs.take();
3781 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3782 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3783 Constructor,
3784 Entity.getType(),
3785 Kind.getLocation(),
3786 Exprs,
3787 NumExprs,
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003788 Kind.getParenRange().getEnd(),
3789 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003790 } else {
3791 CXXConstructExpr::ConstructionKind ConstructKind =
3792 CXXConstructExpr::CK_Complete;
3793
3794 if (Entity.getKind() == InitializedEntity::EK_Base) {
3795 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3796 CXXConstructExpr::CK_VirtualBase :
3797 CXXConstructExpr::CK_NonVirtualBase;
3798 }
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003799
3800 // If the entity allows NRVO, mark the construction as elidable
3801 // unconditionally.
3802 if (Entity.allowsNRVO())
3803 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3804 Constructor, /*Elidable=*/true,
3805 move_arg(ConstructorArgs),
3806 ConstructorInitRequiresZeroInit,
3807 ConstructKind);
3808 else
3809 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3810 Constructor,
3811 move_arg(ConstructorArgs),
3812 ConstructorInitRequiresZeroInit,
3813 ConstructKind);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003814 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003815 if (CurInit.isInvalid())
3816 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003817
3818 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00003819 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003820 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003821 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003822
Douglas Gregor2f599792010-04-02 18:24:57 +00003823 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003824 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003825
Douglas Gregor51c56d62009-12-14 20:49:26 +00003826 break;
3827 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003828
3829 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003830 step_iterator NextStep = Step;
3831 ++NextStep;
3832 if (NextStep != StepEnd &&
3833 NextStep->Kind == SK_ConstructorInitialization) {
3834 // The need for zero-initialization is recorded directly into
3835 // the call to the object's constructor within the next step.
3836 ConstructorInitRequiresZeroInit = true;
3837 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3838 S.getLangOptions().CPlusPlus &&
3839 !Kind.isImplicitValueInit()) {
Douglas Gregor016a4a92010-07-07 22:43:56 +00003840 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(Step->Type,
Douglas Gregor71d17402009-12-15 00:01:57 +00003841 Kind.getRange().getBegin(),
3842 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003843 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003844 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003845 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003846 break;
3847 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003848
3849 case SK_CAssignment: {
3850 QualType SourceType = CurInitExpr->getType();
3851 Sema::AssignConvertType ConvTy =
3852 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003853
3854 // If this is a call, allow conversion to a transparent union.
3855 if (ConvTy != Sema::Compatible &&
3856 Entity.getKind() == InitializedEntity::EK_Parameter &&
3857 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3858 == Sema::Compatible)
3859 ConvTy = Sema::Compatible;
3860
Douglas Gregora41a8c52010-04-22 00:20:18 +00003861 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003862 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3863 Step->Type, SourceType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00003864 CurInitExpr,
3865 getAssignmentAction(Entity),
3866 &Complained)) {
3867 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003868 return S.ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003869 } else if (Complained)
3870 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003871
3872 CurInit.release();
3873 CurInit = S.Owned(CurInitExpr);
3874 break;
3875 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003876
3877 case SK_StringInit: {
3878 QualType Ty = Step->Type;
3879 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3880 break;
3881 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003882 }
3883 }
3884
3885 return move(CurInit);
3886}
3887
3888//===----------------------------------------------------------------------===//
3889// Diagnose initialization failures
3890//===----------------------------------------------------------------------===//
3891bool InitializationSequence::Diagnose(Sema &S,
3892 const InitializedEntity &Entity,
3893 const InitializationKind &Kind,
3894 Expr **Args, unsigned NumArgs) {
3895 if (SequenceKind != FailedSequence)
3896 return false;
3897
Douglas Gregord6542d82009-12-22 15:35:07 +00003898 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003899 switch (Failure) {
3900 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003901 // FIXME: Customize for the initialized entity?
3902 if (NumArgs == 0)
3903 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3904 << DestType.getNonReferenceType();
3905 else // FIXME: diagnostic below could be better!
3906 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3907 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003908 break;
3909
3910 case FK_ArrayNeedsInitList:
3911 case FK_ArrayNeedsInitListOrStringLiteral:
3912 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3913 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3914 break;
3915
John McCall6bb80172010-03-30 21:47:33 +00003916 case FK_AddressOfOverloadFailed: {
3917 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00003918 S.ResolveAddressOfOverloadedFunction(Args[0],
3919 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00003920 true,
3921 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00003922 break;
John McCall6bb80172010-03-30 21:47:33 +00003923 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003924
3925 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003926 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003927 switch (FailedOverloadResult) {
3928 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003929 if (Failure == FK_UserConversionOverloadFailed)
3930 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3931 << Args[0]->getType() << DestType
3932 << Args[0]->getSourceRange();
3933 else
3934 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3935 << DestType << Args[0]->getType()
3936 << Args[0]->getSourceRange();
3937
John McCallcbce6062010-01-12 07:18:19 +00003938 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3939 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003940 break;
3941
3942 case OR_No_Viable_Function:
3943 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3944 << Args[0]->getType() << DestType.getNonReferenceType()
3945 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003946 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3947 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003948 break;
3949
3950 case OR_Deleted: {
3951 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3952 << Args[0]->getType() << DestType.getNonReferenceType()
3953 << Args[0]->getSourceRange();
3954 OverloadCandidateSet::iterator Best;
3955 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3956 Kind.getLocation(),
3957 Best);
3958 if (Ovl == OR_Deleted) {
3959 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3960 << Best->Function->isDeleted();
3961 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003962 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003963 }
3964 break;
3965 }
3966
3967 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003968 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003969 break;
3970 }
3971 break;
3972
3973 case FK_NonConstLValueReferenceBindingToTemporary:
3974 case FK_NonConstLValueReferenceBindingToUnrelated:
3975 S.Diag(Kind.getLocation(),
3976 Failure == FK_NonConstLValueReferenceBindingToTemporary
3977 ? diag::err_lvalue_reference_bind_to_temporary
3978 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00003979 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003980 << DestType.getNonReferenceType()
3981 << Args[0]->getType()
3982 << Args[0]->getSourceRange();
3983 break;
3984
3985 case FK_RValueReferenceBindingToLValue:
3986 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3987 << Args[0]->getSourceRange();
3988 break;
3989
3990 case FK_ReferenceInitDropsQualifiers:
3991 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3992 << DestType.getNonReferenceType()
3993 << Args[0]->getType()
3994 << Args[0]->getSourceRange();
3995 break;
3996
3997 case FK_ReferenceInitFailed:
3998 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3999 << DestType.getNonReferenceType()
4000 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4001 << Args[0]->getType()
4002 << Args[0]->getSourceRange();
4003 break;
4004
4005 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004006 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4007 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004008 << DestType
4009 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4010 << Args[0]->getType()
4011 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004012 break;
4013
4014 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004015 SourceRange R;
4016
4017 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4018 R = SourceRange(InitList->getInit(1)->getLocStart(),
4019 InitList->getLocEnd());
4020 else
4021 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004022
4023 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00004024 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004025 break;
4026 }
4027
4028 case FK_ReferenceBindingToInitList:
4029 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4030 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4031 break;
4032
4033 case FK_InitListBadDestinationType:
4034 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4035 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4036 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00004037
4038 case FK_ConstructorOverloadFailed: {
4039 SourceRange ArgsRange;
4040 if (NumArgs)
4041 ArgsRange = SourceRange(Args[0]->getLocStart(),
4042 Args[NumArgs - 1]->getLocEnd());
4043
4044 // FIXME: Using "DestType" for the entity we're printing is probably
4045 // bad.
4046 switch (FailedOverloadResult) {
4047 case OR_Ambiguous:
4048 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4049 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00004050 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00004051 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004052 break;
4053
4054 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004055 if (Kind.getKind() == InitializationKind::IK_Default &&
4056 (Entity.getKind() == InitializedEntity::EK_Base ||
4057 Entity.getKind() == InitializedEntity::EK_Member) &&
4058 isa<CXXConstructorDecl>(S.CurContext)) {
4059 // This is implicit default initialization of a member or
4060 // base within a constructor. If no viable function was
4061 // found, notify the user that she needs to explicitly
4062 // initialize this base/member.
4063 CXXConstructorDecl *Constructor
4064 = cast<CXXConstructorDecl>(S.CurContext);
4065 if (Entity.getKind() == InitializedEntity::EK_Base) {
4066 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4067 << Constructor->isImplicit()
4068 << S.Context.getTypeDeclType(Constructor->getParent())
4069 << /*base=*/0
4070 << Entity.getType();
4071
4072 RecordDecl *BaseDecl
4073 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4074 ->getDecl();
4075 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4076 << S.Context.getTagDeclType(BaseDecl);
4077 } else {
4078 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4079 << Constructor->isImplicit()
4080 << S.Context.getTypeDeclType(Constructor->getParent())
4081 << /*member=*/1
4082 << Entity.getName();
4083 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4084
4085 if (const RecordType *Record
4086 = Entity.getType()->getAs<RecordType>())
4087 S.Diag(Record->getDecl()->getLocation(),
4088 diag::note_previous_decl)
4089 << S.Context.getTagDeclType(Record->getDecl());
4090 }
4091 break;
4092 }
4093
Douglas Gregor51c56d62009-12-14 20:49:26 +00004094 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4095 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00004096 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4097 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004098 break;
4099
4100 case OR_Deleted: {
4101 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4102 << true << DestType << ArgsRange;
4103 OverloadCandidateSet::iterator Best;
4104 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4105 Kind.getLocation(),
4106 Best);
4107 if (Ovl == OR_Deleted) {
4108 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4109 << Best->Function->isDeleted();
4110 } else {
4111 llvm_unreachable("Inconsistent overload resolution?");
4112 }
4113 break;
4114 }
4115
4116 case OR_Success:
4117 llvm_unreachable("Conversion did not fail!");
4118 break;
4119 }
4120 break;
4121 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004122
4123 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004124 if (Entity.getKind() == InitializedEntity::EK_Member &&
4125 isa<CXXConstructorDecl>(S.CurContext)) {
4126 // This is implicit default-initialization of a const member in
4127 // a constructor. Complain that it needs to be explicitly
4128 // initialized.
4129 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4130 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4131 << Constructor->isImplicit()
4132 << S.Context.getTypeDeclType(Constructor->getParent())
4133 << /*const=*/1
4134 << Entity.getName();
4135 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4136 << Entity.getName();
4137 } else {
4138 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4139 << DestType << (bool)DestType->getAs<RecordType>();
4140 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004141 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004142
4143 case FK_Incomplete:
4144 S.RequireCompleteType(Kind.getLocation(), DestType,
4145 diag::err_init_incomplete_type);
4146 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004147 }
4148
Douglas Gregora41a8c52010-04-22 00:20:18 +00004149 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004150 return true;
4151}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004152
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004153void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4154 switch (SequenceKind) {
4155 case FailedSequence: {
4156 OS << "Failed sequence: ";
4157 switch (Failure) {
4158 case FK_TooManyInitsForReference:
4159 OS << "too many initializers for reference";
4160 break;
4161
4162 case FK_ArrayNeedsInitList:
4163 OS << "array requires initializer list";
4164 break;
4165
4166 case FK_ArrayNeedsInitListOrStringLiteral:
4167 OS << "array requires initializer list or string literal";
4168 break;
4169
4170 case FK_AddressOfOverloadFailed:
4171 OS << "address of overloaded function failed";
4172 break;
4173
4174 case FK_ReferenceInitOverloadFailed:
4175 OS << "overload resolution for reference initialization failed";
4176 break;
4177
4178 case FK_NonConstLValueReferenceBindingToTemporary:
4179 OS << "non-const lvalue reference bound to temporary";
4180 break;
4181
4182 case FK_NonConstLValueReferenceBindingToUnrelated:
4183 OS << "non-const lvalue reference bound to unrelated type";
4184 break;
4185
4186 case FK_RValueReferenceBindingToLValue:
4187 OS << "rvalue reference bound to an lvalue";
4188 break;
4189
4190 case FK_ReferenceInitDropsQualifiers:
4191 OS << "reference initialization drops qualifiers";
4192 break;
4193
4194 case FK_ReferenceInitFailed:
4195 OS << "reference initialization failed";
4196 break;
4197
4198 case FK_ConversionFailed:
4199 OS << "conversion failed";
4200 break;
4201
4202 case FK_TooManyInitsForScalar:
4203 OS << "too many initializers for scalar";
4204 break;
4205
4206 case FK_ReferenceBindingToInitList:
4207 OS << "referencing binding to initializer list";
4208 break;
4209
4210 case FK_InitListBadDestinationType:
4211 OS << "initializer list for non-aggregate, non-scalar type";
4212 break;
4213
4214 case FK_UserConversionOverloadFailed:
4215 OS << "overloading failed for user-defined conversion";
4216 break;
4217
4218 case FK_ConstructorOverloadFailed:
4219 OS << "constructor overloading failed";
4220 break;
4221
4222 case FK_DefaultInitOfConst:
4223 OS << "default initialization of a const variable";
4224 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004225
4226 case FK_Incomplete:
4227 OS << "initialization of incomplete type";
4228 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004229 }
4230 OS << '\n';
4231 return;
4232 }
4233
4234 case DependentSequence:
4235 OS << "Dependent sequence: ";
4236 return;
4237
4238 case UserDefinedConversion:
4239 OS << "User-defined conversion sequence: ";
4240 break;
4241
4242 case ConstructorInitialization:
4243 OS << "Constructor initialization sequence: ";
4244 break;
4245
4246 case ReferenceBinding:
4247 OS << "Reference binding: ";
4248 break;
4249
4250 case ListInitialization:
4251 OS << "List initialization: ";
4252 break;
4253
4254 case ZeroInitialization:
4255 OS << "Zero initialization\n";
4256 return;
4257
4258 case NoInitialization:
4259 OS << "No initialization\n";
4260 return;
4261
4262 case StandardConversion:
4263 OS << "Standard conversion: ";
4264 break;
4265
4266 case CAssignment:
4267 OS << "C assignment: ";
4268 break;
4269
4270 case StringInit:
4271 OS << "String initialization: ";
4272 break;
4273 }
4274
4275 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4276 if (S != step_begin()) {
4277 OS << " -> ";
4278 }
4279
4280 switch (S->Kind) {
4281 case SK_ResolveAddressOfOverloadedFunction:
4282 OS << "resolve address of overloaded function";
4283 break;
4284
4285 case SK_CastDerivedToBaseRValue:
4286 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4287 break;
4288
4289 case SK_CastDerivedToBaseLValue:
4290 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4291 break;
4292
4293 case SK_BindReference:
4294 OS << "bind reference to lvalue";
4295 break;
4296
4297 case SK_BindReferenceToTemporary:
4298 OS << "bind reference to a temporary";
4299 break;
4300
Douglas Gregor523d46a2010-04-18 07:40:54 +00004301 case SK_ExtraneousCopyToTemporary:
4302 OS << "extraneous C++03 copy to temporary";
4303 break;
4304
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004305 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004306 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004307 break;
4308
4309 case SK_QualificationConversionRValue:
4310 OS << "qualification conversion (rvalue)";
4311
4312 case SK_QualificationConversionLValue:
4313 OS << "qualification conversion (lvalue)";
4314 break;
4315
4316 case SK_ConversionSequence:
4317 OS << "implicit conversion sequence (";
4318 S->ICS->DebugPrint(); // FIXME: use OS
4319 OS << ")";
4320 break;
4321
4322 case SK_ListInitialization:
4323 OS << "list initialization";
4324 break;
4325
4326 case SK_ConstructorInitialization:
4327 OS << "constructor initialization";
4328 break;
4329
4330 case SK_ZeroInitialization:
4331 OS << "zero initialization";
4332 break;
4333
4334 case SK_CAssignment:
4335 OS << "C assignment";
4336 break;
4337
4338 case SK_StringInit:
4339 OS << "string initialization";
4340 break;
4341 }
4342 }
4343}
4344
4345void InitializationSequence::dump() const {
4346 dump(llvm::errs());
4347}
4348
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004349//===----------------------------------------------------------------------===//
4350// Initialization helper functions
4351//===----------------------------------------------------------------------===//
4352Sema::OwningExprResult
4353Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4354 SourceLocation EqualLoc,
4355 OwningExprResult Init) {
4356 if (Init.isInvalid())
4357 return ExprError();
4358
4359 Expr *InitE = (Expr *)Init.get();
4360 assert(InitE && "No initialization expression?");
4361
4362 if (EqualLoc.isInvalid())
4363 EqualLoc = InitE->getLocStart();
4364
4365 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4366 EqualLoc);
4367 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4368 Init.release();
4369 return Seq.Perform(*this, Entity, Kind,
4370 MultiExprArg(*this, (void**)&InitE, 1));
4371}