blob: 5aa649bdc92e731e6d47811b3b75a0d99df5accd [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 Gregor63982352010-07-13 18:40:04 +0000526 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
527 IList->setType(ExprTy);
528 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000529 if (hadError)
530 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000531
Eli Friedman638e1442008-05-25 13:22:35 +0000532 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000533 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000534 if (StructuredIndex == 1 &&
535 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000536 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000537 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000538 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000539 hadError = true;
540 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000541 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000542 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000543 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000544 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000545 // Don't complain for incomplete types, since we'll get an error
546 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000547 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000548 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000549 CurrentObjectType->isArrayType()? 0 :
550 CurrentObjectType->isVectorType()? 1 :
551 CurrentObjectType->isScalarType()? 2 :
552 CurrentObjectType->isUnionType()? 3 :
553 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000554
555 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000556 if (SemaRef.getLangOptions().CPlusPlus) {
557 DK = diag::err_excess_initializers;
558 hadError = true;
559 }
Nate Begeman08634522009-07-07 21:53:06 +0000560 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
561 DK = diag::err_excess_initializers;
562 hadError = true;
563 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000564
Chris Lattner08202542009-02-24 22:50:46 +0000565 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000566 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000567 }
568 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000569
Eli Friedman759f2522009-05-16 11:45:48 +0000570 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000571 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000572 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000573 << FixItHint::CreateRemoval(IList->getLocStart())
574 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000575}
576
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000577void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000578 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000579 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000580 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000581 unsigned &Index,
582 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000583 unsigned &StructuredIndex,
584 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000585 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000586 CheckScalarType(Entity, IList, DeclType, Index,
587 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000588 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000589 CheckVectorType(Entity, IList, DeclType, Index,
590 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000591 } else if (DeclType->isAggregateType()) {
592 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000593 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000594 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000596 StructuredList, StructuredIndex,
597 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000598 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000599 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000600 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000601 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000602 CheckArrayType(Entity, IList, DeclType, Zero,
603 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000604 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000605 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000607 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
608 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000609 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000610 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000611 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000612 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000613 } else if (DeclType->isRecordType()) {
614 // C++ [dcl.init]p14:
615 // [...] If the class is an aggregate (8.5.1), and the initializer
616 // is a brace-enclosed list, see 8.5.1.
617 //
618 // Note: 8.5.1 is handled below; here, we diagnose the case where
619 // we have an initializer list and a destination type that is not
620 // an aggregate.
621 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000622 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000623 << DeclType << IList->getSourceRange();
624 hadError = true;
625 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000626 CheckReferenceType(Entity, IList, DeclType, Index,
627 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000628 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000629 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
630 << DeclType;
631 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000632 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000633 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
634 << DeclType;
635 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000636 }
637}
638
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000639void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000640 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000641 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000642 unsigned &Index,
643 InitListExpr *StructuredList,
644 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000645 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000646 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
647 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000648 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000649 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000650 = getStructuredSubobjectInit(IList, Index, ElemType,
651 StructuredList, StructuredIndex,
652 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000653 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000654 newStructuredList, newStructuredIndex);
655 ++StructuredIndex;
656 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000657 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
658 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000659 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000660 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000661 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000662 CheckScalarType(Entity, IList, ElemType, Index,
663 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000664 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000665 CheckReferenceType(Entity, IList, ElemType, Index,
666 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000667 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000668 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000669 // C++ [dcl.init.aggr]p12:
670 // All implicit type conversions (clause 4) are considered when
671 // initializing the aggregate member with an ini- tializer from
672 // an initializer-list. If the initializer can initialize a
673 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000674
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000675 // FIXME: Better EqualLoc?
676 InitializationKind Kind =
677 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
678 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
679
680 if (Seq) {
681 Sema::OwningExprResult Result =
682 Seq.Perform(SemaRef, Entity, Kind,
683 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
684 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000686
687 UpdateStructuredListElement(StructuredList, StructuredIndex,
688 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000689 ++Index;
690 return;
691 }
692
693 // Fall through for subaggregate initialization
694 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000695 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000696 //
697 // The initializer for a structure or union object that has
698 // automatic storage duration shall be either an initializer
699 // list as described below, or a single expression that has
700 // compatible structure or union type. In the latter case, the
701 // initial value of the object, including unnamed members, is
702 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000703 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000704 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000705 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
706 ++Index;
707 return;
708 }
709
710 // Fall through for subaggregate initialization
711 }
712
713 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000714 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000715 // [...] Otherwise, if the member is itself a non-empty
716 // subaggregate, brace elision is assumed and the initializer is
717 // considered for the initialization of the first member of
718 // the subaggregate.
719 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000720 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000721 StructuredIndex);
722 ++StructuredIndex;
723 } else {
724 // We cannot initialize this element, so let
725 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000726 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
727 SemaRef.Owned(expr));
728 IList->setInit(Index, 0);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000729 hadError = true;
730 ++Index;
731 ++StructuredIndex;
732 }
733 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000734}
735
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000736void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000737 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000738 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000739 InitListExpr *StructuredList,
740 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000741 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000742 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000743 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000744 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000745 diag::err_many_braces_around_scalar_init)
746 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000747 hadError = true;
748 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000749 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000750 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000751 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000752 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000753 diag::err_designator_for_scalar_init)
754 << DeclType << expr->getSourceRange();
755 hadError = true;
756 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000757 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000758 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000759 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000760
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000761 Sema::OwningExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000762 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
763 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000764
Chandler Carruthb5719242010-02-13 07:23:01 +0000765 Expr *ResultExpr = 0;
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000766
767 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000768 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000769 else {
770 ResultExpr = Result.takeAs<Expr>();
771
772 if (ResultExpr != expr) {
773 // The type was promoted, update initializer list.
774 IList->setInit(Index, ResultExpr);
775 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000776 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000777 if (hadError)
778 ++StructuredIndex;
779 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000780 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000781 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000782 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000783 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000784 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000785 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000786 ++Index;
787 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000788 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000789 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000790}
791
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000792void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
793 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000794 unsigned &Index,
795 InitListExpr *StructuredList,
796 unsigned &StructuredIndex) {
797 if (Index < IList->getNumInits()) {
798 Expr *expr = IList->getInit(Index);
799 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000800 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000801 << DeclType << IList->getSourceRange();
802 hadError = true;
803 ++Index;
804 ++StructuredIndex;
805 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000806 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000807
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000808 Sema::OwningExprResult Result =
809 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
810 SemaRef.Owned(expr));
811
812 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000813 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000814
815 expr = Result.takeAs<Expr>();
816 IList->setInit(Index, expr);
817
Douglas Gregor930d8b52009-01-30 22:09:00 +0000818 if (hadError)
819 ++StructuredIndex;
820 else
821 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
822 ++Index;
823 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000824 // FIXME: It would be wonderful if we could point at the actual member. In
825 // general, it would be useful to pass location information down the stack,
826 // so that we know the location (or decl) of the "current object" being
827 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000828 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000829 diag::err_init_reference_member_uninitialized)
830 << DeclType
831 << IList->getSourceRange();
832 hadError = true;
833 ++Index;
834 ++StructuredIndex;
835 return;
836 }
837}
838
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000839void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000840 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000841 unsigned &Index,
842 InitListExpr *StructuredList,
843 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000844 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000845 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000846 unsigned maxElements = VT->getNumElements();
847 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000848 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Nate Begeman2ef13e52009-08-10 23:49:36 +0000850 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000851 InitializedEntity ElementEntity =
852 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000853
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000854 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
855 // Don't attempt to go past the end of the init list
856 if (Index >= IList->getNumInits())
857 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000858
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000859 ElementEntity.setElementIndex(Index);
860 CheckSubElementType(ElementEntity, IList, elementType, Index,
861 StructuredList, StructuredIndex);
862 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000863 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000864 InitializedEntity ElementEntity =
865 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
866
Nate Begeman2ef13e52009-08-10 23:49:36 +0000867 // OpenCL initializers allows vectors to be constructed from vectors.
868 for (unsigned i = 0; i < maxElements; ++i) {
869 // Don't attempt to go past the end of the init list
870 if (Index >= IList->getNumInits())
871 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000872
873 ElementEntity.setElementIndex(Index);
874
Nate Begeman2ef13e52009-08-10 23:49:36 +0000875 QualType IType = IList->getInit(Index)->getType();
876 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000877 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000878 StructuredList, StructuredIndex);
879 ++numEltsInit;
880 } else {
Nate Begeman3e315522010-07-07 22:26:56 +0000881 QualType VecType;
John McCall183700f2009-09-21 23:43:11 +0000882 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000883 unsigned numIElts = IVT->getNumElements();
Nate Begeman3e315522010-07-07 22:26:56 +0000884
885 if (IType->isExtVectorType())
886 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
887 else
888 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
889 IVT->getAltiVecSpecific());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000890 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000891 StructuredList, StructuredIndex);
892 numEltsInit += numIElts;
893 }
894 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000895 }
Mike Stump1eb44332009-09-09 15:08:12 +0000896
John Thompsonf3afbea2010-04-20 23:21:17 +0000897 // OpenCL requires all elements to be initialized.
Nate Begeman2ef13e52009-08-10 23:49:36 +0000898 if (numEltsInit != maxElements)
Chris Lattnere12a7792010-04-20 05:19:10 +0000899 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman2ef13e52009-08-10 23:49:36 +0000900 SemaRef.Diag(IList->getSourceRange().getBegin(),
901 diag::err_vector_incorrect_num_initializers)
902 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000903 }
904}
905
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000906void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000907 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000908 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000909 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000910 unsigned &Index,
911 InitListExpr *StructuredList,
912 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000913 // Check for the special-case of initializing an array with a string.
914 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000915 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
916 SemaRef.Context)) {
917 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000918 // We place the string literal directly into the resulting
919 // initializer list. This is the only place where the structure
920 // of the structured initializer list doesn't match exactly,
921 // because doing so would involve allocating one character
922 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000923 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000924 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000925 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000926 return;
927 }
928 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000929 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000930 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000931 // Check for VLAs; in standard C it would be possible to check this
932 // earlier, but I don't know where clang accepts VLAs (gcc accepts
933 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000934 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000935 diag::err_variable_object_no_init)
936 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000937 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000938 ++Index;
939 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000940 return;
941 }
942
Douglas Gregor05c13a32009-01-22 00:58:24 +0000943 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000944 llvm::APSInt maxElements(elementIndex.getBitWidth(),
945 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000946 bool maxElementsKnown = false;
947 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000948 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000949 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000950 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000951 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000952 maxElementsKnown = true;
953 }
954
Chris Lattner08202542009-02-24 22:50:46 +0000955 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000956 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000957 while (Index < IList->getNumInits()) {
958 Expr *Init = IList->getInit(Index);
959 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000960 // If we're not the subobject that matches up with the '{' for
961 // the designator, we shouldn't be handling the
962 // designator. Return immediately.
963 if (!SubobjectIsDesignatorContext)
964 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000965
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000966 // Handle this designated initializer. elementIndex will be
967 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000968 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000969 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000970 StructuredList, StructuredIndex, true,
971 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000972 hadError = true;
973 continue;
974 }
975
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000976 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
977 maxElements.extend(elementIndex.getBitWidth());
978 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
979 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000980 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000981
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000982 // If the array is of incomplete type, keep track of the number of
983 // elements in the initializer.
984 if (!maxElementsKnown && elementIndex > maxElements)
985 maxElements = elementIndex;
986
Douglas Gregor05c13a32009-01-22 00:58:24 +0000987 continue;
988 }
989
990 // If we know the maximum number of elements, and we've already
991 // hit it, stop consuming elements in the initializer list.
992 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000993 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000994
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000995 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000996 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000997 Entity);
998 // Check this element.
999 CheckSubElementType(ElementEntity, IList, elementType, Index,
1000 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001001 ++elementIndex;
1002
1003 // If the array is of incomplete type, keep track of the number of
1004 // elements in the initializer.
1005 if (!maxElementsKnown && elementIndex > maxElements)
1006 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001007 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001008 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001009 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001010 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001011 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001012 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001013 // Sizing an array implicitly to zero is not allowed by ISO C,
1014 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001015 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001016 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001017 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001018
Mike Stump1eb44332009-09-09 15:08:12 +00001019 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001020 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001021 }
1022}
1023
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001024void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001025 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001026 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001027 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001028 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001029 unsigned &Index,
1030 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001031 unsigned &StructuredIndex,
1032 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001033 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Eli Friedmanb85f7072008-05-19 19:16:24 +00001035 // If the record is invalid, some of it's members are invalid. To avoid
1036 // confusion, we forgo checking the intializer for the entire record.
1037 if (structDecl->isInvalidDecl()) {
1038 hadError = true;
1039 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001040 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001041
1042 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1043 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001044 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001045 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001046 Field != FieldEnd; ++Field) {
1047 if (Field->getDeclName()) {
1048 StructuredList->setInitializedFieldInUnion(*Field);
1049 break;
1050 }
1051 }
1052 return;
1053 }
1054
Douglas Gregor05c13a32009-01-22 00:58:24 +00001055 // If structDecl is a forward declaration, this loop won't do
1056 // anything except look at designated initializers; That's okay,
1057 // because an error should get printed out elsewhere. It might be
1058 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001059 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001060 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001061 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001062 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001063 while (Index < IList->getNumInits()) {
1064 Expr *Init = IList->getInit(Index);
1065
1066 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001067 // If we're not the subobject that matches up with the '{' for
1068 // the designator, we shouldn't be handling the
1069 // designator. Return immediately.
1070 if (!SubobjectIsDesignatorContext)
1071 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001072
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001073 // Handle this designated initializer. Field will be updated to
1074 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001075 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001076 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001077 StructuredList, StructuredIndex,
1078 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001079 hadError = true;
1080
Douglas Gregordfb5e592009-02-12 19:00:39 +00001081 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001082
1083 // Disable check for missing fields when designators are used.
1084 // This matches gcc behaviour.
1085 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001086 continue;
1087 }
1088
1089 if (Field == FieldEnd) {
1090 // We've run out of fields. We're done.
1091 break;
1092 }
1093
Douglas Gregordfb5e592009-02-12 19:00:39 +00001094 // We've already initialized a member of a union. We're done.
1095 if (InitializedSomething && DeclType->isUnionType())
1096 break;
1097
Douglas Gregor44b43212008-12-11 16:49:14 +00001098 // If we've hit the flexible array member at the end, we're done.
1099 if (Field->getType()->isIncompleteArrayType())
1100 break;
1101
Douglas Gregor0bb76892009-01-29 16:53:55 +00001102 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001103 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001104 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001105 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001106 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001107
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001108 InitializedEntity MemberEntity =
1109 InitializedEntity::InitializeMember(*Field, &Entity);
1110 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1111 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001112 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001113
1114 if (DeclType->isUnionType()) {
1115 // Initialize the first field within the union.
1116 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001117 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001118
1119 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001120 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001121
John McCall80639de2010-03-11 19:32:38 +00001122 // Emit warnings for missing struct field initializers.
Douglas Gregor8e198902010-06-18 21:43:10 +00001123 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001124 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1125 // It is possible we have one or more unnamed bitfields remaining.
1126 // Find first (if any) named field and emit warning.
1127 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1128 it != end; ++it) {
1129 if (!it->isUnnamedBitfield()) {
1130 SemaRef.Diag(IList->getSourceRange().getEnd(),
1131 diag::warn_missing_field_initializers) << it->getName();
1132 break;
1133 }
1134 }
1135 }
1136
Mike Stump1eb44332009-09-09 15:08:12 +00001137 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001138 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001139 return;
1140
1141 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001142 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001143 (!isa<InitListExpr>(IList->getInit(Index)) ||
1144 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001145 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001146 diag::err_flexible_array_init_nonempty)
1147 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001148 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001149 << *Field;
1150 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001151 ++Index;
1152 return;
1153 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001154 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001155 diag::ext_flexible_array_init)
1156 << IList->getInit(Index)->getSourceRange().getBegin();
1157 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1158 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001159 }
1160
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001161 InitializedEntity MemberEntity =
1162 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001163
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001164 if (isa<InitListExpr>(IList->getInit(Index)))
1165 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1166 StructuredList, StructuredIndex);
1167 else
1168 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001169 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001170}
Steve Naroff0cca7492008-05-01 22:18:59 +00001171
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001172/// \brief Expand a field designator that refers to a member of an
1173/// anonymous struct or union into a series of field designators that
1174/// refers to the field within the appropriate subobject.
1175///
1176/// Field/FieldIndex will be updated to point to the (new)
1177/// currently-designated field.
1178static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001179 DesignatedInitExpr *DIE,
1180 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001181 FieldDecl *Field,
1182 RecordDecl::field_iterator &FieldIter,
1183 unsigned &FieldIndex) {
1184 typedef DesignatedInitExpr::Designator Designator;
1185
1186 // Build the path from the current object to the member of the
1187 // anonymous struct/union (backwards).
1188 llvm::SmallVector<FieldDecl *, 4> Path;
1189 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001191 // Build the replacement designators.
1192 llvm::SmallVector<Designator, 4> Replacements;
1193 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1194 FI = Path.rbegin(), FIEnd = Path.rend();
1195 FI != FIEnd; ++FI) {
1196 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001197 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001198 DIE->getDesignator(DesigIdx)->getDotLoc(),
1199 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1200 else
1201 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1202 SourceLocation()));
1203 Replacements.back().setField(*FI);
1204 }
1205
1206 // Expand the current designator into the set of replacement
1207 // designators, so we have a full subobject path down to where the
1208 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001209 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001210 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001212 // Update FieldIter/FieldIndex;
1213 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001214 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001215 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001216 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001217 FieldIter != FEnd; ++FieldIter) {
1218 if (FieldIter->isUnnamedBitfield())
1219 continue;
1220
1221 if (*FieldIter == Path.back())
1222 return;
1223
1224 ++FieldIndex;
1225 }
1226
1227 assert(false && "Unable to find anonymous struct/union field");
1228}
1229
Douglas Gregor05c13a32009-01-22 00:58:24 +00001230/// @brief Check the well-formedness of a C99 designated initializer.
1231///
1232/// Determines whether the designated initializer @p DIE, which
1233/// resides at the given @p Index within the initializer list @p
1234/// IList, is well-formed for a current object of type @p DeclType
1235/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001236/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001237/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001238///
1239/// @param IList The initializer list in which this designated
1240/// initializer occurs.
1241///
Douglas Gregor71199712009-04-15 04:56:10 +00001242/// @param DIE The designated initializer expression.
1243///
1244/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001245///
1246/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1247/// into which the designation in @p DIE should refer.
1248///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001249/// @param NextField If non-NULL and the first designator in @p DIE is
1250/// a field, this will be set to the field declaration corresponding
1251/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001252///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001253/// @param NextElementIndex If non-NULL and the first designator in @p
1254/// DIE is an array designator or GNU array-range designator, this
1255/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001256///
1257/// @param Index Index into @p IList where the designated initializer
1258/// @p DIE occurs.
1259///
Douglas Gregor4c678342009-01-28 21:54:33 +00001260/// @param StructuredList The initializer list expression that
1261/// describes all of the subobject initializers in the order they'll
1262/// actually be initialized.
1263///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001264/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001265bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001266InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001267 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001268 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001269 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001270 QualType &CurrentObjectType,
1271 RecordDecl::field_iterator *NextField,
1272 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001273 unsigned &Index,
1274 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001275 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001276 bool FinishSubobjectInit,
1277 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001278 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001279 // Check the actual initialization for the designated object type.
1280 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001281
1282 // Temporarily remove the designator expression from the
1283 // initializer list that the child calls see, so that we don't try
1284 // to re-process the designator.
1285 unsigned OldIndex = Index;
1286 IList->setInit(OldIndex, DIE->getInit());
1287
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001288 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001289 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001290
1291 // Restore the designated initializer expression in the syntactic
1292 // form of the initializer list.
1293 if (IList->getInit(OldIndex) != DIE->getInit())
1294 DIE->setInit(IList->getInit(OldIndex));
1295 IList->setInit(OldIndex, DIE);
1296
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001297 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001298 }
1299
Douglas Gregor71199712009-04-15 04:56:10 +00001300 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001301 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001302 "Need a non-designated initializer list to start from");
1303
Douglas Gregor71199712009-04-15 04:56:10 +00001304 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001305 // Determine the structural initializer list that corresponds to the
1306 // current subobject.
1307 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001308 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001309 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001310 SourceRange(D->getStartLocation(),
1311 DIE->getSourceRange().getEnd()));
1312 assert(StructuredList && "Expected a structured initializer list");
1313
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001314 if (D->isFieldDesignator()) {
1315 // C99 6.7.8p7:
1316 //
1317 // If a designator has the form
1318 //
1319 // . identifier
1320 //
1321 // then the current object (defined below) shall have
1322 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001323 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001324 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001325 if (!RT) {
1326 SourceLocation Loc = D->getDotLoc();
1327 if (Loc.isInvalid())
1328 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001329 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1330 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001331 ++Index;
1332 return true;
1333 }
1334
Douglas Gregor4c678342009-01-28 21:54:33 +00001335 // Note: we perform a linear search of the fields here, despite
1336 // the fact that we have a faster lookup method, because we always
1337 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001338 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001339 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001340 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001341 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001342 Field = RT->getDecl()->field_begin(),
1343 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001344 for (; Field != FieldEnd; ++Field) {
1345 if (Field->isUnnamedBitfield())
1346 continue;
1347
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001348 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 break;
1350
1351 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001352 }
1353
Douglas Gregor4c678342009-01-28 21:54:33 +00001354 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001355 // There was no normal field in the struct with the designated
1356 // name. Perform another lookup for this name, which may find
1357 // something that we can't designate (e.g., a member function),
1358 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001359 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001360 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001361 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001362 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001363 // Name lookup didn't find anything. Determine whether this
1364 // was a typo for another field name.
1365 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1366 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001367 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1368 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001369 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1370 ReplacementField->getDeclContext()->getLookupContext()
1371 ->Equals(RT->getDecl())) {
1372 SemaRef.Diag(D->getFieldLoc(),
1373 diag::err_field_designator_unknown_suggest)
1374 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001375 << FixItHint::CreateReplacement(D->getFieldLoc(),
1376 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001377 SemaRef.Diag(ReplacementField->getLocation(),
1378 diag::note_previous_decl)
1379 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001380 } else {
1381 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1382 << FieldName << CurrentObjectType;
1383 ++Index;
1384 return true;
1385 }
1386 } else if (!KnownField) {
1387 // Determine whether we found a field at all.
1388 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1389 }
1390
1391 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001392 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001393 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001394 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001395 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001396 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001397 ++Index;
1398 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001399 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001400
1401 if (!KnownField &&
1402 cast<RecordDecl>((ReplacementField)->getDeclContext())
1403 ->isAnonymousStructOrUnion()) {
1404 // Handle an field designator that refers to a member of an
1405 // anonymous struct or union.
1406 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1407 ReplacementField,
1408 Field, FieldIndex);
1409 D = DIE->getDesignator(DesigIdx);
1410 } else if (!KnownField) {
1411 // The replacement field comes from typo correction; find it
1412 // in the list of fields.
1413 FieldIndex = 0;
1414 Field = RT->getDecl()->field_begin();
1415 for (; Field != FieldEnd; ++Field) {
1416 if (Field->isUnnamedBitfield())
1417 continue;
1418
1419 if (ReplacementField == *Field ||
1420 Field->getIdentifier() == ReplacementField->getIdentifier())
1421 break;
1422
1423 ++FieldIndex;
1424 }
1425 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001426 } else if (!KnownField &&
1427 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001428 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001429 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1430 Field, FieldIndex);
1431 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001432 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001433
1434 // All of the fields of a union are located at the same place in
1435 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001436 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001437 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001438 StructuredList->setInitializedFieldInUnion(*Field);
1439 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001440
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001441 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001442 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregor4c678342009-01-28 21:54:33 +00001444 // Make sure that our non-designated initializer list has space
1445 // for a subobject corresponding to this field.
1446 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001447 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001448
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001449 // This designator names a flexible array member.
1450 if (Field->getType()->isIncompleteArrayType()) {
1451 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001452 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001453 // We can't designate an object within the flexible array
1454 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001455 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001456 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001457 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001458 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001459 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001460 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001461 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001462 << *Field;
1463 Invalid = true;
1464 }
1465
1466 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1467 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001468 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001469 diag::err_flexible_array_init_needs_braces)
1470 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001471 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001472 << *Field;
1473 Invalid = true;
1474 }
1475
1476 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001477 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001478 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001479 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001480 diag::err_flexible_array_init_nonempty)
1481 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001482 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001483 << *Field;
1484 Invalid = true;
1485 }
1486
1487 if (Invalid) {
1488 ++Index;
1489 return true;
1490 }
1491
1492 // Initialize the array.
1493 bool prevHadError = hadError;
1494 unsigned newStructuredIndex = FieldIndex;
1495 unsigned OldIndex = Index;
1496 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001497
1498 InitializedEntity MemberEntity =
1499 InitializedEntity::InitializeMember(*Field, &Entity);
1500 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001501 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001502
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001503 IList->setInit(OldIndex, DIE);
1504 if (hadError && !prevHadError) {
1505 ++Field;
1506 ++FieldIndex;
1507 if (NextField)
1508 *NextField = Field;
1509 StructuredIndex = FieldIndex;
1510 return true;
1511 }
1512 } else {
1513 // Recurse to check later designated subobjects.
1514 QualType FieldType = (*Field)->getType();
1515 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001516
1517 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001518 InitializedEntity::InitializeMember(*Field, &Entity);
1519 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001520 FieldType, 0, 0, Index,
1521 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001522 true, false))
1523 return true;
1524 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001525
1526 // Find the position of the next field to be initialized in this
1527 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001528 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001529 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001530
1531 // If this the first designator, our caller will continue checking
1532 // the rest of this struct/class/union subobject.
1533 if (IsFirstDesignator) {
1534 if (NextField)
1535 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001536 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001537 return false;
1538 }
1539
Douglas Gregor34e79462009-01-28 23:36:17 +00001540 if (!FinishSubobjectInit)
1541 return false;
1542
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001543 // We've already initialized something in the union; we're done.
1544 if (RT->getDecl()->isUnion())
1545 return hadError;
1546
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001547 // Check the remaining fields within this class/struct/union subobject.
1548 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001549
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001550 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001551 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001552 return hadError && !prevHadError;
1553 }
1554
1555 // C99 6.7.8p6:
1556 //
1557 // If a designator has the form
1558 //
1559 // [ constant-expression ]
1560 //
1561 // then the current object (defined below) shall have array
1562 // type and the expression shall be an integer constant
1563 // expression. If the array is of unknown size, any
1564 // nonnegative value is valid.
1565 //
1566 // Additionally, cope with the GNU extension that permits
1567 // designators of the form
1568 //
1569 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001570 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001572 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001573 << CurrentObjectType;
1574 ++Index;
1575 return true;
1576 }
1577
1578 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001579 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1580 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001581 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001582 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001583 DesignatedEndIndex = DesignatedStartIndex;
1584 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001585 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001586
Mike Stump1eb44332009-09-09 15:08:12 +00001587
1588 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001589 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001590 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001591 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001592 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001593
Chris Lattner3bf68932009-04-25 21:59:05 +00001594 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001595 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001596 }
1597
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001598 if (isa<ConstantArrayType>(AT)) {
1599 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001600 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1601 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1602 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1603 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1604 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001605 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001606 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001607 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001608 << IndexExpr->getSourceRange();
1609 ++Index;
1610 return true;
1611 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001612 } else {
1613 // Make sure the bit-widths and signedness match.
1614 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1615 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001616 else if (DesignatedStartIndex.getBitWidth() <
1617 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001618 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1619 DesignatedStartIndex.setIsUnsigned(true);
1620 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001621 }
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Douglas Gregor4c678342009-01-28 21:54:33 +00001623 // Make sure that our non-designated initializer list has space
1624 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001625 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001626 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001627 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001628
Douglas Gregor34e79462009-01-28 23:36:17 +00001629 // Repeatedly perform subobject initializations in the range
1630 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001631
Douglas Gregor34e79462009-01-28 23:36:17 +00001632 // Move to the next designator
1633 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1634 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001635
1636 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001637 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001638
Douglas Gregor34e79462009-01-28 23:36:17 +00001639 while (DesignatedStartIndex <= DesignatedEndIndex) {
1640 // Recurse to check later designated subobjects.
1641 QualType ElementType = AT->getElementType();
1642 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001643
1644 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001645 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001646 ElementType, 0, 0, Index,
1647 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001648 (DesignatedStartIndex == DesignatedEndIndex),
1649 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001650 return true;
1651
1652 // Move to the next index in the array that we'll be initializing.
1653 ++DesignatedStartIndex;
1654 ElementIndex = DesignatedStartIndex.getZExtValue();
1655 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001656
1657 // If this the first designator, our caller will continue checking
1658 // the rest of this array subobject.
1659 if (IsFirstDesignator) {
1660 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001661 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001662 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001663 return false;
1664 }
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Douglas Gregor34e79462009-01-28 23:36:17 +00001666 if (!FinishSubobjectInit)
1667 return false;
1668
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001669 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001670 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001671 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001672 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001673 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001674 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001675}
1676
Douglas Gregor4c678342009-01-28 21:54:33 +00001677// Get the structured initializer list for a subobject of type
1678// @p CurrentObjectType.
1679InitListExpr *
1680InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1681 QualType CurrentObjectType,
1682 InitListExpr *StructuredList,
1683 unsigned StructuredIndex,
1684 SourceRange InitRange) {
1685 Expr *ExistingInit = 0;
1686 if (!StructuredList)
1687 ExistingInit = SyntacticToSemantic[IList];
1688 else if (StructuredIndex < StructuredList->getNumInits())
1689 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Douglas Gregor4c678342009-01-28 21:54:33 +00001691 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1692 return Result;
1693
1694 if (ExistingInit) {
1695 // We are creating an initializer list that initializes the
1696 // subobjects of the current object, but there was already an
1697 // initialization that completely initialized the current
1698 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001699 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001700 // struct X { int a, b; };
1701 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001702 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001703 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1704 // designated initializer re-initializes the whole
1705 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001706 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001707 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001708 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001709 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001710 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001711 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001712 << ExistingInit->getSourceRange();
1713 }
1714
Mike Stump1eb44332009-09-09 15:08:12 +00001715 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001716 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1717 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001718 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001719
Douglas Gregor63982352010-07-13 18:40:04 +00001720 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001721
Douglas Gregorfa219202009-03-20 23:58:33 +00001722 // Pre-allocate storage for the structured initializer list.
1723 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001724 unsigned NumInits = 0;
1725 if (!StructuredList)
1726 NumInits = IList->getNumInits();
1727 else if (Index < IList->getNumInits()) {
1728 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1729 NumInits = SubList->getNumInits();
1730 }
1731
Mike Stump1eb44332009-09-09 15:08:12 +00001732 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001733 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1734 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1735 NumElements = CAType->getSize().getZExtValue();
1736 // Simple heuristic so that we don't allocate a very large
1737 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001738 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001739 NumElements = 0;
1740 }
John McCall183700f2009-09-21 23:43:11 +00001741 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001742 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001743 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001744 RecordDecl *RDecl = RType->getDecl();
1745 if (RDecl->isUnion())
1746 NumElements = 1;
1747 else
Mike Stump1eb44332009-09-09 15:08:12 +00001748 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001749 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001750 }
1751
Douglas Gregor08457732009-03-21 18:13:52 +00001752 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001753 NumElements = IList->getNumInits();
1754
Ted Kremenek709210f2010-04-13 23:39:13 +00001755 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001756
Douglas Gregor4c678342009-01-28 21:54:33 +00001757 // Link this new initializer list into the structured initializer
1758 // lists.
1759 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001760 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001761 else {
1762 Result->setSyntacticForm(IList);
1763 SyntacticToSemantic[IList] = Result;
1764 }
1765
1766 return Result;
1767}
1768
1769/// Update the initializer at index @p StructuredIndex within the
1770/// structured initializer list to the value @p expr.
1771void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1772 unsigned &StructuredIndex,
1773 Expr *expr) {
1774 // No structured initializer list to update
1775 if (!StructuredList)
1776 return;
1777
Ted Kremenek709210f2010-04-13 23:39:13 +00001778 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1779 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001780 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001781 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001782 diag::warn_initializer_overrides)
1783 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001784 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001785 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001786 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001787 << PrevInit->getSourceRange();
1788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Douglas Gregor4c678342009-01-28 21:54:33 +00001790 ++StructuredIndex;
1791}
1792
Douglas Gregor05c13a32009-01-22 00:58:24 +00001793/// Check that the given Index expression is a valid array designator
1794/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001795/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001796/// and produces a reasonable diagnostic if there is a
1797/// failure. Returns true if there was an error, false otherwise. If
1798/// everything went okay, Value will receive the value of the constant
1799/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001800static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001801CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001802 SourceLocation Loc = Index->getSourceRange().getBegin();
1803
1804 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001805 if (S.VerifyIntegerConstantExpression(Index, &Value))
1806 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001807
Chris Lattner3bf68932009-04-25 21:59:05 +00001808 if (Value.isSigned() && Value.isNegative())
1809 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001810 << Value.toString(10) << Index->getSourceRange();
1811
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001812 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001813 return false;
1814}
1815
1816Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1817 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001818 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001819 OwningExprResult Init) {
1820 typedef DesignatedInitExpr::Designator ASTDesignator;
1821
1822 bool Invalid = false;
1823 llvm::SmallVector<ASTDesignator, 32> Designators;
1824 llvm::SmallVector<Expr *, 32> InitExpressions;
1825
1826 // Build designators and check array designator expressions.
1827 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1828 const Designator &D = Desig.getDesignator(Idx);
1829 switch (D.getKind()) {
1830 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001831 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001832 D.getFieldLoc()));
1833 break;
1834
1835 case Designator::ArrayDesignator: {
1836 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1837 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001838 if (!Index->isTypeDependent() &&
1839 !Index->isValueDependent() &&
1840 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001841 Invalid = true;
1842 else {
1843 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001844 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001845 D.getRBracketLoc()));
1846 InitExpressions.push_back(Index);
1847 }
1848 break;
1849 }
1850
1851 case Designator::ArrayRangeDesignator: {
1852 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1853 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1854 llvm::APSInt StartValue;
1855 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001856 bool StartDependent = StartIndex->isTypeDependent() ||
1857 StartIndex->isValueDependent();
1858 bool EndDependent = EndIndex->isTypeDependent() ||
1859 EndIndex->isValueDependent();
1860 if ((!StartDependent &&
1861 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1862 (!EndDependent &&
1863 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001864 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001865 else {
1866 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001867 if (StartDependent || EndDependent) {
1868 // Nothing to compute.
1869 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001870 EndValue.extend(StartValue.getBitWidth());
1871 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1872 StartValue.extend(EndValue.getBitWidth());
1873
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001874 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001875 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001876 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001877 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1878 Invalid = true;
1879 } else {
1880 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001881 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001882 D.getEllipsisLoc(),
1883 D.getRBracketLoc()));
1884 InitExpressions.push_back(StartIndex);
1885 InitExpressions.push_back(EndIndex);
1886 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001887 }
1888 break;
1889 }
1890 }
1891 }
1892
1893 if (Invalid || Init.isInvalid())
1894 return ExprError();
1895
1896 // Clear out the expressions within the designation.
1897 Desig.ClearExprs(*this);
1898
1899 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001900 = DesignatedInitExpr::Create(Context,
1901 Designators.data(), Designators.size(),
1902 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001903 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001904 return Owned(DIE);
1905}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001906
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001907bool Sema::CheckInitList(const InitializedEntity &Entity,
1908 InitListExpr *&InitList, QualType &DeclType) {
1909 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001910 if (!CheckInitList.HadError())
1911 InitList = CheckInitList.getFullyStructuredList();
1912
1913 return CheckInitList.HadError();
1914}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001915
Douglas Gregor20093b42009-12-09 23:02:17 +00001916//===----------------------------------------------------------------------===//
1917// Initialization entity
1918//===----------------------------------------------------------------------===//
1919
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001920InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1921 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001922 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001923{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001924 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1925 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001926 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001927 } else {
1928 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001929 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001930 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001931}
1932
1933InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001934 CXXBaseSpecifier *Base,
1935 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001936{
1937 InitializedEntity Result;
1938 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001939 Result.Base = reinterpret_cast<uintptr_t>(Base);
1940 if (IsInheritedVirtualBase)
1941 Result.Base |= 0x01;
1942
Douglas Gregord6542d82009-12-22 15:35:07 +00001943 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001944 return Result;
1945}
1946
Douglas Gregor99a2e602009-12-16 01:38:02 +00001947DeclarationName InitializedEntity::getName() const {
1948 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001949 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001950 if (!VariableOrMember)
1951 return DeclarationName();
1952 // Fall through
1953
1954 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001955 case EK_Member:
1956 return VariableOrMember->getDeclName();
1957
1958 case EK_Result:
1959 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001960 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001961 case EK_Temporary:
1962 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001963 case EK_ArrayElement:
1964 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001965 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001966 return DeclarationName();
1967 }
1968
1969 // Silence GCC warning
1970 return DeclarationName();
1971}
1972
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001973DeclaratorDecl *InitializedEntity::getDecl() const {
1974 switch (getKind()) {
1975 case EK_Variable:
1976 case EK_Parameter:
1977 case EK_Member:
1978 return VariableOrMember;
1979
1980 case EK_Result:
1981 case EK_Exception:
1982 case EK_New:
1983 case EK_Temporary:
1984 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001985 case EK_ArrayElement:
1986 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001987 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001988 return 0;
1989 }
1990
1991 // Silence GCC warning
1992 return 0;
1993}
1994
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001995bool InitializedEntity::allowsNRVO() const {
1996 switch (getKind()) {
1997 case EK_Result:
1998 case EK_Exception:
1999 return LocAndNRVO.NRVO;
2000
2001 case EK_Variable:
2002 case EK_Parameter:
2003 case EK_Member:
2004 case EK_New:
2005 case EK_Temporary:
2006 case EK_Base:
2007 case EK_ArrayElement:
2008 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002009 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002010 break;
2011 }
2012
2013 return false;
2014}
2015
Douglas Gregor20093b42009-12-09 23:02:17 +00002016//===----------------------------------------------------------------------===//
2017// Initialization sequence
2018//===----------------------------------------------------------------------===//
2019
2020void InitializationSequence::Step::Destroy() {
2021 switch (Kind) {
2022 case SK_ResolveAddressOfOverloadedFunction:
2023 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002024 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002025 case SK_CastDerivedToBaseLValue:
2026 case SK_BindReference:
2027 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002028 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002029 case SK_UserConversion:
2030 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002031 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002032 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002033 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002034 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002035 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002036 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002037 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00002038 break;
2039
2040 case SK_ConversionSequence:
2041 delete ICS;
2042 }
2043}
2044
Douglas Gregorb70cf442010-03-26 20:14:36 +00002045bool InitializationSequence::isDirectReferenceBinding() const {
2046 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2047}
2048
2049bool InitializationSequence::isAmbiguous() const {
2050 if (getKind() != FailedSequence)
2051 return false;
2052
2053 switch (getFailureKind()) {
2054 case FK_TooManyInitsForReference:
2055 case FK_ArrayNeedsInitList:
2056 case FK_ArrayNeedsInitListOrStringLiteral:
2057 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2058 case FK_NonConstLValueReferenceBindingToTemporary:
2059 case FK_NonConstLValueReferenceBindingToUnrelated:
2060 case FK_RValueReferenceBindingToLValue:
2061 case FK_ReferenceInitDropsQualifiers:
2062 case FK_ReferenceInitFailed:
2063 case FK_ConversionFailed:
2064 case FK_TooManyInitsForScalar:
2065 case FK_ReferenceBindingToInitList:
2066 case FK_InitListBadDestinationType:
2067 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002068 case FK_Incomplete:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002069 return false;
2070
2071 case FK_ReferenceInitOverloadFailed:
2072 case FK_UserConversionOverloadFailed:
2073 case FK_ConstructorOverloadFailed:
2074 return FailedOverloadResult == OR_Ambiguous;
2075 }
2076
2077 return false;
2078}
2079
Douglas Gregord6e44a32010-04-16 22:09:46 +00002080bool InitializationSequence::isConstructorInitialization() const {
2081 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2082}
2083
Douglas Gregor20093b42009-12-09 23:02:17 +00002084void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002085 FunctionDecl *Function,
2086 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002087 Step S;
2088 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2089 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002090 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002091 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002092 Steps.push_back(S);
2093}
2094
2095void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
Sebastian Redl906082e2010-07-20 04:20:21 +00002096 ImplicitCastExpr::ResultCategory Category) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002097 Step S;
Sebastian Redl906082e2010-07-20 04:20:21 +00002098 switch (Category) {
2099 case ImplicitCastExpr::RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2100 case ImplicitCastExpr::XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2101 case ImplicitCastExpr::LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2102 default: llvm_unreachable("No such category");
2103 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002104 S.Type = BaseType;
2105 Steps.push_back(S);
2106}
2107
2108void InitializationSequence::AddReferenceBindingStep(QualType T,
2109 bool BindingTemporary) {
2110 Step S;
2111 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2112 S.Type = T;
2113 Steps.push_back(S);
2114}
2115
Douglas Gregor523d46a2010-04-18 07:40:54 +00002116void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2117 Step S;
2118 S.Kind = SK_ExtraneousCopyToTemporary;
2119 S.Type = T;
2120 Steps.push_back(S);
2121}
2122
Eli Friedman03981012009-12-11 02:42:07 +00002123void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002124 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002125 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002126 Step S;
2127 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002128 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002129 S.Function.Function = Function;
2130 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002131 Steps.push_back(S);
2132}
2133
2134void InitializationSequence::AddQualificationConversionStep(QualType Ty,
Sebastian Redl906082e2010-07-20 04:20:21 +00002135 ImplicitCastExpr::ResultCategory Category) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002136 Step S;
Sebastian Redl906082e2010-07-20 04:20:21 +00002137 switch (Category) {
2138 case ImplicitCastExpr::RValue:
2139 S.Kind = SK_QualificationConversionRValue;
2140 break;
2141 case ImplicitCastExpr::XValue:
2142 S.Kind = SK_QualificationConversionXValue;
2143 break;
2144 case ImplicitCastExpr::LValue:
2145 S.Kind = SK_QualificationConversionLValue;
2146 break;
2147 default: llvm_unreachable("No such category");
2148 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002149 S.Type = Ty;
2150 Steps.push_back(S);
2151}
2152
2153void InitializationSequence::AddConversionSequenceStep(
2154 const ImplicitConversionSequence &ICS,
2155 QualType T) {
2156 Step S;
2157 S.Kind = SK_ConversionSequence;
2158 S.Type = T;
2159 S.ICS = new ImplicitConversionSequence(ICS);
2160 Steps.push_back(S);
2161}
2162
Douglas Gregord87b61f2009-12-10 17:56:55 +00002163void InitializationSequence::AddListInitializationStep(QualType T) {
2164 Step S;
2165 S.Kind = SK_ListInitialization;
2166 S.Type = T;
2167 Steps.push_back(S);
2168}
2169
Douglas Gregor51c56d62009-12-14 20:49:26 +00002170void
2171InitializationSequence::AddConstructorInitializationStep(
2172 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002173 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002174 QualType T) {
2175 Step S;
2176 S.Kind = SK_ConstructorInitialization;
2177 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002178 S.Function.Function = Constructor;
2179 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002180 Steps.push_back(S);
2181}
2182
Douglas Gregor71d17402009-12-15 00:01:57 +00002183void InitializationSequence::AddZeroInitializationStep(QualType T) {
2184 Step S;
2185 S.Kind = SK_ZeroInitialization;
2186 S.Type = T;
2187 Steps.push_back(S);
2188}
2189
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002190void InitializationSequence::AddCAssignmentStep(QualType T) {
2191 Step S;
2192 S.Kind = SK_CAssignment;
2193 S.Type = T;
2194 Steps.push_back(S);
2195}
2196
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002197void InitializationSequence::AddStringInitStep(QualType T) {
2198 Step S;
2199 S.Kind = SK_StringInit;
2200 S.Type = T;
2201 Steps.push_back(S);
2202}
2203
Douglas Gregor20093b42009-12-09 23:02:17 +00002204void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2205 OverloadingResult Result) {
2206 SequenceKind = FailedSequence;
2207 this->Failure = Failure;
2208 this->FailedOverloadResult = Result;
2209}
2210
2211//===----------------------------------------------------------------------===//
2212// Attempt initialization
2213//===----------------------------------------------------------------------===//
2214
2215/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002216static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002217 const InitializedEntity &Entity,
2218 const InitializationKind &Kind,
2219 InitListExpr *InitList,
2220 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002221 // FIXME: We only perform rudimentary checking of list
2222 // initializations at this point, then assume that any list
2223 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002224 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002225 // do all of the necessary checking. C++0x initializer lists will
2226 // force us to perform more checking here.
2227 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2228
Douglas Gregord6542d82009-12-22 15:35:07 +00002229 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002230
2231 // C++ [dcl.init]p13:
2232 // If T is a scalar type, then a declaration of the form
2233 //
2234 // T x = { a };
2235 //
2236 // is equivalent to
2237 //
2238 // T x = a;
2239 if (DestType->isScalarType()) {
2240 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2241 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2242 return;
2243 }
2244
2245 // Assume scalar initialization from a single value works.
2246 } else if (DestType->isAggregateType()) {
2247 // Assume aggregate initialization works.
2248 } else if (DestType->isVectorType()) {
2249 // Assume vector initialization works.
2250 } else if (DestType->isReferenceType()) {
2251 // FIXME: C++0x defines behavior for this.
2252 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2253 return;
2254 } else if (DestType->isRecordType()) {
2255 // FIXME: C++0x defines behavior for this
2256 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2257 }
2258
2259 // Add a general "list initialization" step.
2260 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002261}
2262
2263/// \brief Try a reference initialization that involves calling a conversion
2264/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002265static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2266 const InitializedEntity &Entity,
2267 const InitializationKind &Kind,
2268 Expr *Initializer,
2269 bool AllowRValues,
2270 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002271 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002272 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2273 QualType T1 = cv1T1.getUnqualifiedType();
2274 QualType cv2T2 = Initializer->getType();
2275 QualType T2 = cv2T2.getUnqualifiedType();
2276
2277 bool DerivedToBase;
2278 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2279 T1, T2, DerivedToBase) &&
2280 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002281 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002282
2283 // Build the candidate set directly in the initialization sequence
2284 // structure, so that it will persist if we fail.
2285 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2286 CandidateSet.clear();
2287
2288 // Determine whether we are allowed to call explicit constructors or
2289 // explicit conversion operators.
2290 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2291
2292 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002293 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2294 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002295 // The type we're converting to is a class type. Enumerate its constructors
2296 // to see if there is a suitable conversion.
2297 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
Douglas Gregor20093b42009-12-09 23:02:17 +00002298 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002299 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002300 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002301 NamedDecl *D = *Con;
2302 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2303
Douglas Gregor20093b42009-12-09 23:02:17 +00002304 // Find the constructor (which may be a template).
2305 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002306 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002307 if (ConstructorTmpl)
2308 Constructor = cast<CXXConstructorDecl>(
2309 ConstructorTmpl->getTemplatedDecl());
2310 else
John McCall9aa472c2010-03-19 07:35:19 +00002311 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002312
2313 if (!Constructor->isInvalidDecl() &&
2314 Constructor->isConvertingConstructor(AllowExplicit)) {
2315 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002316 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002317 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002318 &Initializer, 1, CandidateSet);
2319 else
John McCall9aa472c2010-03-19 07:35:19 +00002320 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002321 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002322 }
2323 }
2324 }
2325
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002326 const RecordType *T2RecordType = 0;
2327 if ((T2RecordType = T2->getAs<RecordType>()) &&
2328 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002329 // The type we're converting from is a class type, enumerate its conversion
2330 // functions.
2331 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2332
2333 // Determine the type we are converting to. If we are allowed to
2334 // convert to an rvalue, take the type that the destination type
2335 // refers to.
2336 QualType ToType = AllowRValues? cv1T1 : DestType;
2337
John McCalleec51cf2010-01-20 00:46:10 +00002338 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002339 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002340 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2341 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002342 NamedDecl *D = *I;
2343 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2344 if (isa<UsingShadowDecl>(D))
2345 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2346
2347 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2348 CXXConversionDecl *Conv;
2349 if (ConvTemplate)
2350 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2351 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002352 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002353
2354 // If the conversion function doesn't return a reference type,
2355 // it can't be considered for this conversion unless we're allowed to
2356 // consider rvalues.
2357 // FIXME: Do we need to make sure that we only consider conversion
2358 // candidates with reference-compatible results? That might be needed to
2359 // break recursion.
2360 if ((AllowExplicit || !Conv->isExplicit()) &&
2361 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2362 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002363 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002364 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002365 ToType, CandidateSet);
2366 else
John McCall9aa472c2010-03-19 07:35:19 +00002367 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002368 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002369 }
2370 }
2371 }
2372
2373 SourceLocation DeclLoc = Initializer->getLocStart();
2374
2375 // Perform overload resolution. If it fails, return the failed result.
2376 OverloadCandidateSet::iterator Best;
2377 if (OverloadingResult Result
2378 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2379 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002380
Douglas Gregor20093b42009-12-09 23:02:17 +00002381 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002382
2383 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002384 if (isa<CXXConversionDecl>(Function))
2385 T2 = Function->getResultType();
2386 else
2387 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002388
2389 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002390 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002391 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002392
2393 // Determine whether we need to perform derived-to-base or
2394 // cv-qualification adjustments.
Sebastian Redl906082e2010-07-20 04:20:21 +00002395 ImplicitCastExpr::ResultCategory Category = ImplicitCastExpr::RValue;
2396 if (T2->isLValueReferenceType())
2397 Category = ImplicitCastExpr::LValue;
2398 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
2399 Category = RRef->getPointeeType()->isFunctionType() ?
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002400 ImplicitCastExpr::LValue : ImplicitCastExpr::XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002401
Douglas Gregor20093b42009-12-09 23:02:17 +00002402 bool NewDerivedToBase = false;
2403 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregor63982352010-07-13 18:40:04 +00002404 = S.CompareReferenceRelationship(DeclLoc, T1,
2405 T2.getNonLValueExprType(S.Context),
Douglas Gregor20093b42009-12-09 23:02:17 +00002406 NewDerivedToBase);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002407 if (NewRefRelationship == Sema::Ref_Incompatible) {
2408 // If the type we've converted to is not reference-related to the
2409 // type we're looking for, then there is another conversion step
2410 // we need to perform to produce a temporary of the right type
2411 // that we'll be binding to.
2412 ImplicitConversionSequence ICS;
2413 ICS.setStandard();
2414 ICS.Standard = Best->FinalConversion;
2415 T2 = ICS.Standard.getToType(2);
2416 Sequence.AddConversionSequenceStep(ICS, T2);
2417 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002418 Sequence.AddDerivedToBaseCastStep(
2419 S.Context.getQualifiedType(T1,
2420 T2.getNonReferenceType().getQualifiers()),
Sebastian Redl906082e2010-07-20 04:20:21 +00002421 Category);
Douglas Gregor20093b42009-12-09 23:02:17 +00002422
2423 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
Sebastian Redl906082e2010-07-20 04:20:21 +00002424 Sequence.AddQualificationConversionStep(cv1T1, Category);
Douglas Gregor20093b42009-12-09 23:02:17 +00002425
2426 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2427 return OR_Success;
2428}
2429
Sebastian Redl4680bf22010-06-30 18:13:39 +00002430/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor20093b42009-12-09 23:02:17 +00002431static void TryReferenceInitialization(Sema &S,
2432 const InitializedEntity &Entity,
2433 const InitializationKind &Kind,
2434 Expr *Initializer,
2435 InitializationSequence &Sequence) {
2436 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002437
Douglas Gregord6542d82009-12-22 15:35:07 +00002438 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002439 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002440 Qualifiers T1Quals;
2441 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002442 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002443 Qualifiers T2Quals;
2444 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002445 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002446
Douglas Gregor20093b42009-12-09 23:02:17 +00002447 // If the initializer is the address of an overloaded function, try
2448 // to resolve the overloaded function. If all goes well, T2 is the
2449 // type of the resulting function.
2450 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002451 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002452 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2453 T1,
John McCall6bb80172010-03-30 21:47:33 +00002454 false,
2455 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002456 if (!Fn) {
2457 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2458 return;
2459 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002460
John McCall6bb80172010-03-30 21:47:33 +00002461 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002462 cv2T2 = Fn->getType();
2463 T2 = cv2T2.getUnqualifiedType();
2464 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002465
Douglas Gregor20093b42009-12-09 23:02:17 +00002466 // Compute some basic properties of the types and the initializer.
2467 bool isLValueRef = DestType->isLValueReferenceType();
2468 bool isRValueRef = !isLValueRef;
2469 bool DerivedToBase = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002470 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002471 Sema::ReferenceCompareResult RefRelationship
2472 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002473
Douglas Gregor20093b42009-12-09 23:02:17 +00002474 // C++0x [dcl.init.ref]p5:
2475 // A reference to type "cv1 T1" is initialized by an expression of type
2476 // "cv2 T2" as follows:
2477 //
2478 // - If the reference is an lvalue reference and the initializer
2479 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002480 // Note the analogous bullet points for rvlaue refs to functions. Because
2481 // there are no function rvalues in C++, rvalue refs to functions are treated
2482 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002483 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002484 bool T1Function = T1->isFunctionType();
2485 if (isLValueRef || T1Function) {
2486 if (InitCategory.isLValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002487 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2488 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2489 // reference-compatible with "cv2 T2," or
2490 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002491 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002492 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002493 // can occur. However, we do pay attention to whether it is a bit-field
2494 // to decide whether we're actually binding to a temporary created from
2495 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002496 if (DerivedToBase)
2497 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002498 S.Context.getQualifiedType(T1, T2Quals),
Sebastian Redl906082e2010-07-20 04:20:21 +00002499 ImplicitCastExpr::LValue);
Chandler Carruth5535c382010-01-12 20:32:25 +00002500 if (T1Quals != T2Quals)
Sebastian Redl906082e2010-07-20 04:20:21 +00002501 Sequence.AddQualificationConversionStep(cv1T1,ImplicitCastExpr::LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002502 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002503 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002504 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002505 return;
2506 }
2507
2508 // - has a class type (i.e., T2 is a class type), where T1 is not
2509 // reference-related to T2, and can be implicitly converted to an
2510 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2511 // with "cv3 T3" (this conversion is selected by enumerating the
2512 // applicable conversion functions (13.3.1.6) and choosing the best
2513 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002514 // If we have an rvalue ref to function type here, the rhs must be
2515 // an rvalue.
2516 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2517 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002518 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2519 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002520 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002521 Sequence);
2522 if (ConvOvlResult == OR_Success)
2523 return;
John McCall1d318332010-01-12 00:44:57 +00002524 if (ConvOvlResult != OR_No_Viable_Function) {
2525 Sequence.SetOverloadFailure(
2526 InitializationSequence::FK_ReferenceInitOverloadFailed,
2527 ConvOvlResult);
2528 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002529 }
2530 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002531
Douglas Gregor20093b42009-12-09 23:02:17 +00002532 // - Otherwise, the reference shall be an lvalue reference to a
2533 // non-volatile const type (i.e., cv1 shall be const), or the reference
2534 // shall be an rvalue reference and the initializer expression shall
Sebastian Redl4680bf22010-06-30 18:13:39 +00002535 // be an rvalue or have a function type.
2536 // We handled the function type stuff above.
Douglas Gregoref06e242010-01-29 19:39:15 +00002537 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redl4680bf22010-06-30 18:13:39 +00002538 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002539 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2540 Sequence.SetOverloadFailure(
2541 InitializationSequence::FK_ReferenceInitOverloadFailed,
2542 ConvOvlResult);
2543 else if (isLValueRef)
Sebastian Redl4680bf22010-06-30 18:13:39 +00002544 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002545 ? (RefRelationship == Sema::Ref_Related
2546 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2547 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2548 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2549 else
2550 Sequence.SetFailed(
2551 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002552
Douglas Gregor20093b42009-12-09 23:02:17 +00002553 return;
2554 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002555
2556 // - [If T1 is not a function type], if T2 is a class type and
2557 if (!T1Function && T2->isRecordType()) {
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002558 bool isXValue = InitCategory.isXValue();
Douglas Gregor20093b42009-12-09 23:02:17 +00002559 // - the initializer expression is an rvalue and "cv1 T1" is
2560 // reference-compatible with "cv2 T2", or
Sebastian Redl4680bf22010-06-30 18:13:39 +00002561 if (InitCategory.isRValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002562 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002563 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2564 // compiler the freedom to perform a copy here or bind to the
2565 // object, while C++0x requires that we bind directly to the
2566 // object. Hence, we always bind to the object without making an
2567 // extra copy. However, in C++03 requires that we check for the
2568 // presence of a suitable copy constructor:
2569 //
2570 // The constructor that would be used to make the copy shall
2571 // be callable whether or not the copy is actually done.
2572 if (!S.getLangOptions().CPlusPlus0x)
2573 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2574
Douglas Gregor20093b42009-12-09 23:02:17 +00002575 if (DerivedToBase)
2576 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002577 S.Context.getQualifiedType(T1, T2Quals),
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002578 isXValue ? ImplicitCastExpr::XValue
2579 : ImplicitCastExpr::RValue);
Chandler Carruth5535c382010-01-12 20:32:25 +00002580 if (T1Quals != T2Quals)
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002581 Sequence.AddQualificationConversionStep(cv1T1,
2582 isXValue ? ImplicitCastExpr::XValue
2583 : ImplicitCastExpr::RValue);
2584 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00002585 return;
2586 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002587
Douglas Gregor20093b42009-12-09 23:02:17 +00002588 // - T1 is not reference-related to T2 and the initializer expression
2589 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2590 // conversion is selected by enumerating the applicable conversion
2591 // functions (13.3.1.6) and choosing the best one through overload
2592 // resolution (13.3)),
2593 if (RefRelationship == Sema::Ref_Incompatible) {
2594 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2595 Kind, Initializer,
2596 /*AllowRValues=*/true,
2597 Sequence);
2598 if (ConvOvlResult)
2599 Sequence.SetOverloadFailure(
2600 InitializationSequence::FK_ReferenceInitOverloadFailed,
2601 ConvOvlResult);
2602
2603 return;
2604 }
2605
2606 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2607 return;
2608 }
2609
2610 // - If the initializer expression is an rvalue, with T2 an array type,
2611 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2612 // is bound to the object represented by the rvalue (see 3.10).
2613 // FIXME: How can an array type be reference-compatible with anything?
2614 // Don't we mean the element types of T1 and T2?
2615
2616 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2617 // from the initializer expression using the rules for a non-reference
2618 // copy initialization (8.5). The reference is then bound to the
2619 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002620
Douglas Gregor20093b42009-12-09 23:02:17 +00002621 // Determine whether we are allowed to call explicit constructors or
2622 // explicit conversion operators.
2623 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002624
2625 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2626
2627 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2628 /*SuppressUserConversions*/ false,
2629 AllowExplicit,
2630 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002631 // FIXME: Use the conversion function set stored in ICS to turn
2632 // this into an overloading ambiguity diagnostic. However, we need
2633 // to keep that set as an OverloadCandidateSet rather than as some
2634 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002635 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2636 Sequence.SetOverloadFailure(
2637 InitializationSequence::FK_ReferenceInitOverloadFailed,
2638 ConvOvlResult);
2639 else
2640 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002641 return;
2642 }
2643
2644 // [...] If T1 is reference-related to T2, cv1 must be the
2645 // same cv-qualification as, or greater cv-qualification
2646 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002647 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2648 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002649 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002650 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002651 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2652 return;
2653 }
2654
Douglas Gregor20093b42009-12-09 23:02:17 +00002655 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2656 return;
2657}
2658
2659/// \brief Attempt character array initialization from a string literal
2660/// (C++ [dcl.init.string], C99 6.7.8).
2661static void TryStringLiteralInitialization(Sema &S,
2662 const InitializedEntity &Entity,
2663 const InitializationKind &Kind,
2664 Expr *Initializer,
2665 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002666 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002667 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002668}
2669
Douglas Gregor20093b42009-12-09 23:02:17 +00002670/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2671/// enumerates the constructors of the initialized entity and performs overload
2672/// resolution to select the best.
2673static void TryConstructorInitialization(Sema &S,
2674 const InitializedEntity &Entity,
2675 const InitializationKind &Kind,
2676 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002677 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002678 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002679 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002680
2681 // Build the candidate set directly in the initialization sequence
2682 // structure, so that it will persist if we fail.
2683 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2684 CandidateSet.clear();
2685
2686 // Determine whether we are allowed to call explicit constructors or
2687 // explicit conversion operators.
2688 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2689 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002690 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002691
2692 // The type we're constructing needs to be complete.
2693 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002694 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002695 return;
2696 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002697
2698 // The type we're converting to is a class type. Enumerate its constructors
2699 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002700 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2701 assert(DestRecordType && "Constructor initialization requires record type");
2702 CXXRecordDecl *DestRecordDecl
2703 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2704
Douglas Gregor51c56d62009-12-14 20:49:26 +00002705 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002706 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002707 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002708 NamedDecl *D = *Con;
2709 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002710 bool SuppressUserConversions = false;
2711
Douglas Gregor51c56d62009-12-14 20:49:26 +00002712 // Find the constructor (which may be a template).
2713 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002714 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002715 if (ConstructorTmpl)
2716 Constructor = cast<CXXConstructorDecl>(
2717 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002718 else {
John McCall9aa472c2010-03-19 07:35:19 +00002719 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002720
2721 // If we're performing copy initialization using a copy constructor, we
2722 // suppress user-defined conversions on the arguments.
2723 // FIXME: Move constructors?
2724 if (Kind.getKind() == InitializationKind::IK_Copy &&
2725 Constructor->isCopyConstructor())
2726 SuppressUserConversions = true;
2727 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002728
2729 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002730 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002731 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002732 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002733 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002734 Args, NumArgs, CandidateSet,
2735 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002736 else
John McCall9aa472c2010-03-19 07:35:19 +00002737 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002738 Args, NumArgs, CandidateSet,
2739 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002740 }
2741 }
2742
2743 SourceLocation DeclLoc = Kind.getLocation();
2744
2745 // Perform overload resolution. If it fails, return the failed result.
2746 OverloadCandidateSet::iterator Best;
2747 if (OverloadingResult Result
2748 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2749 Sequence.SetOverloadFailure(
2750 InitializationSequence::FK_ConstructorOverloadFailed,
2751 Result);
2752 return;
2753 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002754
2755 // C++0x [dcl.init]p6:
2756 // If a program calls for the default initialization of an object
2757 // of a const-qualified type T, T shall be a class type with a
2758 // user-provided default constructor.
2759 if (Kind.getKind() == InitializationKind::IK_Default &&
2760 Entity.getType().isConstQualified() &&
2761 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2762 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2763 return;
2764 }
2765
Douglas Gregor51c56d62009-12-14 20:49:26 +00002766 // Add the constructor initialization step. Any cv-qualification conversion is
2767 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002768 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002769 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002770 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002771 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002772}
2773
Douglas Gregor71d17402009-12-15 00:01:57 +00002774/// \brief Attempt value initialization (C++ [dcl.init]p7).
2775static void TryValueInitialization(Sema &S,
2776 const InitializedEntity &Entity,
2777 const InitializationKind &Kind,
2778 InitializationSequence &Sequence) {
2779 // C++ [dcl.init]p5:
2780 //
2781 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002782 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002783
2784 // -- if T is an array type, then each element is value-initialized;
2785 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2786 T = AT->getElementType();
2787
2788 if (const RecordType *RT = T->getAs<RecordType>()) {
2789 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2790 // -- if T is a class type (clause 9) with a user-declared
2791 // constructor (12.1), then the default constructor for T is
2792 // called (and the initialization is ill-formed if T has no
2793 // accessible default constructor);
2794 //
2795 // FIXME: we really want to refer to a single subobject of the array,
2796 // but Entity doesn't have a way to capture that (yet).
2797 if (ClassDecl->hasUserDeclaredConstructor())
2798 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2799
Douglas Gregor16006c92009-12-16 18:50:27 +00002800 // -- if T is a (possibly cv-qualified) non-union class type
2801 // without a user-provided constructor, then the object is
2802 // zero-initialized and, if T’s implicitly-declared default
2803 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002804 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002805 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002806 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002807 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2808 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002809 }
2810 }
2811
Douglas Gregord6542d82009-12-22 15:35:07 +00002812 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002813 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2814}
2815
Douglas Gregor99a2e602009-12-16 01:38:02 +00002816/// \brief Attempt default initialization (C++ [dcl.init]p6).
2817static void TryDefaultInitialization(Sema &S,
2818 const InitializedEntity &Entity,
2819 const InitializationKind &Kind,
2820 InitializationSequence &Sequence) {
2821 assert(Kind.getKind() == InitializationKind::IK_Default);
2822
2823 // C++ [dcl.init]p6:
2824 // To default-initialize an object of type T means:
2825 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002826 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002827 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2828 DestType = Array->getElementType();
2829
2830 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2831 // constructor for T is called (and the initialization is ill-formed if
2832 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002833 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002834 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2835 Sequence);
2836 }
2837
2838 // - otherwise, no initialization is performed.
2839 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2840
2841 // If a program calls for the default initialization of an object of
2842 // a const-qualified type T, T shall be a class type with a user-provided
2843 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002844 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002845 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2846}
2847
Douglas Gregor20093b42009-12-09 23:02:17 +00002848/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2849/// which enumerates all conversion functions and performs overload resolution
2850/// to select the best.
2851static void TryUserDefinedConversion(Sema &S,
2852 const InitializedEntity &Entity,
2853 const InitializationKind &Kind,
2854 Expr *Initializer,
2855 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002856 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2857
Douglas Gregord6542d82009-12-22 15:35:07 +00002858 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002859 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2860 QualType SourceType = Initializer->getType();
2861 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2862 "Must have a class type to perform a user-defined conversion");
2863
2864 // Build the candidate set directly in the initialization sequence
2865 // structure, so that it will persist if we fail.
2866 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2867 CandidateSet.clear();
2868
2869 // Determine whether we are allowed to call explicit constructors or
2870 // explicit conversion operators.
2871 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2872
2873 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2874 // The type we're converting to is a class type. Enumerate its constructors
2875 // to see if there is a suitable conversion.
2876 CXXRecordDecl *DestRecordDecl
2877 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2878
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002879 // Try to complete the type we're converting to.
2880 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002881 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002882 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002883 Con != ConEnd; ++Con) {
2884 NamedDecl *D = *Con;
2885 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002886
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002887 // Find the constructor (which may be a template).
2888 CXXConstructorDecl *Constructor = 0;
2889 FunctionTemplateDecl *ConstructorTmpl
2890 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002891 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002892 Constructor = cast<CXXConstructorDecl>(
2893 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002894 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002895 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002896
2897 if (!Constructor->isInvalidDecl() &&
2898 Constructor->isConvertingConstructor(AllowExplicit)) {
2899 if (ConstructorTmpl)
2900 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2901 /*ExplicitArgs*/ 0,
2902 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002903 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002904 else
2905 S.AddOverloadCandidate(Constructor, FoundDecl,
2906 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002907 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002908 }
2909 }
2910 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002911 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002912
2913 SourceLocation DeclLoc = Initializer->getLocStart();
2914
Douglas Gregor4a520a22009-12-14 17:27:33 +00002915 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2916 // The type we're converting from is a class type, enumerate its conversion
2917 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002918
Eli Friedman33c2da92009-12-20 22:12:03 +00002919 // We can only enumerate the conversion functions for a complete type; if
2920 // the type isn't complete, simply skip this step.
2921 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2922 CXXRecordDecl *SourceRecordDecl
2923 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002924
John McCalleec51cf2010-01-20 00:46:10 +00002925 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002926 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002927 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002928 E = Conversions->end();
2929 I != E; ++I) {
2930 NamedDecl *D = *I;
2931 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2932 if (isa<UsingShadowDecl>(D))
2933 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2934
2935 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2936 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002937 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002938 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002939 else
John McCall32daa422010-03-31 01:36:47 +00002940 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00002941
2942 if (AllowExplicit || !Conv->isExplicit()) {
2943 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002944 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002945 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002946 CandidateSet);
2947 else
John McCall9aa472c2010-03-19 07:35:19 +00002948 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00002949 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002950 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002951 }
2952 }
2953 }
2954
Douglas Gregor4a520a22009-12-14 17:27:33 +00002955 // Perform overload resolution. If it fails, return the failed result.
2956 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002957 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002958 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2959 Sequence.SetOverloadFailure(
2960 InitializationSequence::FK_UserConversionOverloadFailed,
2961 Result);
2962 return;
2963 }
John McCall1d318332010-01-12 00:44:57 +00002964
Douglas Gregor4a520a22009-12-14 17:27:33 +00002965 FunctionDecl *Function = Best->Function;
2966
2967 if (isa<CXXConstructorDecl>(Function)) {
2968 // Add the user-defined conversion step. Any cv-qualification conversion is
2969 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00002970 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002971 return;
2972 }
2973
2974 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002975 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002976 if (ConvType->getAs<RecordType>()) {
2977 // If we're converting to a class type, there may be an copy if
2978 // the resulting temporary object (possible to create an object of
2979 // a base class type). That copy is not a separate conversion, so
2980 // we just make a note of the actual destination type (possibly a
2981 // base class of the type returned by the conversion function) and
2982 // let the user-defined conversion step handle the conversion.
2983 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
2984 return;
2985 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002986
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002987 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
2988
2989 // If the conversion following the call to the conversion function
2990 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00002991 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2992 Best->FinalConversion.Third) {
2993 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002994 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002995 ICS.Standard = Best->FinalConversion;
2996 Sequence.AddConversionSequenceStep(ICS, DestType);
2997 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002998}
2999
John McCall369371c2010-06-04 02:29:22 +00003000bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
3001 const InitializedEntity &Entity,
3002 Expr *Initializer,
3003 bool SuppressUserConversions,
3004 bool AllowExplicitConversions,
3005 bool InOverloadResolution) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003006 ImplicitConversionSequence ICS
John McCall369371c2010-06-04 02:29:22 +00003007 = TryImplicitConversion(Initializer, Entity.getType(),
3008 SuppressUserConversions,
3009 AllowExplicitConversions,
3010 InOverloadResolution);
3011 if (ICS.isBad()) return true;
3012
3013 // Perform the actual conversion.
Douglas Gregord6542d82009-12-22 15:35:07 +00003014 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
John McCall369371c2010-06-04 02:29:22 +00003015 return false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003016}
3017
3018InitializationSequence::InitializationSequence(Sema &S,
3019 const InitializedEntity &Entity,
3020 const InitializationKind &Kind,
3021 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003022 unsigned NumArgs)
3023 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003024 ASTContext &Context = S.Context;
3025
3026 // C++0x [dcl.init]p16:
3027 // The semantics of initializers are as follows. The destination type is
3028 // the type of the object or reference being initialized and the source
3029 // type is the type of the initializer expression. The source type is not
3030 // defined when the initializer is a braced-init-list or when it is a
3031 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003032 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003033
3034 if (DestType->isDependentType() ||
3035 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3036 SequenceKind = DependentSequence;
3037 return;
3038 }
3039
3040 QualType SourceType;
3041 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003042 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003043 Initializer = Args[0];
3044 if (!isa<InitListExpr>(Initializer))
3045 SourceType = Initializer->getType();
3046 }
3047
3048 // - If the initializer is a braced-init-list, the object is
3049 // list-initialized (8.5.4).
3050 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3051 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003052 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003053 }
3054
3055 // - If the destination type is a reference type, see 8.5.3.
3056 if (DestType->isReferenceType()) {
3057 // C++0x [dcl.init.ref]p1:
3058 // A variable declared to be a T& or T&&, that is, "reference to type T"
3059 // (8.3.2), shall be initialized by an object, or function, of type T or
3060 // by an object that can be converted into a T.
3061 // (Therefore, multiple arguments are not permitted.)
3062 if (NumArgs != 1)
3063 SetFailed(FK_TooManyInitsForReference);
3064 else
3065 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3066 return;
3067 }
3068
3069 // - If the destination type is an array of characters, an array of
3070 // char16_t, an array of char32_t, or an array of wchar_t, and the
3071 // initializer is a string literal, see 8.5.2.
3072 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3073 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3074 return;
3075 }
3076
3077 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003078 if (Kind.getKind() == InitializationKind::IK_Value ||
3079 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003080 TryValueInitialization(S, Entity, Kind, *this);
3081 return;
3082 }
3083
Douglas Gregor99a2e602009-12-16 01:38:02 +00003084 // Handle default initialization.
3085 if (Kind.getKind() == InitializationKind::IK_Default){
3086 TryDefaultInitialization(S, Entity, Kind, *this);
3087 return;
3088 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003089
Douglas Gregor20093b42009-12-09 23:02:17 +00003090 // - Otherwise, if the destination type is an array, the program is
3091 // ill-formed.
3092 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3093 if (AT->getElementType()->isAnyCharacterType())
3094 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3095 else
3096 SetFailed(FK_ArrayNeedsInitList);
3097
3098 return;
3099 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003100
3101 // Handle initialization in C
3102 if (!S.getLangOptions().CPlusPlus) {
3103 setSequenceKind(CAssignment);
3104 AddCAssignmentStep(DestType);
3105 return;
3106 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003107
3108 // - If the destination type is a (possibly cv-qualified) class type:
3109 if (DestType->isRecordType()) {
3110 // - If the initialization is direct-initialization, or if it is
3111 // copy-initialization where the cv-unqualified version of the
3112 // source type is the same class as, or a derived class of, the
3113 // class of the destination, constructors are considered. [...]
3114 if (Kind.getKind() == InitializationKind::IK_Direct ||
3115 (Kind.getKind() == InitializationKind::IK_Copy &&
3116 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3117 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003118 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003119 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003120 // - Otherwise (i.e., for the remaining copy-initialization cases),
3121 // user-defined conversion sequences that can convert from the source
3122 // type to the destination type or (when a conversion function is
3123 // used) to a derived class thereof are enumerated as described in
3124 // 13.3.1.4, and the best one is chosen through overload resolution
3125 // (13.3).
3126 else
3127 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3128 return;
3129 }
3130
Douglas Gregor99a2e602009-12-16 01:38:02 +00003131 if (NumArgs > 1) {
3132 SetFailed(FK_TooManyInitsForScalar);
3133 return;
3134 }
3135 assert(NumArgs == 1 && "Zero-argument case handled above");
3136
Douglas Gregor20093b42009-12-09 23:02:17 +00003137 // - Otherwise, if the source type is a (possibly cv-qualified) class
3138 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003139 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003140 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3141 return;
3142 }
3143
3144 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003145 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003146 // conversions (Clause 4) will be used, if necessary, to convert the
3147 // initializer expression to the cv-unqualified version of the
3148 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003149 if (S.TryImplicitConversion(*this, Entity, Initializer,
3150 /*SuppressUserConversions*/ true,
3151 /*AllowExplicitConversions*/ false,
3152 /*InOverloadResolution*/ false))
3153 SetFailed(InitializationSequence::FK_ConversionFailed);
3154 else
3155 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003156}
3157
3158InitializationSequence::~InitializationSequence() {
3159 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3160 StepEnd = Steps.end();
3161 Step != StepEnd; ++Step)
3162 Step->Destroy();
3163}
3164
3165//===----------------------------------------------------------------------===//
3166// Perform initialization
3167//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003168static Sema::AssignmentAction
3169getAssignmentAction(const InitializedEntity &Entity) {
3170 switch(Entity.getKind()) {
3171 case InitializedEntity::EK_Variable:
3172 case InitializedEntity::EK_New:
3173 return Sema::AA_Initializing;
3174
3175 case InitializedEntity::EK_Parameter:
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003176 if (Entity.getDecl() &&
3177 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3178 return Sema::AA_Sending;
3179
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003180 return Sema::AA_Passing;
3181
3182 case InitializedEntity::EK_Result:
3183 return Sema::AA_Returning;
3184
3185 case InitializedEntity::EK_Exception:
3186 case InitializedEntity::EK_Base:
3187 llvm_unreachable("No assignment action for C++-specific initialization");
3188 break;
3189
3190 case InitializedEntity::EK_Temporary:
3191 // FIXME: Can we tell apart casting vs. converting?
3192 return Sema::AA_Casting;
3193
3194 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003195 case InitializedEntity::EK_ArrayElement:
3196 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003197 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003198 return Sema::AA_Initializing;
3199 }
3200
3201 return Sema::AA_Converting;
3202}
3203
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003204/// \brief Whether we should binding a created object as a temporary when
3205/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003206static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003207 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003208 case InitializedEntity::EK_ArrayElement:
3209 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003210 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003211 case InitializedEntity::EK_New:
3212 case InitializedEntity::EK_Variable:
3213 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003214 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003215 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003216 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003217 return false;
3218
3219 case InitializedEntity::EK_Parameter:
3220 case InitializedEntity::EK_Temporary:
3221 return true;
3222 }
3223
3224 llvm_unreachable("missed an InitializedEntity kind?");
3225}
3226
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003227/// \brief Whether the given entity, when initialized with an object
3228/// created for that initialization, requires destruction.
3229static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3230 switch (Entity.getKind()) {
3231 case InitializedEntity::EK_Member:
3232 case InitializedEntity::EK_Result:
3233 case InitializedEntity::EK_New:
3234 case InitializedEntity::EK_Base:
3235 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003236 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003237 return false;
3238
3239 case InitializedEntity::EK_Variable:
3240 case InitializedEntity::EK_Parameter:
3241 case InitializedEntity::EK_Temporary:
3242 case InitializedEntity::EK_ArrayElement:
3243 case InitializedEntity::EK_Exception:
3244 return true;
3245 }
3246
3247 llvm_unreachable("missed an InitializedEntity kind?");
3248}
3249
Douglas Gregor523d46a2010-04-18 07:40:54 +00003250/// \brief Make a (potentially elidable) temporary copy of the object
3251/// provided by the given initializer by calling the appropriate copy
3252/// constructor.
3253///
3254/// \param S The Sema object used for type-checking.
3255///
3256/// \param T The type of the temporary object, which must either by
3257/// the type of the initializer expression or a superclass thereof.
3258///
3259/// \param Enter The entity being initialized.
3260///
3261/// \param CurInit The initializer expression.
3262///
3263/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3264/// is permitted in C++03 (but not C++0x) when binding a reference to
3265/// an rvalue.
3266///
3267/// \returns An expression that copies the initializer expression into
3268/// a temporary object, or an error expression if a copy could not be
3269/// created.
Douglas Gregor2f599792010-04-02 18:24:57 +00003270static Sema::OwningExprResult CopyObject(Sema &S,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003271 QualType T,
Douglas Gregor2f599792010-04-02 18:24:57 +00003272 const InitializedEntity &Entity,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003273 Sema::OwningExprResult CurInit,
3274 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003275 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003276 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003277 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003278 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003279 Class = cast<CXXRecordDecl>(Record->getDecl());
3280 if (!Class)
3281 return move(CurInit);
3282
3283 // C++0x [class.copy]p34:
3284 // When certain criteria are met, an implementation is allowed to
3285 // omit the copy/move construction of a class object, even if the
3286 // copy/move constructor and/or destructor for the object have
3287 // side effects. [...]
3288 // - when a temporary class object that has not been bound to a
3289 // reference (12.2) would be copied/moved to a class object
3290 // with the same cv-unqualified type, the copy/move operation
3291 // can be omitted by constructing the temporary object
3292 // directly into the target of the omitted copy/move
3293 //
3294 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003295 // elision for return statements and throw expressions are handled as part
3296 // of constructor initialization, while copy elision for exception handlers
3297 // is handled by the run-time.
Douglas Gregor2f599792010-04-02 18:24:57 +00003298 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregor523d46a2010-04-18 07:40:54 +00003299 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003300 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003301 switch (Entity.getKind()) {
3302 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003303 Loc = Entity.getReturnLoc();
3304 break;
3305
3306 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003307 Loc = Entity.getThrowLoc();
3308 break;
3309
3310 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003311 Loc = Entity.getDecl()->getLocation();
3312 break;
3313
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003314 case InitializedEntity::EK_ArrayElement:
3315 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003316 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003317 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003318 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003319 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003320 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003321 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003322 Loc = CurInitExpr->getLocStart();
3323 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003324 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003325
3326 // Make sure that the type we are copying is complete.
3327 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3328 return move(CurInit);
3329
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003330 // Perform overload resolution using the class's copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003331 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003332 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003333 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003334 Con != ConEnd; ++Con) {
Douglas Gregor2f599792010-04-02 18:24:57 +00003335 // Only consider copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003336 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3337 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor153b3ba2010-04-18 02:16:12 +00003338 !Constructor->isCopyConstructor() ||
3339 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003340 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003341
3342 DeclAccessPair FoundDecl
3343 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3344 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003345 &CurInitExpr, 1, CandidateSet);
Douglas Gregor2f599792010-04-02 18:24:57 +00003346 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003347
3348 OverloadCandidateSet::iterator Best;
3349 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3350 case OR_Success:
3351 break;
3352
3353 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003354 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3355 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3356 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003357 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003358 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003359 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3360 &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003361 if (!IsExtraneousCopy || S.isSFINAEContext())
3362 return S.ExprError();
3363 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003364
3365 case OR_Ambiguous:
3366 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003367 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003368 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003369 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3370 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003371 return S.ExprError();
3372
3373 case OR_Deleted:
3374 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003375 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003376 << CurInitExpr->getSourceRange();
3377 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3378 << Best->Function->isDeleted();
3379 return S.ExprError();
3380 }
3381
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003382 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3383 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3384 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003385
Anders Carlsson9a68a672010-04-21 18:47:17 +00003386 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003387 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003388
3389 if (IsExtraneousCopy) {
3390 // If this is a totally extraneous copy for C++03 reference
3391 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003392 // expression. We don't generate an (elided) copy operation here
3393 // because doing so would require us to pass down a flag to avoid
3394 // infinite recursion, where each step adds another extraneous,
3395 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003396
Douglas Gregor2559a702010-04-18 07:57:34 +00003397 // Instantiate the default arguments of any extra parameters in
3398 // the selected copy constructor, as if we were going to create a
3399 // proper call to the copy constructor.
3400 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3401 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3402 if (S.RequireCompleteType(Loc, Parm->getType(),
3403 S.PDiag(diag::err_call_incomplete_argument)))
3404 break;
3405
3406 // Build the default argument expression; we don't actually care
3407 // if this succeeds or not, because this routine will complain
3408 // if there was a problem.
3409 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3410 }
3411
Douglas Gregor523d46a2010-04-18 07:40:54 +00003412 return S.Owned(CurInitExpr);
3413 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003414
3415 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003416 // constructor call (we might have derived-to-base conversions, or
3417 // the copy constructor may have default arguments).
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003418 if (S.CompleteConstructorCall(Constructor,
3419 Sema::MultiExprArg(S,
3420 (void **)&CurInitExpr,
3421 1),
3422 Loc, ConstructorArgs))
3423 return S.ExprError();
3424
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003425 // Actually perform the constructor call.
3426 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
3427 move_arg(ConstructorArgs));
3428
3429 // If we're supposed to bind temporaries, do so.
3430 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3431 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3432 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003433}
Douglas Gregor20093b42009-12-09 23:02:17 +00003434
Douglas Gregora41a8c52010-04-22 00:20:18 +00003435void InitializationSequence::PrintInitLocationNote(Sema &S,
3436 const InitializedEntity &Entity) {
3437 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3438 if (Entity.getDecl()->getLocation().isInvalid())
3439 return;
3440
3441 if (Entity.getDecl()->getDeclName())
3442 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3443 << Entity.getDecl()->getDeclName();
3444 else
3445 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3446 }
3447}
3448
Douglas Gregor20093b42009-12-09 23:02:17 +00003449Action::OwningExprResult
3450InitializationSequence::Perform(Sema &S,
3451 const InitializedEntity &Entity,
3452 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003453 Action::MultiExprArg Args,
3454 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003455 if (SequenceKind == FailedSequence) {
3456 unsigned NumArgs = Args.size();
3457 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3458 return S.ExprError();
3459 }
3460
3461 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003462 // If the declaration is a non-dependent, incomplete array type
3463 // that has an initializer, then its type will be completed once
3464 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003465 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003466 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003467 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003468 if (const IncompleteArrayType *ArrayT
3469 = S.Context.getAsIncompleteArrayType(DeclType)) {
3470 // FIXME: We don't currently have the ability to accurately
3471 // compute the length of an initializer list without
3472 // performing full type-checking of the initializer list
3473 // (since we have to determine where braces are implicitly
3474 // introduced and such). So, we fall back to making the array
3475 // type a dependently-sized array type with no specified
3476 // bound.
3477 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3478 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003479
Douglas Gregord87b61f2009-12-10 17:56:55 +00003480 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003481 if (DeclaratorDecl *DD = Entity.getDecl()) {
3482 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3483 TypeLoc TL = TInfo->getTypeLoc();
3484 if (IncompleteArrayTypeLoc *ArrayLoc
3485 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3486 Brackets = ArrayLoc->getBracketsRange();
3487 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003488 }
3489
3490 *ResultType
3491 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3492 /*NumElts=*/0,
3493 ArrayT->getSizeModifier(),
3494 ArrayT->getIndexTypeCVRQualifiers(),
3495 Brackets);
3496 }
3497
3498 }
3499 }
3500
Eli Friedman08544622009-12-22 02:35:53 +00003501 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003502 return Sema::OwningExprResult(S, Args.release()[0]);
3503
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003504 if (Args.size() == 0)
3505 return S.Owned((Expr *)0);
3506
Douglas Gregor20093b42009-12-09 23:02:17 +00003507 unsigned NumArgs = Args.size();
3508 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3509 SourceLocation(),
3510 (Expr **)Args.release(),
3511 NumArgs,
3512 SourceLocation()));
3513 }
3514
Douglas Gregor99a2e602009-12-16 01:38:02 +00003515 if (SequenceKind == NoInitialization)
3516 return S.Owned((Expr *)0);
3517
Douglas Gregord6542d82009-12-22 15:35:07 +00003518 QualType DestType = Entity.getType().getNonReferenceType();
3519 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003520 // the same as Entity.getDecl()->getType() in cases involving type merging,
3521 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003522 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003523 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003524 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003525
Douglas Gregor99a2e602009-12-16 01:38:02 +00003526 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3527
3528 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3529
3530 // For initialization steps that start with a single initializer,
3531 // grab the only argument out the Args and place it into the "current"
3532 // initializer.
3533 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003534 case SK_ResolveAddressOfOverloadedFunction:
3535 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003536 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003537 case SK_CastDerivedToBaseLValue:
3538 case SK_BindReference:
3539 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003540 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003541 case SK_UserConversion:
3542 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003543 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003544 case SK_QualificationConversionRValue:
3545 case SK_ConversionSequence:
3546 case SK_ListInitialization:
3547 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003548 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003549 assert(Args.size() == 1);
3550 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3551 if (CurInit.isInvalid())
3552 return S.ExprError();
3553 break;
3554
3555 case SK_ConstructorInitialization:
3556 case SK_ZeroInitialization:
3557 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003558 }
3559
3560 // Walk through the computed steps for the initialization sequence,
3561 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003562 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003563 for (step_iterator Step = step_begin(), StepEnd = step_end();
3564 Step != StepEnd; ++Step) {
3565 if (CurInit.isInvalid())
3566 return S.ExprError();
3567
3568 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003569 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003570
3571 switch (Step->Kind) {
3572 case SK_ResolveAddressOfOverloadedFunction:
3573 // Overload resolution determined which function invoke; update the
3574 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003575 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003576 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003577 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003578 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003579 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003580 break;
3581
3582 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003583 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003584 case SK_CastDerivedToBaseLValue: {
3585 // We have a derived-to-base cast that produces either an rvalue or an
3586 // lvalue. Perform that cast.
3587
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003588 CXXBaseSpecifierArray BasePath;
3589
Douglas Gregor20093b42009-12-09 23:02:17 +00003590 // Casts to inaccessible base classes are allowed with C-style casts.
3591 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3592 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3593 CurInitExpr->getLocStart(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003594 CurInitExpr->getSourceRange(),
3595 &BasePath, IgnoreBaseAccess))
Douglas Gregor20093b42009-12-09 23:02:17 +00003596 return S.ExprError();
3597
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003598 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3599 QualType T = SourceType;
3600 if (const PointerType *Pointer = T->getAs<PointerType>())
3601 T = Pointer->getPointeeType();
3602 if (const RecordType *RecordTy = T->getAs<RecordType>())
3603 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3604 cast<CXXRecordDecl>(RecordTy->getDecl()));
3605 }
3606
Sebastian Redl906082e2010-07-20 04:20:21 +00003607 ImplicitCastExpr::ResultCategory Category =
3608 Step->Kind == SK_CastDerivedToBaseLValue ?
3609 ImplicitCastExpr::LValue :
3610 (Step->Kind == SK_CastDerivedToBaseXValue ?
3611 ImplicitCastExpr::XValue :
3612 ImplicitCastExpr::RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003613 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3614 CastExpr::CK_DerivedToBase,
Anders Carlsson88465d32010-04-23 22:18:37 +00003615 (Expr*)CurInit.release(),
Sebastian Redl906082e2010-07-20 04:20:21 +00003616 BasePath, Category));
Douglas Gregor20093b42009-12-09 23:02:17 +00003617 break;
3618 }
3619
3620 case SK_BindReference:
3621 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3622 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3623 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003624 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003625 << BitField->getDeclName()
3626 << CurInitExpr->getSourceRange();
3627 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3628 return S.ExprError();
3629 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003630
Anders Carlsson09380262010-01-31 17:18:49 +00003631 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003632 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003633 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3634 << Entity.getType().isVolatileQualified()
3635 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003636 PrintInitLocationNote(S, Entity);
Anders Carlsson09380262010-01-31 17:18:49 +00003637 return S.ExprError();
3638 }
3639
Douglas Gregor20093b42009-12-09 23:02:17 +00003640 // Reference binding does not have any corresponding ASTs.
3641
3642 // Check exception specifications
3643 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3644 return S.ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003645
Douglas Gregor20093b42009-12-09 23:02:17 +00003646 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003647
Douglas Gregor20093b42009-12-09 23:02:17 +00003648 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003649 // Reference binding does not have any corresponding ASTs.
3650
Douglas Gregor20093b42009-12-09 23:02:17 +00003651 // Check exception specifications
3652 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3653 return S.ExprError();
3654
Douglas Gregor20093b42009-12-09 23:02:17 +00003655 break;
3656
Douglas Gregor523d46a2010-04-18 07:40:54 +00003657 case SK_ExtraneousCopyToTemporary:
3658 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3659 /*IsExtraneousCopy=*/true);
3660 break;
3661
Douglas Gregor20093b42009-12-09 23:02:17 +00003662 case SK_UserConversion: {
3663 // We have a user-defined conversion that invokes either a constructor
3664 // or a conversion function.
3665 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003666 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003667 FunctionDecl *Fn = Step->Function.Function;
3668 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003669 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003670 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003671 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003672 // Build a call to the selected constructor.
3673 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3674 SourceLocation Loc = CurInitExpr->getLocStart();
3675 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003676
Douglas Gregor20093b42009-12-09 23:02:17 +00003677 // Determine the arguments required to actually perform the constructor
3678 // call.
3679 if (S.CompleteConstructorCall(Constructor,
3680 Sema::MultiExprArg(S,
3681 (void **)&CurInitExpr,
3682 1),
3683 Loc, ConstructorArgs))
3684 return S.ExprError();
3685
3686 // Build the an expression that constructs a temporary.
3687 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3688 move_arg(ConstructorArgs));
3689 if (CurInit.isInvalid())
3690 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003691
Anders Carlsson9a68a672010-04-21 18:47:17 +00003692 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003693 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003694 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor20093b42009-12-09 23:02:17 +00003695
3696 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003697 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3698 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3699 S.IsDerivedFrom(SourceType, Class))
3700 IsCopy = true;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003701
3702 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003703 } else {
3704 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003705 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003706 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003707 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003708 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003709 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003710
Douglas Gregor20093b42009-12-09 23:02:17 +00003711 // FIXME: Should we move this initialization into a separate
3712 // derived-to-base conversion? I believe the answer is "no", because
3713 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003714 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003715 FoundFn, Conversion))
Douglas Gregor20093b42009-12-09 23:02:17 +00003716 return S.ExprError();
3717
3718 // Do a little dance to make sure that CurInit has the proper
3719 // pointer.
3720 CurInit.release();
3721
3722 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003723 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3724 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003725 if (CurInit.isInvalid() || !CurInit.get())
3726 return S.ExprError();
3727
3728 CastKind = CastExpr::CK_UserDefinedConversion;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003729
3730 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003731 }
3732
Douglas Gregor2f599792010-04-02 18:24:57 +00003733 bool RequiresCopy = !IsCopy &&
3734 getKind() != InitializationSequence::ReferenceBinding;
3735 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003736 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003737 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3738 CurInitExpr = static_cast<Expr *>(CurInit.get());
3739 QualType T = CurInitExpr->getType();
3740 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00003741 CXXDestructorDecl *Destructor
3742 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003743 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3744 S.PDiag(diag::err_access_dtor_temp) << T);
3745 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3746 }
3747 }
3748
Douglas Gregor20093b42009-12-09 23:02:17 +00003749 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redl906082e2010-07-20 04:20:21 +00003750 // FIXME: xvalues
Douglas Gregor20093b42009-12-09 23:02:17 +00003751 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003752 CastKind,
3753 CurInitExpr,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003754 CXXBaseSpecifierArray(),
Sebastian Redl906082e2010-07-20 04:20:21 +00003755 IsLvalue ? ImplicitCastExpr::LValue : ImplicitCastExpr::RValue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003756
Douglas Gregor2f599792010-04-02 18:24:57 +00003757 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003758 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3759 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003760
Douglas Gregor20093b42009-12-09 23:02:17 +00003761 break;
3762 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003763
Douglas Gregor20093b42009-12-09 23:02:17 +00003764 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003765 case SK_QualificationConversionXValue:
3766 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003767 // Perform a qualification conversion; these can never go wrong.
Sebastian Redl906082e2010-07-20 04:20:21 +00003768 ImplicitCastExpr::ResultCategory Category =
3769 Step->Kind == SK_QualificationConversionLValue ?
3770 ImplicitCastExpr::LValue :
3771 (Step->Kind == SK_QualificationConversionXValue ?
3772 ImplicitCastExpr::XValue :
3773 ImplicitCastExpr::RValue);
3774 S.ImpCastExprToType(CurInitExpr, Step->Type, CastExpr::CK_NoOp, Category);
Douglas Gregor20093b42009-12-09 23:02:17 +00003775 CurInit.release();
3776 CurInit = S.Owned(CurInitExpr);
3777 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003778 }
3779
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003780 case SK_ConversionSequence: {
3781 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3782
3783 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3784 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor20093b42009-12-09 23:02:17 +00003785 return S.ExprError();
3786
3787 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003788 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003789 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003790 }
3791
Douglas Gregord87b61f2009-12-10 17:56:55 +00003792 case SK_ListInitialization: {
3793 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3794 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003795 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003796 return S.ExprError();
3797
3798 CurInit.release();
3799 CurInit = S.Owned(InitList);
3800 break;
3801 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003802
3803 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003804 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003805 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003806 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003807
Douglas Gregor51c56d62009-12-14 20:49:26 +00003808 // Build a call to the selected constructor.
3809 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00003810 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3811 ? Kind.getEqualLoc()
3812 : Kind.getLocation();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003813
3814 // Determine the arguments required to actually perform the constructor
3815 // call.
3816 if (S.CompleteConstructorCall(Constructor, move(Args),
3817 Loc, ConstructorArgs))
3818 return S.ExprError();
3819
Douglas Gregord6e44a32010-04-16 22:09:46 +00003820 // Build the expression that constructs a temporary.
Douglas Gregor91be6f52010-03-02 17:18:33 +00003821 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003822 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003823 (Kind.getKind() == InitializationKind::IK_Direct ||
3824 Kind.getKind() == InitializationKind::IK_Value)) {
3825 // An explicitly-constructed temporary, e.g., X(1, 2).
3826 unsigned NumExprs = ConstructorArgs.size();
3827 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003828 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor91be6f52010-03-02 17:18:33 +00003829 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3830 Constructor,
3831 Entity.getType(),
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003832 Loc,
Douglas Gregor91be6f52010-03-02 17:18:33 +00003833 Exprs,
3834 NumExprs,
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003835 Kind.getParenRange().getEnd(),
3836 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003837 } else {
3838 CXXConstructExpr::ConstructionKind ConstructKind =
3839 CXXConstructExpr::CK_Complete;
3840
3841 if (Entity.getKind() == InitializedEntity::EK_Base) {
3842 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3843 CXXConstructExpr::CK_VirtualBase :
3844 CXXConstructExpr::CK_NonVirtualBase;
3845 }
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003846
3847 // If the entity allows NRVO, mark the construction as elidable
3848 // unconditionally.
3849 if (Entity.allowsNRVO())
3850 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3851 Constructor, /*Elidable=*/true,
3852 move_arg(ConstructorArgs),
3853 ConstructorInitRequiresZeroInit,
3854 ConstructKind);
3855 else
3856 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3857 Constructor,
3858 move_arg(ConstructorArgs),
3859 ConstructorInitRequiresZeroInit,
3860 ConstructKind);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003861 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003862 if (CurInit.isInvalid())
3863 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003864
3865 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00003866 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003867 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003868 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003869
Douglas Gregor2f599792010-04-02 18:24:57 +00003870 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003871 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003872
Douglas Gregor51c56d62009-12-14 20:49:26 +00003873 break;
3874 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003875
3876 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003877 step_iterator NextStep = Step;
3878 ++NextStep;
3879 if (NextStep != StepEnd &&
3880 NextStep->Kind == SK_ConstructorInitialization) {
3881 // The need for zero-initialization is recorded directly into
3882 // the call to the object's constructor within the next step.
3883 ConstructorInitRequiresZeroInit = true;
3884 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3885 S.getLangOptions().CPlusPlus &&
3886 !Kind.isImplicitValueInit()) {
Douglas Gregored8abf12010-07-08 06:14:04 +00003887 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(Step->Type,
Douglas Gregor71d17402009-12-15 00:01:57 +00003888 Kind.getRange().getBegin(),
3889 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003890 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003891 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003892 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003893 break;
3894 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003895
3896 case SK_CAssignment: {
3897 QualType SourceType = CurInitExpr->getType();
3898 Sema::AssignConvertType ConvTy =
3899 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003900
3901 // If this is a call, allow conversion to a transparent union.
3902 if (ConvTy != Sema::Compatible &&
3903 Entity.getKind() == InitializedEntity::EK_Parameter &&
3904 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3905 == Sema::Compatible)
3906 ConvTy = Sema::Compatible;
3907
Douglas Gregora41a8c52010-04-22 00:20:18 +00003908 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003909 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3910 Step->Type, SourceType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00003911 CurInitExpr,
3912 getAssignmentAction(Entity),
3913 &Complained)) {
3914 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003915 return S.ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003916 } else if (Complained)
3917 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003918
3919 CurInit.release();
3920 CurInit = S.Owned(CurInitExpr);
3921 break;
3922 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003923
3924 case SK_StringInit: {
3925 QualType Ty = Step->Type;
3926 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3927 break;
3928 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003929 }
3930 }
3931
3932 return move(CurInit);
3933}
3934
3935//===----------------------------------------------------------------------===//
3936// Diagnose initialization failures
3937//===----------------------------------------------------------------------===//
3938bool InitializationSequence::Diagnose(Sema &S,
3939 const InitializedEntity &Entity,
3940 const InitializationKind &Kind,
3941 Expr **Args, unsigned NumArgs) {
3942 if (SequenceKind != FailedSequence)
3943 return false;
3944
Douglas Gregord6542d82009-12-22 15:35:07 +00003945 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003946 switch (Failure) {
3947 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003948 // FIXME: Customize for the initialized entity?
3949 if (NumArgs == 0)
3950 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3951 << DestType.getNonReferenceType();
3952 else // FIXME: diagnostic below could be better!
3953 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3954 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003955 break;
3956
3957 case FK_ArrayNeedsInitList:
3958 case FK_ArrayNeedsInitListOrStringLiteral:
3959 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3960 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3961 break;
3962
John McCall6bb80172010-03-30 21:47:33 +00003963 case FK_AddressOfOverloadFailed: {
3964 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00003965 S.ResolveAddressOfOverloadedFunction(Args[0],
3966 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00003967 true,
3968 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00003969 break;
John McCall6bb80172010-03-30 21:47:33 +00003970 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003971
3972 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003973 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003974 switch (FailedOverloadResult) {
3975 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003976 if (Failure == FK_UserConversionOverloadFailed)
3977 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3978 << Args[0]->getType() << DestType
3979 << Args[0]->getSourceRange();
3980 else
3981 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3982 << DestType << Args[0]->getType()
3983 << Args[0]->getSourceRange();
3984
John McCallcbce6062010-01-12 07:18:19 +00003985 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3986 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003987 break;
3988
3989 case OR_No_Viable_Function:
3990 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3991 << Args[0]->getType() << DestType.getNonReferenceType()
3992 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003993 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3994 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003995 break;
3996
3997 case OR_Deleted: {
3998 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3999 << Args[0]->getType() << DestType.getNonReferenceType()
4000 << Args[0]->getSourceRange();
4001 OverloadCandidateSet::iterator Best;
4002 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4003 Kind.getLocation(),
4004 Best);
4005 if (Ovl == OR_Deleted) {
4006 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4007 << Best->Function->isDeleted();
4008 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004009 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004010 }
4011 break;
4012 }
4013
4014 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004015 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004016 break;
4017 }
4018 break;
4019
4020 case FK_NonConstLValueReferenceBindingToTemporary:
4021 case FK_NonConstLValueReferenceBindingToUnrelated:
4022 S.Diag(Kind.getLocation(),
4023 Failure == FK_NonConstLValueReferenceBindingToTemporary
4024 ? diag::err_lvalue_reference_bind_to_temporary
4025 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004026 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004027 << DestType.getNonReferenceType()
4028 << Args[0]->getType()
4029 << Args[0]->getSourceRange();
4030 break;
4031
4032 case FK_RValueReferenceBindingToLValue:
4033 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4034 << Args[0]->getSourceRange();
4035 break;
4036
4037 case FK_ReferenceInitDropsQualifiers:
4038 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4039 << DestType.getNonReferenceType()
4040 << Args[0]->getType()
4041 << Args[0]->getSourceRange();
4042 break;
4043
4044 case FK_ReferenceInitFailed:
4045 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4046 << DestType.getNonReferenceType()
4047 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4048 << Args[0]->getType()
4049 << Args[0]->getSourceRange();
4050 break;
4051
4052 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004053 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4054 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004055 << DestType
4056 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4057 << Args[0]->getType()
4058 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004059 break;
4060
4061 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004062 SourceRange R;
4063
4064 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4065 R = SourceRange(InitList->getInit(1)->getLocStart(),
4066 InitList->getLocEnd());
4067 else
4068 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004069
4070 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00004071 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004072 break;
4073 }
4074
4075 case FK_ReferenceBindingToInitList:
4076 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4077 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4078 break;
4079
4080 case FK_InitListBadDestinationType:
4081 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4082 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4083 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00004084
4085 case FK_ConstructorOverloadFailed: {
4086 SourceRange ArgsRange;
4087 if (NumArgs)
4088 ArgsRange = SourceRange(Args[0]->getLocStart(),
4089 Args[NumArgs - 1]->getLocEnd());
4090
4091 // FIXME: Using "DestType" for the entity we're printing is probably
4092 // bad.
4093 switch (FailedOverloadResult) {
4094 case OR_Ambiguous:
4095 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4096 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00004097 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00004098 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004099 break;
4100
4101 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004102 if (Kind.getKind() == InitializationKind::IK_Default &&
4103 (Entity.getKind() == InitializedEntity::EK_Base ||
4104 Entity.getKind() == InitializedEntity::EK_Member) &&
4105 isa<CXXConstructorDecl>(S.CurContext)) {
4106 // This is implicit default initialization of a member or
4107 // base within a constructor. If no viable function was
4108 // found, notify the user that she needs to explicitly
4109 // initialize this base/member.
4110 CXXConstructorDecl *Constructor
4111 = cast<CXXConstructorDecl>(S.CurContext);
4112 if (Entity.getKind() == InitializedEntity::EK_Base) {
4113 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4114 << Constructor->isImplicit()
4115 << S.Context.getTypeDeclType(Constructor->getParent())
4116 << /*base=*/0
4117 << Entity.getType();
4118
4119 RecordDecl *BaseDecl
4120 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4121 ->getDecl();
4122 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4123 << S.Context.getTagDeclType(BaseDecl);
4124 } else {
4125 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4126 << Constructor->isImplicit()
4127 << S.Context.getTypeDeclType(Constructor->getParent())
4128 << /*member=*/1
4129 << Entity.getName();
4130 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4131
4132 if (const RecordType *Record
4133 = Entity.getType()->getAs<RecordType>())
4134 S.Diag(Record->getDecl()->getLocation(),
4135 diag::note_previous_decl)
4136 << S.Context.getTagDeclType(Record->getDecl());
4137 }
4138 break;
4139 }
4140
Douglas Gregor51c56d62009-12-14 20:49:26 +00004141 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4142 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00004143 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4144 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004145 break;
4146
4147 case OR_Deleted: {
4148 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4149 << true << DestType << ArgsRange;
4150 OverloadCandidateSet::iterator Best;
4151 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4152 Kind.getLocation(),
4153 Best);
4154 if (Ovl == OR_Deleted) {
4155 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4156 << Best->Function->isDeleted();
4157 } else {
4158 llvm_unreachable("Inconsistent overload resolution?");
4159 }
4160 break;
4161 }
4162
4163 case OR_Success:
4164 llvm_unreachable("Conversion did not fail!");
4165 break;
4166 }
4167 break;
4168 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004169
4170 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004171 if (Entity.getKind() == InitializedEntity::EK_Member &&
4172 isa<CXXConstructorDecl>(S.CurContext)) {
4173 // This is implicit default-initialization of a const member in
4174 // a constructor. Complain that it needs to be explicitly
4175 // initialized.
4176 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4177 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4178 << Constructor->isImplicit()
4179 << S.Context.getTypeDeclType(Constructor->getParent())
4180 << /*const=*/1
4181 << Entity.getName();
4182 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4183 << Entity.getName();
4184 } else {
4185 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4186 << DestType << (bool)DestType->getAs<RecordType>();
4187 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004188 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004189
4190 case FK_Incomplete:
4191 S.RequireCompleteType(Kind.getLocation(), DestType,
4192 diag::err_init_incomplete_type);
4193 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004194 }
4195
Douglas Gregora41a8c52010-04-22 00:20:18 +00004196 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004197 return true;
4198}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004199
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004200void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4201 switch (SequenceKind) {
4202 case FailedSequence: {
4203 OS << "Failed sequence: ";
4204 switch (Failure) {
4205 case FK_TooManyInitsForReference:
4206 OS << "too many initializers for reference";
4207 break;
4208
4209 case FK_ArrayNeedsInitList:
4210 OS << "array requires initializer list";
4211 break;
4212
4213 case FK_ArrayNeedsInitListOrStringLiteral:
4214 OS << "array requires initializer list or string literal";
4215 break;
4216
4217 case FK_AddressOfOverloadFailed:
4218 OS << "address of overloaded function failed";
4219 break;
4220
4221 case FK_ReferenceInitOverloadFailed:
4222 OS << "overload resolution for reference initialization failed";
4223 break;
4224
4225 case FK_NonConstLValueReferenceBindingToTemporary:
4226 OS << "non-const lvalue reference bound to temporary";
4227 break;
4228
4229 case FK_NonConstLValueReferenceBindingToUnrelated:
4230 OS << "non-const lvalue reference bound to unrelated type";
4231 break;
4232
4233 case FK_RValueReferenceBindingToLValue:
4234 OS << "rvalue reference bound to an lvalue";
4235 break;
4236
4237 case FK_ReferenceInitDropsQualifiers:
4238 OS << "reference initialization drops qualifiers";
4239 break;
4240
4241 case FK_ReferenceInitFailed:
4242 OS << "reference initialization failed";
4243 break;
4244
4245 case FK_ConversionFailed:
4246 OS << "conversion failed";
4247 break;
4248
4249 case FK_TooManyInitsForScalar:
4250 OS << "too many initializers for scalar";
4251 break;
4252
4253 case FK_ReferenceBindingToInitList:
4254 OS << "referencing binding to initializer list";
4255 break;
4256
4257 case FK_InitListBadDestinationType:
4258 OS << "initializer list for non-aggregate, non-scalar type";
4259 break;
4260
4261 case FK_UserConversionOverloadFailed:
4262 OS << "overloading failed for user-defined conversion";
4263 break;
4264
4265 case FK_ConstructorOverloadFailed:
4266 OS << "constructor overloading failed";
4267 break;
4268
4269 case FK_DefaultInitOfConst:
4270 OS << "default initialization of a const variable";
4271 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004272
4273 case FK_Incomplete:
4274 OS << "initialization of incomplete type";
4275 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004276 }
4277 OS << '\n';
4278 return;
4279 }
4280
4281 case DependentSequence:
4282 OS << "Dependent sequence: ";
4283 return;
4284
4285 case UserDefinedConversion:
4286 OS << "User-defined conversion sequence: ";
4287 break;
4288
4289 case ConstructorInitialization:
4290 OS << "Constructor initialization sequence: ";
4291 break;
4292
4293 case ReferenceBinding:
4294 OS << "Reference binding: ";
4295 break;
4296
4297 case ListInitialization:
4298 OS << "List initialization: ";
4299 break;
4300
4301 case ZeroInitialization:
4302 OS << "Zero initialization\n";
4303 return;
4304
4305 case NoInitialization:
4306 OS << "No initialization\n";
4307 return;
4308
4309 case StandardConversion:
4310 OS << "Standard conversion: ";
4311 break;
4312
4313 case CAssignment:
4314 OS << "C assignment: ";
4315 break;
4316
4317 case StringInit:
4318 OS << "String initialization: ";
4319 break;
4320 }
4321
4322 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4323 if (S != step_begin()) {
4324 OS << " -> ";
4325 }
4326
4327 switch (S->Kind) {
4328 case SK_ResolveAddressOfOverloadedFunction:
4329 OS << "resolve address of overloaded function";
4330 break;
4331
4332 case SK_CastDerivedToBaseRValue:
4333 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4334 break;
4335
Sebastian Redl906082e2010-07-20 04:20:21 +00004336 case SK_CastDerivedToBaseXValue:
4337 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4338 break;
4339
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004340 case SK_CastDerivedToBaseLValue:
4341 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4342 break;
4343
4344 case SK_BindReference:
4345 OS << "bind reference to lvalue";
4346 break;
4347
4348 case SK_BindReferenceToTemporary:
4349 OS << "bind reference to a temporary";
4350 break;
4351
Douglas Gregor523d46a2010-04-18 07:40:54 +00004352 case SK_ExtraneousCopyToTemporary:
4353 OS << "extraneous C++03 copy to temporary";
4354 break;
4355
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004356 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004357 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004358 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004359
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004360 case SK_QualificationConversionRValue:
4361 OS << "qualification conversion (rvalue)";
4362
Sebastian Redl906082e2010-07-20 04:20:21 +00004363 case SK_QualificationConversionXValue:
4364 OS << "qualification conversion (xvalue)";
4365
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004366 case SK_QualificationConversionLValue:
4367 OS << "qualification conversion (lvalue)";
4368 break;
4369
4370 case SK_ConversionSequence:
4371 OS << "implicit conversion sequence (";
4372 S->ICS->DebugPrint(); // FIXME: use OS
4373 OS << ")";
4374 break;
4375
4376 case SK_ListInitialization:
4377 OS << "list initialization";
4378 break;
4379
4380 case SK_ConstructorInitialization:
4381 OS << "constructor initialization";
4382 break;
4383
4384 case SK_ZeroInitialization:
4385 OS << "zero initialization";
4386 break;
4387
4388 case SK_CAssignment:
4389 OS << "C assignment";
4390 break;
4391
4392 case SK_StringInit:
4393 OS << "string initialization";
4394 break;
4395 }
4396 }
4397}
4398
4399void InitializationSequence::dump() const {
4400 dump(llvm::errs());
4401}
4402
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004403//===----------------------------------------------------------------------===//
4404// Initialization helper functions
4405//===----------------------------------------------------------------------===//
4406Sema::OwningExprResult
4407Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4408 SourceLocation EqualLoc,
4409 OwningExprResult Init) {
4410 if (Init.isInvalid())
4411 return ExprError();
4412
4413 Expr *InitE = (Expr *)Init.get();
4414 assert(InitE && "No initialization expression?");
4415
4416 if (EqualLoc.isInvalid())
4417 EqualLoc = InitE->getLocStart();
4418
4419 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4420 EqualLoc);
4421 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4422 Init.release();
4423 return Seq.Perform(*this, Entity, Kind,
4424 MultiExprArg(*this, (void**)&InitE, 1));
4425}