blob: c1569620dab79789be769ed0e6c4b57d945ba8ed [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregorc171e3b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "Sema.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000021#include "clang/Lex/Preprocessor.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000022#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000024#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Chris Lattner79e079d2009-02-24 23:10:27 +000035static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000036 const ArrayType *AT = Context.getAsArrayType(DeclType);
37 if (!AT) return 0;
38
Eli Friedman8718a6a2009-05-29 18:22:49 +000039 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40 return 0;
41
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // See if this is a string literal or @encode.
43 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattner8879e3b2009-02-26 23:26:43 +000045 // Handle @encode, which is a narrow string.
46 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
47 return Init;
48
49 // Otherwise we can only handle string literals.
50 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000051 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000052
53 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000054 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
56 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000058
Eli Friedmanbb6415c2009-05-31 10:54:53 +000059 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
60 // correction from DR343): "An array with element type compatible with a
61 // qualified or unqualified version of wchar_t may be initialized by a wide
62 // string literal, optionally enclosed in braces."
63 if (Context.typesAreCompatible(Context.getWCharType(),
64 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000065 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattnerdd8e0062009-02-24 22:27:37 +000067 return 0;
68}
69
Chris Lattner79e079d2009-02-24 23:10:27 +000070static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
71 // Get the length of the string as parsed.
72 uint64_t StrLength =
73 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
74
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner79e079d2009-02-24 23:10:27 +000076 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000077 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000078 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000079 // being initialized to a string literal.
80 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000081 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000082 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000083 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
84 ConstVal,
85 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000086 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000087 }
Mike Stump1eb44332009-09-09 15:08:12 +000088
Eli Friedman8718a6a2009-05-29 18:22:49 +000089 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000090
Eli Friedman8718a6a2009-05-29 18:22:49 +000091 // C99 6.7.8p14. We have an array of character type with known size. However,
92 // the size may be smaller or larger than the string we are initializing.
93 // FIXME: Avoid truncation for 64-bit length strings.
94 if (StrLength-1 > CAT->getSize().getZExtValue())
95 S.Diag(Str->getSourceRange().getBegin(),
96 diag::warn_initializer_string_for_char_array_too_long)
97 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000098
Eli Friedman8718a6a2009-05-29 18:22:49 +000099 // Set the type to the actual size that we are initializing. If we have
100 // something like:
101 // char x[1] = "foo";
102 // then this will set the string literal's type to char[1].
103 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000104}
105
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000106//===----------------------------------------------------------------------===//
107// Semantic checking for initializer lists.
108//===----------------------------------------------------------------------===//
109
Douglas Gregor9e80f722009-01-29 01:05:33 +0000110/// @brief Semantic checking for initializer lists.
111///
112/// The InitListChecker class contains a set of routines that each
113/// handle the initialization of a certain kind of entity, e.g.,
114/// arrays, vectors, struct/union types, scalars, etc. The
115/// InitListChecker itself performs a recursive walk of the subobject
116/// structure of the type to be initialized, while stepping through
117/// the initializer list one element at a time. The IList and Index
118/// parameters to each of the Check* routines contain the active
119/// (syntactic) initializer list and the index into that initializer
120/// list that represents the current initializer. Each routine is
121/// responsible for moving that Index forward as it consumes elements.
122///
123/// Each Check* routine also has a StructuredList/StructuredIndex
124/// arguments, which contains the current the "structured" (semantic)
125/// initializer list and the index into that initializer list where we
126/// are copying initializers as we map them over to the semantic
127/// list. Once we have completed our recursive walk of the subobject
128/// structure, we will have constructed a full semantic initializer
129/// list.
130///
131/// C99 designators cause changes in the initializer list traversal,
132/// because they make the initialization "jump" into a specific
133/// subobject and then continue the initialization from that
134/// point. CheckDesignatedInitializer() recursively steps into the
135/// designated subobject and manages backing out the recursion to
136/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000137namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000138class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000139 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000140 bool hadError;
141 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
142 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000144 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000145 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000146 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000147 unsigned &StructuredIndex,
148 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000149 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000150 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000151 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000152 unsigned &StructuredIndex,
153 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000154 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000155 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000156 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000157 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000159 unsigned &StructuredIndex,
160 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000161 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000162 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000163 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000164 InitListExpr *StructuredList,
165 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000166 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000167 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000168 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000169 InitListExpr *StructuredList,
170 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000171 void CheckReferenceType(const InitializedEntity &Entity,
172 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000173 unsigned &Index,
174 InitListExpr *StructuredList,
175 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000177 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000178 InitListExpr *StructuredList,
179 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000181 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000182 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000183 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000194 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000195 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000196 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000197 RecordDecl::field_iterator *NextField,
198 llvm::APSInt *NextElementIndex,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000202 bool FinishSubobjectInit,
203 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000204 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
205 QualType CurrentObjectType,
206 InitListExpr *StructuredList,
207 unsigned StructuredIndex,
208 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000209 void UpdateStructuredListElement(InitListExpr *StructuredList,
210 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000211 Expr *expr);
212 int numArrayElements(QualType DeclType);
213 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000214
Douglas Gregord6d37de2009-12-22 00:05:34 +0000215 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
216 const InitializedEntity &ParentEntity,
217 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000218 void FillInValueInitializations(const InitializedEntity &Entity,
219 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000220public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000221 InitListChecker(Sema &S, const InitializedEntity &Entity,
222 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000223 bool HadError() { return hadError; }
224
225 // @brief Retrieves the fully-structured initializer list used for
226 // semantic analysis and code generation.
227 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
228};
Chris Lattner8b419b92009-02-24 22:48:58 +0000229} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000230
Douglas Gregord6d37de2009-12-22 00:05:34 +0000231void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
232 const InitializedEntity &ParentEntity,
233 InitListExpr *ILE,
234 bool &RequiresSecondPass) {
235 SourceLocation Loc = ILE->getSourceRange().getBegin();
236 unsigned NumInits = ILE->getNumInits();
237 InitializedEntity MemberEntity
238 = InitializedEntity::InitializeMember(Field, &ParentEntity);
239 if (Init >= NumInits || !ILE->getInit(Init)) {
240 // FIXME: We probably don't need to handle references
241 // specially here, since value-initialization of references is
242 // handled in InitializationSequence.
243 if (Field->getType()->isReferenceType()) {
244 // C++ [dcl.init.aggr]p9:
245 // If an incomplete or empty initializer-list leaves a
246 // member of reference type uninitialized, the program is
247 // ill-formed.
248 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
249 << Field->getType()
250 << ILE->getSyntacticForm()->getSourceRange();
251 SemaRef.Diag(Field->getLocation(),
252 diag::note_uninit_reference_member);
253 hadError = true;
254 return;
255 }
256
257 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
258 true);
259 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
260 if (!InitSeq) {
261 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
262 hadError = true;
263 return;
264 }
265
266 Sema::OwningExprResult MemberInit
267 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
268 Sema::MultiExprArg(SemaRef, 0, 0));
269 if (MemberInit.isInvalid()) {
270 hadError = true;
271 return;
272 }
273
274 if (hadError) {
275 // Do nothing
276 } else if (Init < NumInits) {
277 ILE->setInit(Init, MemberInit.takeAs<Expr>());
278 } else if (InitSeq.getKind()
279 == InitializationSequence::ConstructorInitialization) {
280 // Value-initialization requires a constructor call, so
281 // extend the initializer list to include the constructor
282 // call and make a note that we'll need to take another pass
283 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000284 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000285 RequiresSecondPass = true;
286 }
287 } else if (InitListExpr *InnerILE
288 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289 FillInValueInitializations(MemberEntity, InnerILE,
290 RequiresSecondPass);
291}
292
Douglas Gregor4c678342009-01-28 21:54:33 +0000293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Ted Kremenek6217b802009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000307 if (RType->getDecl()->isUnion() &&
308 ILE->getInitializedFieldInUnion())
309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310 Entity, ILE, RequiresSecondPass);
311 else {
312 unsigned Init = 0;
313 for (RecordDecl::field_iterator
314 Field = RType->getDecl()->field_begin(),
315 FieldEnd = RType->getDecl()->field_end();
316 Field != FieldEnd; ++Field) {
317 if (Field->isUnnamedBitfield())
318 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000319
Douglas Gregord6d37de2009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000321 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000325 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000326
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000336 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000354 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000357
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssond3d824d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregor87fd7032009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368 true);
369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370 if (!InitSeq) {
371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000376 Sema::OwningExprResult ElementInit
377 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
378 Sema::MultiExprArg(SemaRef, 0, 0));
379 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000380 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000381 return;
382 }
383
384 if (hadError) {
385 // Do nothing
386 } else if (Init < NumInits) {
387 ILE->setInit(Init, ElementInit.takeAs<Expr>());
388 } else if (InitSeq.getKind()
389 == InitializationSequence::ConstructorInitialization) {
390 // Value-initialization requires a constructor call, so
391 // extend the initializer list to include the constructor
392 // call and make a note that we'll need to take another pass
393 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000394 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 RequiresSecondPass = true;
396 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000397 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
399 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000400 }
401}
402
Chris Lattner68355a52009-01-29 05:10:57 +0000403
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
405 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000406 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000407 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000408
Eli Friedmanb85f7072008-05-19 19:16:24 +0000409 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000410 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000411 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000412 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000413 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000414 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000415 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000416
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000417 if (!hadError) {
418 bool RequiresSecondPass = false;
419 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000420 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000421 FillInValueInitializations(Entity, FullyStructuredList,
422 RequiresSecondPass);
423 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000424}
425
426int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000427 // FIXME: use a proper constant
428 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000429 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000430 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000431 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
432 }
433 return maxElements;
434}
435
436int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000437 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000438 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000439 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000440 Field = structDecl->field_begin(),
441 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000442 Field != FieldEnd; ++Field) {
443 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
444 ++InitializableMembers;
445 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000446 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000447 return std::min(InitializableMembers, 1);
448 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000449}
450
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000451void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000452 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000453 QualType T, unsigned &Index,
454 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000455 unsigned &StructuredIndex,
456 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000457 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 if (T->isArrayType())
460 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000461 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000462 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000463 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000464 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000465 else
466 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000467
Eli Friedman402256f2008-05-25 13:49:22 +0000468 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000469 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000470 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000471 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000472 hadError = true;
473 return;
474 }
475
Douglas Gregor4c678342009-01-28 21:54:33 +0000476 // Build a structured initializer list corresponding to this subobject.
477 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000478 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
479 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000480 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
481 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000482 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000483
Douglas Gregor4c678342009-01-28 21:54:33 +0000484 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000485 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000486 CheckListElementTypes(Entity, ParentIList, T,
487 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000488 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000489 StructuredSubobjectInitIndex,
490 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000491 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000492 StructuredSubobjectInitList->setType(T);
493
Douglas Gregored8a93d2009-03-01 17:12:46 +0000494 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000495 // range corresponds with the end of the last initializer it used.
496 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000497 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000498 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
499 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
500 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000501
502 // Warn about missing braces.
503 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000504 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
505 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000506 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000507 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
508 "{")
509 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner1dcd0612010-03-07 04:47:12 +0000510 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000511 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000512 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000513}
514
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000515void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000516 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000517 unsigned &Index,
518 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000519 unsigned &StructuredIndex,
520 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000521 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000522 SyntacticToSemantic[IList] = StructuredList;
523 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000524 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
525 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor2c792812010-02-09 00:50:06 +0000526 IList->setType(T.getNonReferenceType());
527 StructuredList->setType(T.getNonReferenceType());
Eli Friedman638e1442008-05-25 13:22:35 +0000528 if (hadError)
529 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000530
Eli Friedman638e1442008-05-25 13:22:35 +0000531 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000532 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000533 if (StructuredIndex == 1 &&
534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000536 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000537 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000538 hadError = true;
539 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000540 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000542 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000543 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000544 // Don't complain for incomplete types, since we'll get an error
545 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000547 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000548 CurrentObjectType->isArrayType()? 0 :
549 CurrentObjectType->isVectorType()? 1 :
550 CurrentObjectType->isScalarType()? 2 :
551 CurrentObjectType->isUnionType()? 3 :
552 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000553
554 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Nate Begeman08634522009-07-07 21:53:06 +0000559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000563
Chris Lattner08202542009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000565 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000566 }
567 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000568
Eli Friedman759f2522009-05-16 11:45:48 +0000569 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000571 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000572 << FixItHint::CreateRemoval(IList->getLocStart())
573 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000574}
575
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000577 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000578 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000579 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000580 unsigned &Index,
581 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000582 unsigned &StructuredIndex,
583 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000584 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000585 CheckScalarType(Entity, IList, DeclType, Index,
586 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000588 CheckVectorType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000590 } else if (DeclType->isAggregateType()) {
591 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000592 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000593 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000595 StructuredList, StructuredIndex,
596 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000597 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000598 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000599 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000600 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000601 CheckArrayType(Entity, IList, DeclType, Zero,
602 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000604 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000605 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000608 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000610 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000611 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000612 } else if (DeclType->isRecordType()) {
613 // C++ [dcl.init]p14:
614 // [...] If the class is an aggregate (8.5.1), and the initializer
615 // is a brace-enclosed list, see 8.5.1.
616 //
617 // Note: 8.5.1 is handled below; here, we diagnose the case where
618 // we have an initializer list and a destination type that is not
619 // an aggregate.
620 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000622 << DeclType << IList->getSourceRange();
623 hadError = true;
624 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000625 CheckReferenceType(Entity, IList, DeclType, Index,
626 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000627 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000628 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
629 << DeclType;
630 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000631 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000632 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
633 << DeclType;
634 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000635 }
636}
637
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000638void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000639 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000640 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000641 unsigned &Index,
642 InitListExpr *StructuredList,
643 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000644 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000645 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
646 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000648 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 = getStructuredSubobjectInit(IList, Index, ElemType,
650 StructuredList, StructuredIndex,
651 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000652 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000653 newStructuredList, newStructuredIndex);
654 ++StructuredIndex;
655 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000656 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
657 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000658 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000659 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000660 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000661 CheckScalarType(Entity, IList, ElemType, Index,
662 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000663 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000664 CheckReferenceType(Entity, IList, ElemType, Index,
665 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000666 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000667 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000668 // C++ [dcl.init.aggr]p12:
669 // All implicit type conversions (clause 4) are considered when
670 // initializing the aggregate member with an ini- tializer from
671 // an initializer-list. If the initializer can initialize a
672 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000673
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000674 // FIXME: Better EqualLoc?
675 InitializationKind Kind =
676 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
677 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
678
679 if (Seq) {
680 Sema::OwningExprResult Result =
681 Seq.Perform(SemaRef, Entity, Kind,
682 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
683 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000684 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000685
686 UpdateStructuredListElement(StructuredList, StructuredIndex,
687 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000688 ++Index;
689 return;
690 }
691
692 // Fall through for subaggregate initialization
693 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000694 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000695 //
696 // The initializer for a structure or union object that has
697 // automatic storage duration shall be either an initializer
698 // list as described below, or a single expression that has
699 // compatible structure or union type. In the latter case, the
700 // initial value of the object, including unnamed members, is
701 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000702 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000703 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000704 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
705 ++Index;
706 return;
707 }
708
709 // Fall through for subaggregate initialization
710 }
711
712 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000713 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000714 // [...] Otherwise, if the member is itself a non-empty
715 // subaggregate, brace elision is assumed and the initializer is
716 // considered for the initialization of the first member of
717 // the subaggregate.
718 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000719 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000720 StructuredIndex);
721 ++StructuredIndex;
722 } else {
723 // We cannot initialize this element, so let
724 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000725 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
726 SemaRef.Owned(expr));
727 IList->setInit(Index, 0);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000728 hadError = true;
729 ++Index;
730 ++StructuredIndex;
731 }
732 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000733}
734
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000735void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000736 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000737 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000738 InitListExpr *StructuredList,
739 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000740 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000741 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000742 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000743 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000744 diag::err_many_braces_around_scalar_init)
745 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000746 hadError = true;
747 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000748 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000749 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000750 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000751 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000752 diag::err_designator_for_scalar_init)
753 << DeclType << expr->getSourceRange();
754 hadError = true;
755 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000756 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000757 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000758 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000759
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000760 Sema::OwningExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000761 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
762 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000763
Chandler Carruthb5719242010-02-13 07:23:01 +0000764 Expr *ResultExpr = 0;
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000765
766 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000767 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000768 else {
769 ResultExpr = Result.takeAs<Expr>();
770
771 if (ResultExpr != expr) {
772 // The type was promoted, update initializer list.
773 IList->setInit(Index, ResultExpr);
774 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000775 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000776 if (hadError)
777 ++StructuredIndex;
778 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000779 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000780 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000781 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000782 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000783 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000784 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000785 ++Index;
786 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000787 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000788 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000789}
790
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000791void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
792 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000793 unsigned &Index,
794 InitListExpr *StructuredList,
795 unsigned &StructuredIndex) {
796 if (Index < IList->getNumInits()) {
797 Expr *expr = IList->getInit(Index);
798 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000799 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000800 << DeclType << IList->getSourceRange();
801 hadError = true;
802 ++Index;
803 ++StructuredIndex;
804 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000805 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000806
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000807 Sema::OwningExprResult Result =
808 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
809 SemaRef.Owned(expr));
810
811 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000812 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000813
814 expr = Result.takeAs<Expr>();
815 IList->setInit(Index, expr);
816
Douglas Gregor930d8b52009-01-30 22:09:00 +0000817 if (hadError)
818 ++StructuredIndex;
819 else
820 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
821 ++Index;
822 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000823 // FIXME: It would be wonderful if we could point at the actual member. In
824 // general, it would be useful to pass location information down the stack,
825 // so that we know the location (or decl) of the "current object" being
826 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000827 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000828 diag::err_init_reference_member_uninitialized)
829 << DeclType
830 << IList->getSourceRange();
831 hadError = true;
832 ++Index;
833 ++StructuredIndex;
834 return;
835 }
836}
837
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000838void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000839 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000840 unsigned &Index,
841 InitListExpr *StructuredList,
842 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000843 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000844 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000845 unsigned maxElements = VT->getNumElements();
846 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000847 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Nate Begeman2ef13e52009-08-10 23:49:36 +0000849 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000850 InitializedEntity ElementEntity =
851 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000852
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000853 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
854 // Don't attempt to go past the end of the init list
855 if (Index >= IList->getNumInits())
856 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000857
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000858 ElementEntity.setElementIndex(Index);
859 CheckSubElementType(ElementEntity, IList, elementType, Index,
860 StructuredList, StructuredIndex);
861 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000862 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000863 InitializedEntity ElementEntity =
864 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
865
Nate Begeman2ef13e52009-08-10 23:49:36 +0000866 // OpenCL initializers allows vectors to be constructed from vectors.
867 for (unsigned i = 0; i < maxElements; ++i) {
868 // Don't attempt to go past the end of the init list
869 if (Index >= IList->getNumInits())
870 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000871
872 ElementEntity.setElementIndex(Index);
873
Nate Begeman2ef13e52009-08-10 23:49:36 +0000874 QualType IType = IList->getInit(Index)->getType();
875 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000876 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000877 StructuredList, StructuredIndex);
878 ++numEltsInit;
879 } else {
John McCall183700f2009-09-21 23:43:11 +0000880 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000881 unsigned numIElts = IVT->getNumElements();
882 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
883 numIElts);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000884 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000885 StructuredList, StructuredIndex);
886 numEltsInit += numIElts;
887 }
888 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000889 }
Mike Stump1eb44332009-09-09 15:08:12 +0000890
John Thompsonf3afbea2010-04-20 23:21:17 +0000891 // OpenCL requires all elements to be initialized.
Nate Begeman2ef13e52009-08-10 23:49:36 +0000892 if (numEltsInit != maxElements)
Chris Lattnere12a7792010-04-20 05:19:10 +0000893 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman2ef13e52009-08-10 23:49:36 +0000894 SemaRef.Diag(IList->getSourceRange().getBegin(),
895 diag::err_vector_incorrect_num_initializers)
896 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000897 }
898}
899
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000900void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000901 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000902 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000903 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000904 unsigned &Index,
905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000907 // Check for the special-case of initializing an array with a string.
908 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000909 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
910 SemaRef.Context)) {
911 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000912 // We place the string literal directly into the resulting
913 // initializer list. This is the only place where the structure
914 // of the structured initializer list doesn't match exactly,
915 // because doing so would involve allocating one character
916 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000917 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000918 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000919 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000920 return;
921 }
922 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000923 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000924 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000925 // Check for VLAs; in standard C it would be possible to check this
926 // earlier, but I don't know where clang accepts VLAs (gcc accepts
927 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000928 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000929 diag::err_variable_object_no_init)
930 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000931 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000932 ++Index;
933 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000934 return;
935 }
936
Douglas Gregor05c13a32009-01-22 00:58:24 +0000937 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000938 llvm::APSInt maxElements(elementIndex.getBitWidth(),
939 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000940 bool maxElementsKnown = false;
941 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000942 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000943 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000944 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000945 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000946 maxElementsKnown = true;
947 }
948
Chris Lattner08202542009-02-24 22:50:46 +0000949 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000950 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000951 while (Index < IList->getNumInits()) {
952 Expr *Init = IList->getInit(Index);
953 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000954 // If we're not the subobject that matches up with the '{' for
955 // the designator, we shouldn't be handling the
956 // designator. Return immediately.
957 if (!SubobjectIsDesignatorContext)
958 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000959
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000960 // Handle this designated initializer. elementIndex will be
961 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000962 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000963 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000964 StructuredList, StructuredIndex, true,
965 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000966 hadError = true;
967 continue;
968 }
969
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000970 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
971 maxElements.extend(elementIndex.getBitWidth());
972 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
973 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000974 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000975
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000976 // If the array is of incomplete type, keep track of the number of
977 // elements in the initializer.
978 if (!maxElementsKnown && elementIndex > maxElements)
979 maxElements = elementIndex;
980
Douglas Gregor05c13a32009-01-22 00:58:24 +0000981 continue;
982 }
983
984 // If we know the maximum number of elements, and we've already
985 // hit it, stop consuming elements in the initializer list.
986 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000987 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000988
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000989 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000990 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000991 Entity);
992 // Check this element.
993 CheckSubElementType(ElementEntity, IList, elementType, Index,
994 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000995 ++elementIndex;
996
997 // If the array is of incomplete type, keep track of the number of
998 // elements in the initializer.
999 if (!maxElementsKnown && elementIndex > maxElements)
1000 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001001 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001002 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001003 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001004 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001005 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001006 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001007 // Sizing an array implicitly to zero is not allowed by ISO C,
1008 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001009 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001010 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001011 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001012
Mike Stump1eb44332009-09-09 15:08:12 +00001013 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001014 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001015 }
1016}
1017
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001018void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001019 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001020 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001021 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001022 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001023 unsigned &Index,
1024 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001025 unsigned &StructuredIndex,
1026 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001027 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Eli Friedmanb85f7072008-05-19 19:16:24 +00001029 // If the record is invalid, some of it's members are invalid. To avoid
1030 // confusion, we forgo checking the intializer for the entire record.
1031 if (structDecl->isInvalidDecl()) {
1032 hadError = true;
1033 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001034 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001035
1036 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1037 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001038 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001039 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001040 Field != FieldEnd; ++Field) {
1041 if (Field->getDeclName()) {
1042 StructuredList->setInitializedFieldInUnion(*Field);
1043 break;
1044 }
1045 }
1046 return;
1047 }
1048
Douglas Gregor05c13a32009-01-22 00:58:24 +00001049 // If structDecl is a forward declaration, this loop won't do
1050 // anything except look at designated initializers; That's okay,
1051 // because an error should get printed out elsewhere. It might be
1052 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001053 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001054 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001055 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001056 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001057 while (Index < IList->getNumInits()) {
1058 Expr *Init = IList->getInit(Index);
1059
1060 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001061 // If we're not the subobject that matches up with the '{' for
1062 // the designator, we shouldn't be handling the
1063 // designator. Return immediately.
1064 if (!SubobjectIsDesignatorContext)
1065 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001066
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001067 // Handle this designated initializer. Field will be updated to
1068 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001069 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001070 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001071 StructuredList, StructuredIndex,
1072 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001073 hadError = true;
1074
Douglas Gregordfb5e592009-02-12 19:00:39 +00001075 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001076
1077 // Disable check for missing fields when designators are used.
1078 // This matches gcc behaviour.
1079 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001080 continue;
1081 }
1082
1083 if (Field == FieldEnd) {
1084 // We've run out of fields. We're done.
1085 break;
1086 }
1087
Douglas Gregordfb5e592009-02-12 19:00:39 +00001088 // We've already initialized a member of a union. We're done.
1089 if (InitializedSomething && DeclType->isUnionType())
1090 break;
1091
Douglas Gregor44b43212008-12-11 16:49:14 +00001092 // If we've hit the flexible array member at the end, we're done.
1093 if (Field->getType()->isIncompleteArrayType())
1094 break;
1095
Douglas Gregor0bb76892009-01-29 16:53:55 +00001096 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001097 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001098 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001099 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001100 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001101
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001102 InitializedEntity MemberEntity =
1103 InitializedEntity::InitializeMember(*Field, &Entity);
1104 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1105 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001106 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001107
1108 if (DeclType->isUnionType()) {
1109 // Initialize the first field within the union.
1110 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001111 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001112
1113 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001114 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001115
John McCall80639de2010-03-11 19:32:38 +00001116 // Emit warnings for missing struct field initializers.
Douglas Gregor8e198902010-06-18 21:43:10 +00001117 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001118 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1119 // It is possible we have one or more unnamed bitfields remaining.
1120 // Find first (if any) named field and emit warning.
1121 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1122 it != end; ++it) {
1123 if (!it->isUnnamedBitfield()) {
1124 SemaRef.Diag(IList->getSourceRange().getEnd(),
1125 diag::warn_missing_field_initializers) << it->getName();
1126 break;
1127 }
1128 }
1129 }
1130
Mike Stump1eb44332009-09-09 15:08:12 +00001131 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001132 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001133 return;
1134
1135 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001136 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001137 (!isa<InitListExpr>(IList->getInit(Index)) ||
1138 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001139 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001140 diag::err_flexible_array_init_nonempty)
1141 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001142 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001143 << *Field;
1144 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001145 ++Index;
1146 return;
1147 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001148 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001149 diag::ext_flexible_array_init)
1150 << IList->getInit(Index)->getSourceRange().getBegin();
1151 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1152 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001153 }
1154
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001155 InitializedEntity MemberEntity =
1156 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001157
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001158 if (isa<InitListExpr>(IList->getInit(Index)))
1159 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1160 StructuredList, StructuredIndex);
1161 else
1162 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001163 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001164}
Steve Naroff0cca7492008-05-01 22:18:59 +00001165
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001166/// \brief Expand a field designator that refers to a member of an
1167/// anonymous struct or union into a series of field designators that
1168/// refers to the field within the appropriate subobject.
1169///
1170/// Field/FieldIndex will be updated to point to the (new)
1171/// currently-designated field.
1172static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001173 DesignatedInitExpr *DIE,
1174 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001175 FieldDecl *Field,
1176 RecordDecl::field_iterator &FieldIter,
1177 unsigned &FieldIndex) {
1178 typedef DesignatedInitExpr::Designator Designator;
1179
1180 // Build the path from the current object to the member of the
1181 // anonymous struct/union (backwards).
1182 llvm::SmallVector<FieldDecl *, 4> Path;
1183 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001185 // Build the replacement designators.
1186 llvm::SmallVector<Designator, 4> Replacements;
1187 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1188 FI = Path.rbegin(), FIEnd = Path.rend();
1189 FI != FIEnd; ++FI) {
1190 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001191 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001192 DIE->getDesignator(DesigIdx)->getDotLoc(),
1193 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1194 else
1195 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1196 SourceLocation()));
1197 Replacements.back().setField(*FI);
1198 }
1199
1200 // Expand the current designator into the set of replacement
1201 // designators, so we have a full subobject path down to where the
1202 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001203 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001204 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001206 // Update FieldIter/FieldIndex;
1207 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001208 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001209 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001210 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001211 FieldIter != FEnd; ++FieldIter) {
1212 if (FieldIter->isUnnamedBitfield())
1213 continue;
1214
1215 if (*FieldIter == Path.back())
1216 return;
1217
1218 ++FieldIndex;
1219 }
1220
1221 assert(false && "Unable to find anonymous struct/union field");
1222}
1223
Douglas Gregor05c13a32009-01-22 00:58:24 +00001224/// @brief Check the well-formedness of a C99 designated initializer.
1225///
1226/// Determines whether the designated initializer @p DIE, which
1227/// resides at the given @p Index within the initializer list @p
1228/// IList, is well-formed for a current object of type @p DeclType
1229/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001230/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001231/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001232///
1233/// @param IList The initializer list in which this designated
1234/// initializer occurs.
1235///
Douglas Gregor71199712009-04-15 04:56:10 +00001236/// @param DIE The designated initializer expression.
1237///
1238/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001239///
1240/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1241/// into which the designation in @p DIE should refer.
1242///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001243/// @param NextField If non-NULL and the first designator in @p DIE is
1244/// a field, this will be set to the field declaration corresponding
1245/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001246///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001247/// @param NextElementIndex If non-NULL and the first designator in @p
1248/// DIE is an array designator or GNU array-range designator, this
1249/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001250///
1251/// @param Index Index into @p IList where the designated initializer
1252/// @p DIE occurs.
1253///
Douglas Gregor4c678342009-01-28 21:54:33 +00001254/// @param StructuredList The initializer list expression that
1255/// describes all of the subobject initializers in the order they'll
1256/// actually be initialized.
1257///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001258/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001259bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001260InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001261 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001262 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001263 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001264 QualType &CurrentObjectType,
1265 RecordDecl::field_iterator *NextField,
1266 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001267 unsigned &Index,
1268 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001269 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001270 bool FinishSubobjectInit,
1271 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001272 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001273 // Check the actual initialization for the designated object type.
1274 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001275
1276 // Temporarily remove the designator expression from the
1277 // initializer list that the child calls see, so that we don't try
1278 // to re-process the designator.
1279 unsigned OldIndex = Index;
1280 IList->setInit(OldIndex, DIE->getInit());
1281
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001282 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001283 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001284
1285 // Restore the designated initializer expression in the syntactic
1286 // form of the initializer list.
1287 if (IList->getInit(OldIndex) != DIE->getInit())
1288 DIE->setInit(IList->getInit(OldIndex));
1289 IList->setInit(OldIndex, DIE);
1290
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001291 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001292 }
1293
Douglas Gregor71199712009-04-15 04:56:10 +00001294 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001295 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001296 "Need a non-designated initializer list to start from");
1297
Douglas Gregor71199712009-04-15 04:56:10 +00001298 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001299 // Determine the structural initializer list that corresponds to the
1300 // current subobject.
1301 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001302 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001303 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001304 SourceRange(D->getStartLocation(),
1305 DIE->getSourceRange().getEnd()));
1306 assert(StructuredList && "Expected a structured initializer list");
1307
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001308 if (D->isFieldDesignator()) {
1309 // C99 6.7.8p7:
1310 //
1311 // If a designator has the form
1312 //
1313 // . identifier
1314 //
1315 // then the current object (defined below) shall have
1316 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001317 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001318 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001319 if (!RT) {
1320 SourceLocation Loc = D->getDotLoc();
1321 if (Loc.isInvalid())
1322 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001323 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1324 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001325 ++Index;
1326 return true;
1327 }
1328
Douglas Gregor4c678342009-01-28 21:54:33 +00001329 // Note: we perform a linear search of the fields here, despite
1330 // the fact that we have a faster lookup method, because we always
1331 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001332 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001333 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001334 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001335 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001336 Field = RT->getDecl()->field_begin(),
1337 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001338 for (; Field != FieldEnd; ++Field) {
1339 if (Field->isUnnamedBitfield())
1340 continue;
1341
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001342 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001343 break;
1344
1345 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001346 }
1347
Douglas Gregor4c678342009-01-28 21:54:33 +00001348 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001349 // There was no normal field in the struct with the designated
1350 // name. Perform another lookup for this name, which may find
1351 // something that we can't designate (e.g., a member function),
1352 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001353 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001354 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001355 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001356 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001357 // Name lookup didn't find anything. Determine whether this
1358 // was a typo for another field name.
1359 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1360 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001361 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1362 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001363 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1364 ReplacementField->getDeclContext()->getLookupContext()
1365 ->Equals(RT->getDecl())) {
1366 SemaRef.Diag(D->getFieldLoc(),
1367 diag::err_field_designator_unknown_suggest)
1368 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001369 << FixItHint::CreateReplacement(D->getFieldLoc(),
1370 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001371 SemaRef.Diag(ReplacementField->getLocation(),
1372 diag::note_previous_decl)
1373 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001374 } else {
1375 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1376 << FieldName << CurrentObjectType;
1377 ++Index;
1378 return true;
1379 }
1380 } else if (!KnownField) {
1381 // Determine whether we found a field at all.
1382 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1383 }
1384
1385 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001386 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001387 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001388 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001389 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001390 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001391 ++Index;
1392 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001393 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001394
1395 if (!KnownField &&
1396 cast<RecordDecl>((ReplacementField)->getDeclContext())
1397 ->isAnonymousStructOrUnion()) {
1398 // Handle an field designator that refers to a member of an
1399 // anonymous struct or union.
1400 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1401 ReplacementField,
1402 Field, FieldIndex);
1403 D = DIE->getDesignator(DesigIdx);
1404 } else if (!KnownField) {
1405 // The replacement field comes from typo correction; find it
1406 // in the list of fields.
1407 FieldIndex = 0;
1408 Field = RT->getDecl()->field_begin();
1409 for (; Field != FieldEnd; ++Field) {
1410 if (Field->isUnnamedBitfield())
1411 continue;
1412
1413 if (ReplacementField == *Field ||
1414 Field->getIdentifier() == ReplacementField->getIdentifier())
1415 break;
1416
1417 ++FieldIndex;
1418 }
1419 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001420 } else if (!KnownField &&
1421 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001422 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001423 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1424 Field, FieldIndex);
1425 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001426 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001427
1428 // All of the fields of a union are located at the same place in
1429 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001430 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001431 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001432 StructuredList->setInitializedFieldInUnion(*Field);
1433 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001434
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001435 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001436 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Douglas Gregor4c678342009-01-28 21:54:33 +00001438 // Make sure that our non-designated initializer list has space
1439 // for a subobject corresponding to this field.
1440 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001441 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001442
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001443 // This designator names a flexible array member.
1444 if (Field->getType()->isIncompleteArrayType()) {
1445 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001446 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001447 // We can't designate an object within the flexible array
1448 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001449 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001450 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001451 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001452 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001453 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001454 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001455 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001456 << *Field;
1457 Invalid = true;
1458 }
1459
1460 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1461 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001462 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001463 diag::err_flexible_array_init_needs_braces)
1464 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001465 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001466 << *Field;
1467 Invalid = true;
1468 }
1469
1470 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001471 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001472 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001473 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001474 diag::err_flexible_array_init_nonempty)
1475 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001476 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001477 << *Field;
1478 Invalid = true;
1479 }
1480
1481 if (Invalid) {
1482 ++Index;
1483 return true;
1484 }
1485
1486 // Initialize the array.
1487 bool prevHadError = hadError;
1488 unsigned newStructuredIndex = FieldIndex;
1489 unsigned OldIndex = Index;
1490 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001491
1492 InitializedEntity MemberEntity =
1493 InitializedEntity::InitializeMember(*Field, &Entity);
1494 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001495 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001496
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001497 IList->setInit(OldIndex, DIE);
1498 if (hadError && !prevHadError) {
1499 ++Field;
1500 ++FieldIndex;
1501 if (NextField)
1502 *NextField = Field;
1503 StructuredIndex = FieldIndex;
1504 return true;
1505 }
1506 } else {
1507 // Recurse to check later designated subobjects.
1508 QualType FieldType = (*Field)->getType();
1509 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001510
1511 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001512 InitializedEntity::InitializeMember(*Field, &Entity);
1513 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001514 FieldType, 0, 0, Index,
1515 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001516 true, false))
1517 return true;
1518 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001519
1520 // Find the position of the next field to be initialized in this
1521 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001522 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001523 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001524
1525 // If this the first designator, our caller will continue checking
1526 // the rest of this struct/class/union subobject.
1527 if (IsFirstDesignator) {
1528 if (NextField)
1529 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001530 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001531 return false;
1532 }
1533
Douglas Gregor34e79462009-01-28 23:36:17 +00001534 if (!FinishSubobjectInit)
1535 return false;
1536
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001537 // We've already initialized something in the union; we're done.
1538 if (RT->getDecl()->isUnion())
1539 return hadError;
1540
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001541 // Check the remaining fields within this class/struct/union subobject.
1542 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001543
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001544 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001545 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001546 return hadError && !prevHadError;
1547 }
1548
1549 // C99 6.7.8p6:
1550 //
1551 // If a designator has the form
1552 //
1553 // [ constant-expression ]
1554 //
1555 // then the current object (defined below) shall have array
1556 // type and the expression shall be an integer constant
1557 // expression. If the array is of unknown size, any
1558 // nonnegative value is valid.
1559 //
1560 // Additionally, cope with the GNU extension that permits
1561 // designators of the form
1562 //
1563 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001564 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001565 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001566 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001567 << CurrentObjectType;
1568 ++Index;
1569 return true;
1570 }
1571
1572 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001573 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1574 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001575 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001576 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001577 DesignatedEndIndex = DesignatedStartIndex;
1578 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001579 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001580
Mike Stump1eb44332009-09-09 15:08:12 +00001581
1582 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001583 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001584 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001585 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001586 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001587
Chris Lattner3bf68932009-04-25 21:59:05 +00001588 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001589 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001590 }
1591
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001592 if (isa<ConstantArrayType>(AT)) {
1593 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001594 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1595 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1596 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1597 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1598 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001599 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001600 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001601 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001602 << IndexExpr->getSourceRange();
1603 ++Index;
1604 return true;
1605 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001606 } else {
1607 // Make sure the bit-widths and signedness match.
1608 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1609 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001610 else if (DesignatedStartIndex.getBitWidth() <
1611 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001612 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1613 DesignatedStartIndex.setIsUnsigned(true);
1614 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregor4c678342009-01-28 21:54:33 +00001617 // Make sure that our non-designated initializer list has space
1618 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001619 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001620 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001621 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001622
Douglas Gregor34e79462009-01-28 23:36:17 +00001623 // Repeatedly perform subobject initializations in the range
1624 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001625
Douglas Gregor34e79462009-01-28 23:36:17 +00001626 // Move to the next designator
1627 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1628 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001629
1630 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001631 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001632
Douglas Gregor34e79462009-01-28 23:36:17 +00001633 while (DesignatedStartIndex <= DesignatedEndIndex) {
1634 // Recurse to check later designated subobjects.
1635 QualType ElementType = AT->getElementType();
1636 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001637
1638 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001639 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001640 ElementType, 0, 0, Index,
1641 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001642 (DesignatedStartIndex == DesignatedEndIndex),
1643 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001644 return true;
1645
1646 // Move to the next index in the array that we'll be initializing.
1647 ++DesignatedStartIndex;
1648 ElementIndex = DesignatedStartIndex.getZExtValue();
1649 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001650
1651 // If this the first designator, our caller will continue checking
1652 // the rest of this array subobject.
1653 if (IsFirstDesignator) {
1654 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001655 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001656 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001657 return false;
1658 }
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Douglas Gregor34e79462009-01-28 23:36:17 +00001660 if (!FinishSubobjectInit)
1661 return false;
1662
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001663 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001664 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001665 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001666 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001667 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001668 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001669}
1670
Douglas Gregor4c678342009-01-28 21:54:33 +00001671// Get the structured initializer list for a subobject of type
1672// @p CurrentObjectType.
1673InitListExpr *
1674InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1675 QualType CurrentObjectType,
1676 InitListExpr *StructuredList,
1677 unsigned StructuredIndex,
1678 SourceRange InitRange) {
1679 Expr *ExistingInit = 0;
1680 if (!StructuredList)
1681 ExistingInit = SyntacticToSemantic[IList];
1682 else if (StructuredIndex < StructuredList->getNumInits())
1683 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Douglas Gregor4c678342009-01-28 21:54:33 +00001685 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1686 return Result;
1687
1688 if (ExistingInit) {
1689 // We are creating an initializer list that initializes the
1690 // subobjects of the current object, but there was already an
1691 // initialization that completely initialized the current
1692 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001693 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001694 // struct X { int a, b; };
1695 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001696 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001697 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1698 // designated initializer re-initializes the whole
1699 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001700 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001701 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001702 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001703 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001704 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001705 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001706 << ExistingInit->getSourceRange();
1707 }
1708
Mike Stump1eb44332009-09-09 15:08:12 +00001709 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001710 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1711 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001712 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001713
Douglas Gregor2c792812010-02-09 00:50:06 +00001714 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor4c678342009-01-28 21:54:33 +00001715
Douglas Gregorfa219202009-03-20 23:58:33 +00001716 // Pre-allocate storage for the structured initializer list.
1717 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001718 unsigned NumInits = 0;
1719 if (!StructuredList)
1720 NumInits = IList->getNumInits();
1721 else if (Index < IList->getNumInits()) {
1722 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1723 NumInits = SubList->getNumInits();
1724 }
1725
Mike Stump1eb44332009-09-09 15:08:12 +00001726 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001727 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1728 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1729 NumElements = CAType->getSize().getZExtValue();
1730 // Simple heuristic so that we don't allocate a very large
1731 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001732 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001733 NumElements = 0;
1734 }
John McCall183700f2009-09-21 23:43:11 +00001735 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001736 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001737 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001738 RecordDecl *RDecl = RType->getDecl();
1739 if (RDecl->isUnion())
1740 NumElements = 1;
1741 else
Mike Stump1eb44332009-09-09 15:08:12 +00001742 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001743 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001744 }
1745
Douglas Gregor08457732009-03-21 18:13:52 +00001746 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001747 NumElements = IList->getNumInits();
1748
Ted Kremenek709210f2010-04-13 23:39:13 +00001749 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001750
Douglas Gregor4c678342009-01-28 21:54:33 +00001751 // Link this new initializer list into the structured initializer
1752 // lists.
1753 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001754 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001755 else {
1756 Result->setSyntacticForm(IList);
1757 SyntacticToSemantic[IList] = Result;
1758 }
1759
1760 return Result;
1761}
1762
1763/// Update the initializer at index @p StructuredIndex within the
1764/// structured initializer list to the value @p expr.
1765void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1766 unsigned &StructuredIndex,
1767 Expr *expr) {
1768 // No structured initializer list to update
1769 if (!StructuredList)
1770 return;
1771
Ted Kremenek709210f2010-04-13 23:39:13 +00001772 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1773 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001774 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001775 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001776 diag::warn_initializer_overrides)
1777 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001778 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001780 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001781 << PrevInit->getSourceRange();
1782 }
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Douglas Gregor4c678342009-01-28 21:54:33 +00001784 ++StructuredIndex;
1785}
1786
Douglas Gregor05c13a32009-01-22 00:58:24 +00001787/// Check that the given Index expression is a valid array designator
1788/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001789/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001790/// and produces a reasonable diagnostic if there is a
1791/// failure. Returns true if there was an error, false otherwise. If
1792/// everything went okay, Value will receive the value of the constant
1793/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001794static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001795CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001796 SourceLocation Loc = Index->getSourceRange().getBegin();
1797
1798 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001799 if (S.VerifyIntegerConstantExpression(Index, &Value))
1800 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001801
Chris Lattner3bf68932009-04-25 21:59:05 +00001802 if (Value.isSigned() && Value.isNegative())
1803 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001804 << Value.toString(10) << Index->getSourceRange();
1805
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001806 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001807 return false;
1808}
1809
1810Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1811 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001812 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001813 OwningExprResult Init) {
1814 typedef DesignatedInitExpr::Designator ASTDesignator;
1815
1816 bool Invalid = false;
1817 llvm::SmallVector<ASTDesignator, 32> Designators;
1818 llvm::SmallVector<Expr *, 32> InitExpressions;
1819
1820 // Build designators and check array designator expressions.
1821 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1822 const Designator &D = Desig.getDesignator(Idx);
1823 switch (D.getKind()) {
1824 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001825 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001826 D.getFieldLoc()));
1827 break;
1828
1829 case Designator::ArrayDesignator: {
1830 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1831 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001832 if (!Index->isTypeDependent() &&
1833 !Index->isValueDependent() &&
1834 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001835 Invalid = true;
1836 else {
1837 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001838 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001839 D.getRBracketLoc()));
1840 InitExpressions.push_back(Index);
1841 }
1842 break;
1843 }
1844
1845 case Designator::ArrayRangeDesignator: {
1846 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1847 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1848 llvm::APSInt StartValue;
1849 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001850 bool StartDependent = StartIndex->isTypeDependent() ||
1851 StartIndex->isValueDependent();
1852 bool EndDependent = EndIndex->isTypeDependent() ||
1853 EndIndex->isValueDependent();
1854 if ((!StartDependent &&
1855 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1856 (!EndDependent &&
1857 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001858 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001859 else {
1860 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001861 if (StartDependent || EndDependent) {
1862 // Nothing to compute.
1863 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001864 EndValue.extend(StartValue.getBitWidth());
1865 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1866 StartValue.extend(EndValue.getBitWidth());
1867
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001868 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001869 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001870 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001871 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1872 Invalid = true;
1873 } else {
1874 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001875 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001876 D.getEllipsisLoc(),
1877 D.getRBracketLoc()));
1878 InitExpressions.push_back(StartIndex);
1879 InitExpressions.push_back(EndIndex);
1880 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001881 }
1882 break;
1883 }
1884 }
1885 }
1886
1887 if (Invalid || Init.isInvalid())
1888 return ExprError();
1889
1890 // Clear out the expressions within the designation.
1891 Desig.ClearExprs(*this);
1892
1893 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001894 = DesignatedInitExpr::Create(Context,
1895 Designators.data(), Designators.size(),
1896 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001897 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001898 return Owned(DIE);
1899}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001900
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001901bool Sema::CheckInitList(const InitializedEntity &Entity,
1902 InitListExpr *&InitList, QualType &DeclType) {
1903 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001904 if (!CheckInitList.HadError())
1905 InitList = CheckInitList.getFullyStructuredList();
1906
1907 return CheckInitList.HadError();
1908}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001909
Douglas Gregor20093b42009-12-09 23:02:17 +00001910//===----------------------------------------------------------------------===//
1911// Initialization entity
1912//===----------------------------------------------------------------------===//
1913
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001914InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1915 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001916 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001917{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001918 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1919 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001920 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001921 } else {
1922 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001923 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001924 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001925}
1926
1927InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001928 CXXBaseSpecifier *Base,
1929 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001930{
1931 InitializedEntity Result;
1932 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001933 Result.Base = reinterpret_cast<uintptr_t>(Base);
1934 if (IsInheritedVirtualBase)
1935 Result.Base |= 0x01;
1936
Douglas Gregord6542d82009-12-22 15:35:07 +00001937 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001938 return Result;
1939}
1940
Douglas Gregor99a2e602009-12-16 01:38:02 +00001941DeclarationName InitializedEntity::getName() const {
1942 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001943 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001944 if (!VariableOrMember)
1945 return DeclarationName();
1946 // Fall through
1947
1948 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001949 case EK_Member:
1950 return VariableOrMember->getDeclName();
1951
1952 case EK_Result:
1953 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001954 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001955 case EK_Temporary:
1956 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001957 case EK_ArrayElement:
1958 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001959 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001960 return DeclarationName();
1961 }
1962
1963 // Silence GCC warning
1964 return DeclarationName();
1965}
1966
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001967DeclaratorDecl *InitializedEntity::getDecl() const {
1968 switch (getKind()) {
1969 case EK_Variable:
1970 case EK_Parameter:
1971 case EK_Member:
1972 return VariableOrMember;
1973
1974 case EK_Result:
1975 case EK_Exception:
1976 case EK_New:
1977 case EK_Temporary:
1978 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001979 case EK_ArrayElement:
1980 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001981 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001982 return 0;
1983 }
1984
1985 // Silence GCC warning
1986 return 0;
1987}
1988
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001989bool InitializedEntity::allowsNRVO() const {
1990 switch (getKind()) {
1991 case EK_Result:
1992 case EK_Exception:
1993 return LocAndNRVO.NRVO;
1994
1995 case EK_Variable:
1996 case EK_Parameter:
1997 case EK_Member:
1998 case EK_New:
1999 case EK_Temporary:
2000 case EK_Base:
2001 case EK_ArrayElement:
2002 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002003 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002004 break;
2005 }
2006
2007 return false;
2008}
2009
Douglas Gregor20093b42009-12-09 23:02:17 +00002010//===----------------------------------------------------------------------===//
2011// Initialization sequence
2012//===----------------------------------------------------------------------===//
2013
2014void InitializationSequence::Step::Destroy() {
2015 switch (Kind) {
2016 case SK_ResolveAddressOfOverloadedFunction:
2017 case SK_CastDerivedToBaseRValue:
2018 case SK_CastDerivedToBaseLValue:
2019 case SK_BindReference:
2020 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002021 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002022 case SK_UserConversion:
2023 case SK_QualificationConversionRValue:
2024 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002025 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002026 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002027 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002028 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002029 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00002030 break;
2031
2032 case SK_ConversionSequence:
2033 delete ICS;
2034 }
2035}
2036
Douglas Gregorb70cf442010-03-26 20:14:36 +00002037bool InitializationSequence::isDirectReferenceBinding() const {
2038 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2039}
2040
2041bool InitializationSequence::isAmbiguous() const {
2042 if (getKind() != FailedSequence)
2043 return false;
2044
2045 switch (getFailureKind()) {
2046 case FK_TooManyInitsForReference:
2047 case FK_ArrayNeedsInitList:
2048 case FK_ArrayNeedsInitListOrStringLiteral:
2049 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2050 case FK_NonConstLValueReferenceBindingToTemporary:
2051 case FK_NonConstLValueReferenceBindingToUnrelated:
2052 case FK_RValueReferenceBindingToLValue:
2053 case FK_ReferenceInitDropsQualifiers:
2054 case FK_ReferenceInitFailed:
2055 case FK_ConversionFailed:
2056 case FK_TooManyInitsForScalar:
2057 case FK_ReferenceBindingToInitList:
2058 case FK_InitListBadDestinationType:
2059 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002060 case FK_Incomplete:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002061 return false;
2062
2063 case FK_ReferenceInitOverloadFailed:
2064 case FK_UserConversionOverloadFailed:
2065 case FK_ConstructorOverloadFailed:
2066 return FailedOverloadResult == OR_Ambiguous;
2067 }
2068
2069 return false;
2070}
2071
Douglas Gregord6e44a32010-04-16 22:09:46 +00002072bool InitializationSequence::isConstructorInitialization() const {
2073 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2074}
2075
Douglas Gregor20093b42009-12-09 23:02:17 +00002076void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002077 FunctionDecl *Function,
2078 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002079 Step S;
2080 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2081 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002082 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002083 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002084 Steps.push_back(S);
2085}
2086
2087void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2088 bool IsLValue) {
2089 Step S;
2090 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2091 S.Type = BaseType;
2092 Steps.push_back(S);
2093}
2094
2095void InitializationSequence::AddReferenceBindingStep(QualType T,
2096 bool BindingTemporary) {
2097 Step S;
2098 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2099 S.Type = T;
2100 Steps.push_back(S);
2101}
2102
Douglas Gregor523d46a2010-04-18 07:40:54 +00002103void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2104 Step S;
2105 S.Kind = SK_ExtraneousCopyToTemporary;
2106 S.Type = T;
2107 Steps.push_back(S);
2108}
2109
Eli Friedman03981012009-12-11 02:42:07 +00002110void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002111 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002112 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002113 Step S;
2114 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002115 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002116 S.Function.Function = Function;
2117 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002118 Steps.push_back(S);
2119}
2120
2121void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2122 bool IsLValue) {
2123 Step S;
2124 S.Kind = IsLValue? SK_QualificationConversionLValue
2125 : SK_QualificationConversionRValue;
2126 S.Type = Ty;
2127 Steps.push_back(S);
2128}
2129
2130void InitializationSequence::AddConversionSequenceStep(
2131 const ImplicitConversionSequence &ICS,
2132 QualType T) {
2133 Step S;
2134 S.Kind = SK_ConversionSequence;
2135 S.Type = T;
2136 S.ICS = new ImplicitConversionSequence(ICS);
2137 Steps.push_back(S);
2138}
2139
Douglas Gregord87b61f2009-12-10 17:56:55 +00002140void InitializationSequence::AddListInitializationStep(QualType T) {
2141 Step S;
2142 S.Kind = SK_ListInitialization;
2143 S.Type = T;
2144 Steps.push_back(S);
2145}
2146
Douglas Gregor51c56d62009-12-14 20:49:26 +00002147void
2148InitializationSequence::AddConstructorInitializationStep(
2149 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002150 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002151 QualType T) {
2152 Step S;
2153 S.Kind = SK_ConstructorInitialization;
2154 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002155 S.Function.Function = Constructor;
2156 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002157 Steps.push_back(S);
2158}
2159
Douglas Gregor71d17402009-12-15 00:01:57 +00002160void InitializationSequence::AddZeroInitializationStep(QualType T) {
2161 Step S;
2162 S.Kind = SK_ZeroInitialization;
2163 S.Type = T;
2164 Steps.push_back(S);
2165}
2166
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002167void InitializationSequence::AddCAssignmentStep(QualType T) {
2168 Step S;
2169 S.Kind = SK_CAssignment;
2170 S.Type = T;
2171 Steps.push_back(S);
2172}
2173
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002174void InitializationSequence::AddStringInitStep(QualType T) {
2175 Step S;
2176 S.Kind = SK_StringInit;
2177 S.Type = T;
2178 Steps.push_back(S);
2179}
2180
Douglas Gregor20093b42009-12-09 23:02:17 +00002181void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2182 OverloadingResult Result) {
2183 SequenceKind = FailedSequence;
2184 this->Failure = Failure;
2185 this->FailedOverloadResult = Result;
2186}
2187
2188//===----------------------------------------------------------------------===//
2189// Attempt initialization
2190//===----------------------------------------------------------------------===//
2191
2192/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002193static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002194 const InitializedEntity &Entity,
2195 const InitializationKind &Kind,
2196 InitListExpr *InitList,
2197 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002198 // FIXME: We only perform rudimentary checking of list
2199 // initializations at this point, then assume that any list
2200 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002201 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002202 // do all of the necessary checking. C++0x initializer lists will
2203 // force us to perform more checking here.
2204 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2205
Douglas Gregord6542d82009-12-22 15:35:07 +00002206 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002207
2208 // C++ [dcl.init]p13:
2209 // If T is a scalar type, then a declaration of the form
2210 //
2211 // T x = { a };
2212 //
2213 // is equivalent to
2214 //
2215 // T x = a;
2216 if (DestType->isScalarType()) {
2217 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2218 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2219 return;
2220 }
2221
2222 // Assume scalar initialization from a single value works.
2223 } else if (DestType->isAggregateType()) {
2224 // Assume aggregate initialization works.
2225 } else if (DestType->isVectorType()) {
2226 // Assume vector initialization works.
2227 } else if (DestType->isReferenceType()) {
2228 // FIXME: C++0x defines behavior for this.
2229 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2230 return;
2231 } else if (DestType->isRecordType()) {
2232 // FIXME: C++0x defines behavior for this
2233 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2234 }
2235
2236 // Add a general "list initialization" step.
2237 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002238}
2239
2240/// \brief Try a reference initialization that involves calling a conversion
2241/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002242static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2243 const InitializedEntity &Entity,
2244 const InitializationKind &Kind,
2245 Expr *Initializer,
2246 bool AllowRValues,
2247 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002248 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002249 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2250 QualType T1 = cv1T1.getUnqualifiedType();
2251 QualType cv2T2 = Initializer->getType();
2252 QualType T2 = cv2T2.getUnqualifiedType();
2253
2254 bool DerivedToBase;
2255 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2256 T1, T2, DerivedToBase) &&
2257 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002258 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002259
2260 // Build the candidate set directly in the initialization sequence
2261 // structure, so that it will persist if we fail.
2262 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2263 CandidateSet.clear();
2264
2265 // Determine whether we are allowed to call explicit constructors or
2266 // explicit conversion operators.
2267 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2268
2269 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002270 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2271 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002272 // The type we're converting to is a class type. Enumerate its constructors
2273 // to see if there is a suitable conversion.
2274 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
Douglas Gregor20093b42009-12-09 23:02:17 +00002275 DeclarationName ConstructorName
2276 = S.Context.DeclarationNames.getCXXConstructorName(
2277 S.Context.getCanonicalType(T1).getUnqualifiedType());
2278 DeclContext::lookup_iterator Con, ConEnd;
2279 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2280 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002281 NamedDecl *D = *Con;
2282 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2283
Douglas Gregor20093b42009-12-09 23:02:17 +00002284 // Find the constructor (which may be a template).
2285 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002286 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002287 if (ConstructorTmpl)
2288 Constructor = cast<CXXConstructorDecl>(
2289 ConstructorTmpl->getTemplatedDecl());
2290 else
John McCall9aa472c2010-03-19 07:35:19 +00002291 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002292
2293 if (!Constructor->isInvalidDecl() &&
2294 Constructor->isConvertingConstructor(AllowExplicit)) {
2295 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002296 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002297 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002298 &Initializer, 1, CandidateSet);
2299 else
John McCall9aa472c2010-03-19 07:35:19 +00002300 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002301 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002302 }
2303 }
2304 }
2305
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002306 const RecordType *T2RecordType = 0;
2307 if ((T2RecordType = T2->getAs<RecordType>()) &&
2308 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002309 // The type we're converting from is a class type, enumerate its conversion
2310 // functions.
2311 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2312
2313 // Determine the type we are converting to. If we are allowed to
2314 // convert to an rvalue, take the type that the destination type
2315 // refers to.
2316 QualType ToType = AllowRValues? cv1T1 : DestType;
2317
John McCalleec51cf2010-01-20 00:46:10 +00002318 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002319 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002320 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2321 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002322 NamedDecl *D = *I;
2323 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2324 if (isa<UsingShadowDecl>(D))
2325 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2326
2327 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2328 CXXConversionDecl *Conv;
2329 if (ConvTemplate)
2330 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2331 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002332 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002333
2334 // If the conversion function doesn't return a reference type,
2335 // it can't be considered for this conversion unless we're allowed to
2336 // consider rvalues.
2337 // FIXME: Do we need to make sure that we only consider conversion
2338 // candidates with reference-compatible results? That might be needed to
2339 // break recursion.
2340 if ((AllowExplicit || !Conv->isExplicit()) &&
2341 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2342 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002343 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002344 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002345 ToType, CandidateSet);
2346 else
John McCall9aa472c2010-03-19 07:35:19 +00002347 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002348 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002349 }
2350 }
2351 }
2352
2353 SourceLocation DeclLoc = Initializer->getLocStart();
2354
2355 // Perform overload resolution. If it fails, return the failed result.
2356 OverloadCandidateSet::iterator Best;
2357 if (OverloadingResult Result
2358 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2359 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002360
Douglas Gregor20093b42009-12-09 23:02:17 +00002361 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002362
2363 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002364 if (isa<CXXConversionDecl>(Function))
2365 T2 = Function->getResultType();
2366 else
2367 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002368
2369 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002370 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
John McCallb13b7372010-02-01 03:16:54 +00002371 T2.getNonReferenceType());
Eli Friedman03981012009-12-11 02:42:07 +00002372
2373 // Determine whether we need to perform derived-to-base or
2374 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002375 bool NewDerivedToBase = false;
2376 Sema::ReferenceCompareResult NewRefRelationship
2377 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2378 NewDerivedToBase);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002379 if (NewRefRelationship == Sema::Ref_Incompatible) {
2380 // If the type we've converted to is not reference-related to the
2381 // type we're looking for, then there is another conversion step
2382 // we need to perform to produce a temporary of the right type
2383 // that we'll be binding to.
2384 ImplicitConversionSequence ICS;
2385 ICS.setStandard();
2386 ICS.Standard = Best->FinalConversion;
2387 T2 = ICS.Standard.getToType(2);
2388 Sequence.AddConversionSequenceStep(ICS, T2);
2389 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002390 Sequence.AddDerivedToBaseCastStep(
2391 S.Context.getQualifiedType(T1,
2392 T2.getNonReferenceType().getQualifiers()),
2393 /*isLValue=*/true);
2394
2395 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2396 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2397
2398 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2399 return OR_Success;
2400}
2401
Sebastian Redl4680bf22010-06-30 18:13:39 +00002402/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor20093b42009-12-09 23:02:17 +00002403static void TryReferenceInitialization(Sema &S,
2404 const InitializedEntity &Entity,
2405 const InitializationKind &Kind,
2406 Expr *Initializer,
2407 InitializationSequence &Sequence) {
2408 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002409
Douglas Gregord6542d82009-12-22 15:35:07 +00002410 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002411 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002412 Qualifiers T1Quals;
2413 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002414 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002415 Qualifiers T2Quals;
2416 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002417 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002418
Douglas Gregor20093b42009-12-09 23:02:17 +00002419 // If the initializer is the address of an overloaded function, try
2420 // to resolve the overloaded function. If all goes well, T2 is the
2421 // type of the resulting function.
2422 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002423 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002424 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2425 T1,
John McCall6bb80172010-03-30 21:47:33 +00002426 false,
2427 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002428 if (!Fn) {
2429 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2430 return;
2431 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002432
John McCall6bb80172010-03-30 21:47:33 +00002433 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002434 cv2T2 = Fn->getType();
2435 T2 = cv2T2.getUnqualifiedType();
2436 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002437
Douglas Gregor20093b42009-12-09 23:02:17 +00002438 // Compute some basic properties of the types and the initializer.
2439 bool isLValueRef = DestType->isLValueReferenceType();
2440 bool isRValueRef = !isLValueRef;
2441 bool DerivedToBase = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002442 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002443 Sema::ReferenceCompareResult RefRelationship
2444 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002445
Douglas Gregor20093b42009-12-09 23:02:17 +00002446 // C++0x [dcl.init.ref]p5:
2447 // A reference to type "cv1 T1" is initialized by an expression of type
2448 // "cv2 T2" as follows:
2449 //
2450 // - If the reference is an lvalue reference and the initializer
2451 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002452 // Note the analogous bullet points for rvlaue refs to functions. Because
2453 // there are no function rvalues in C++, rvalue refs to functions are treated
2454 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002455 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002456 bool T1Function = T1->isFunctionType();
2457 if (isLValueRef || T1Function) {
2458 if (InitCategory.isLValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002459 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2460 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2461 // reference-compatible with "cv2 T2," or
2462 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002463 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002464 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002465 // can occur. However, we do pay attention to whether it is a bit-field
2466 // to decide whether we're actually binding to a temporary created from
2467 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002468 if (DerivedToBase)
2469 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002470 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002471 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002472 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002473 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002474 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002475 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002476 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002477 return;
2478 }
2479
2480 // - has a class type (i.e., T2 is a class type), where T1 is not
2481 // reference-related to T2, and can be implicitly converted to an
2482 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2483 // with "cv3 T3" (this conversion is selected by enumerating the
2484 // applicable conversion functions (13.3.1.6) and choosing the best
2485 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002486 // If we have an rvalue ref to function type here, the rhs must be
2487 // an rvalue.
2488 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2489 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002490 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2491 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002492 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002493 Sequence);
2494 if (ConvOvlResult == OR_Success)
2495 return;
John McCall1d318332010-01-12 00:44:57 +00002496 if (ConvOvlResult != OR_No_Viable_Function) {
2497 Sequence.SetOverloadFailure(
2498 InitializationSequence::FK_ReferenceInitOverloadFailed,
2499 ConvOvlResult);
2500 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002501 }
2502 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002503
Douglas Gregor20093b42009-12-09 23:02:17 +00002504 // - Otherwise, the reference shall be an lvalue reference to a
2505 // non-volatile const type (i.e., cv1 shall be const), or the reference
2506 // shall be an rvalue reference and the initializer expression shall
Sebastian Redl4680bf22010-06-30 18:13:39 +00002507 // be an rvalue or have a function type.
2508 // We handled the function type stuff above.
Douglas Gregoref06e242010-01-29 19:39:15 +00002509 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redl4680bf22010-06-30 18:13:39 +00002510 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002511 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2512 Sequence.SetOverloadFailure(
2513 InitializationSequence::FK_ReferenceInitOverloadFailed,
2514 ConvOvlResult);
2515 else if (isLValueRef)
Sebastian Redl4680bf22010-06-30 18:13:39 +00002516 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002517 ? (RefRelationship == Sema::Ref_Related
2518 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2519 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2520 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2521 else
2522 Sequence.SetFailed(
2523 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002524
Douglas Gregor20093b42009-12-09 23:02:17 +00002525 return;
2526 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002527
2528 // - [If T1 is not a function type], if T2 is a class type and
2529 if (!T1Function && T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002530 // - the initializer expression is an rvalue and "cv1 T1" is
2531 // reference-compatible with "cv2 T2", or
Sebastian Redl4680bf22010-06-30 18:13:39 +00002532 if (InitCategory.isRValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002533 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002534 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2535 // compiler the freedom to perform a copy here or bind to the
2536 // object, while C++0x requires that we bind directly to the
2537 // object. Hence, we always bind to the object without making an
2538 // extra copy. However, in C++03 requires that we check for the
2539 // presence of a suitable copy constructor:
2540 //
2541 // The constructor that would be used to make the copy shall
2542 // be callable whether or not the copy is actually done.
2543 if (!S.getLangOptions().CPlusPlus0x)
2544 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2545
Douglas Gregor20093b42009-12-09 23:02:17 +00002546 if (DerivedToBase)
2547 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002548 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002549 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002550 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002551 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2552 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2553 return;
2554 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002555
Douglas Gregor20093b42009-12-09 23:02:17 +00002556 // - T1 is not reference-related to T2 and the initializer expression
2557 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2558 // conversion is selected by enumerating the applicable conversion
2559 // functions (13.3.1.6) and choosing the best one through overload
2560 // resolution (13.3)),
2561 if (RefRelationship == Sema::Ref_Incompatible) {
2562 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2563 Kind, Initializer,
2564 /*AllowRValues=*/true,
2565 Sequence);
2566 if (ConvOvlResult)
2567 Sequence.SetOverloadFailure(
2568 InitializationSequence::FK_ReferenceInitOverloadFailed,
2569 ConvOvlResult);
2570
2571 return;
2572 }
2573
2574 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2575 return;
2576 }
2577
2578 // - If the initializer expression is an rvalue, with T2 an array type,
2579 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2580 // is bound to the object represented by the rvalue (see 3.10).
2581 // FIXME: How can an array type be reference-compatible with anything?
2582 // Don't we mean the element types of T1 and T2?
2583
2584 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2585 // from the initializer expression using the rules for a non-reference
2586 // copy initialization (8.5). The reference is then bound to the
2587 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002588
Douglas Gregor20093b42009-12-09 23:02:17 +00002589 // Determine whether we are allowed to call explicit constructors or
2590 // explicit conversion operators.
2591 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002592
2593 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2594
2595 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2596 /*SuppressUserConversions*/ false,
2597 AllowExplicit,
2598 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002599 // FIXME: Use the conversion function set stored in ICS to turn
2600 // this into an overloading ambiguity diagnostic. However, we need
2601 // to keep that set as an OverloadCandidateSet rather than as some
2602 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002603 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2604 Sequence.SetOverloadFailure(
2605 InitializationSequence::FK_ReferenceInitOverloadFailed,
2606 ConvOvlResult);
2607 else
2608 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002609 return;
2610 }
2611
2612 // [...] If T1 is reference-related to T2, cv1 must be the
2613 // same cv-qualification as, or greater cv-qualification
2614 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002615 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2616 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002617 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002618 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002619 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2620 return;
2621 }
2622
Douglas Gregor20093b42009-12-09 23:02:17 +00002623 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2624 return;
2625}
2626
2627/// \brief Attempt character array initialization from a string literal
2628/// (C++ [dcl.init.string], C99 6.7.8).
2629static void TryStringLiteralInitialization(Sema &S,
2630 const InitializedEntity &Entity,
2631 const InitializationKind &Kind,
2632 Expr *Initializer,
2633 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002634 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002635 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002636}
2637
Douglas Gregor20093b42009-12-09 23:02:17 +00002638/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2639/// enumerates the constructors of the initialized entity and performs overload
2640/// resolution to select the best.
2641static void TryConstructorInitialization(Sema &S,
2642 const InitializedEntity &Entity,
2643 const InitializationKind &Kind,
2644 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002645 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002646 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002647 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002648
2649 // Build the candidate set directly in the initialization sequence
2650 // structure, so that it will persist if we fail.
2651 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2652 CandidateSet.clear();
2653
2654 // Determine whether we are allowed to call explicit constructors or
2655 // explicit conversion operators.
2656 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2657 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002658 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002659
2660 // The type we're constructing needs to be complete.
2661 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002662 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002663 return;
2664 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002665
2666 // The type we're converting to is a class type. Enumerate its constructors
2667 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002668 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2669 assert(DestRecordType && "Constructor initialization requires record type");
2670 CXXRecordDecl *DestRecordDecl
2671 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2672
2673 DeclarationName ConstructorName
2674 = S.Context.DeclarationNames.getCXXConstructorName(
2675 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2676 DeclContext::lookup_iterator Con, ConEnd;
2677 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2678 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002679 NamedDecl *D = *Con;
2680 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002681 bool SuppressUserConversions = false;
2682
Douglas Gregor51c56d62009-12-14 20:49:26 +00002683 // Find the constructor (which may be a template).
2684 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002685 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002686 if (ConstructorTmpl)
2687 Constructor = cast<CXXConstructorDecl>(
2688 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002689 else {
John McCall9aa472c2010-03-19 07:35:19 +00002690 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002691
2692 // If we're performing copy initialization using a copy constructor, we
2693 // suppress user-defined conversions on the arguments.
2694 // FIXME: Move constructors?
2695 if (Kind.getKind() == InitializationKind::IK_Copy &&
2696 Constructor->isCopyConstructor())
2697 SuppressUserConversions = true;
2698 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002699
2700 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002701 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002702 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002703 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002704 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002705 Args, NumArgs, CandidateSet,
2706 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002707 else
John McCall9aa472c2010-03-19 07:35:19 +00002708 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002709 Args, NumArgs, CandidateSet,
2710 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002711 }
2712 }
2713
2714 SourceLocation DeclLoc = Kind.getLocation();
2715
2716 // Perform overload resolution. If it fails, return the failed result.
2717 OverloadCandidateSet::iterator Best;
2718 if (OverloadingResult Result
2719 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2720 Sequence.SetOverloadFailure(
2721 InitializationSequence::FK_ConstructorOverloadFailed,
2722 Result);
2723 return;
2724 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002725
2726 // C++0x [dcl.init]p6:
2727 // If a program calls for the default initialization of an object
2728 // of a const-qualified type T, T shall be a class type with a
2729 // user-provided default constructor.
2730 if (Kind.getKind() == InitializationKind::IK_Default &&
2731 Entity.getType().isConstQualified() &&
2732 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2733 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2734 return;
2735 }
2736
Douglas Gregor51c56d62009-12-14 20:49:26 +00002737 // Add the constructor initialization step. Any cv-qualification conversion is
2738 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002739 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002740 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002741 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002742 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002743}
2744
Douglas Gregor71d17402009-12-15 00:01:57 +00002745/// \brief Attempt value initialization (C++ [dcl.init]p7).
2746static void TryValueInitialization(Sema &S,
2747 const InitializedEntity &Entity,
2748 const InitializationKind &Kind,
2749 InitializationSequence &Sequence) {
2750 // C++ [dcl.init]p5:
2751 //
2752 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002753 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002754
2755 // -- if T is an array type, then each element is value-initialized;
2756 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2757 T = AT->getElementType();
2758
2759 if (const RecordType *RT = T->getAs<RecordType>()) {
2760 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2761 // -- if T is a class type (clause 9) with a user-declared
2762 // constructor (12.1), then the default constructor for T is
2763 // called (and the initialization is ill-formed if T has no
2764 // accessible default constructor);
2765 //
2766 // FIXME: we really want to refer to a single subobject of the array,
2767 // but Entity doesn't have a way to capture that (yet).
2768 if (ClassDecl->hasUserDeclaredConstructor())
2769 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2770
Douglas Gregor16006c92009-12-16 18:50:27 +00002771 // -- if T is a (possibly cv-qualified) non-union class type
2772 // without a user-provided constructor, then the object is
2773 // zero-initialized and, if T’s implicitly-declared default
2774 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002775 if ((ClassDecl->getTagKind() == TTK_Class ||
2776 ClassDecl->getTagKind() == TTK_Struct) &&
Douglas Gregor16006c92009-12-16 18:50:27 +00002777 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002778 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002779 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2780 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002781 }
2782 }
2783
Douglas Gregord6542d82009-12-22 15:35:07 +00002784 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002785 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2786}
2787
Douglas Gregor99a2e602009-12-16 01:38:02 +00002788/// \brief Attempt default initialization (C++ [dcl.init]p6).
2789static void TryDefaultInitialization(Sema &S,
2790 const InitializedEntity &Entity,
2791 const InitializationKind &Kind,
2792 InitializationSequence &Sequence) {
2793 assert(Kind.getKind() == InitializationKind::IK_Default);
2794
2795 // C++ [dcl.init]p6:
2796 // To default-initialize an object of type T means:
2797 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002798 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002799 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2800 DestType = Array->getElementType();
2801
2802 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2803 // constructor for T is called (and the initialization is ill-formed if
2804 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002805 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002806 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2807 Sequence);
2808 }
2809
2810 // - otherwise, no initialization is performed.
2811 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2812
2813 // If a program calls for the default initialization of an object of
2814 // a const-qualified type T, T shall be a class type with a user-provided
2815 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002816 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002817 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2818}
2819
Douglas Gregor20093b42009-12-09 23:02:17 +00002820/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2821/// which enumerates all conversion functions and performs overload resolution
2822/// to select the best.
2823static void TryUserDefinedConversion(Sema &S,
2824 const InitializedEntity &Entity,
2825 const InitializationKind &Kind,
2826 Expr *Initializer,
2827 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002828 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2829
Douglas Gregord6542d82009-12-22 15:35:07 +00002830 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002831 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2832 QualType SourceType = Initializer->getType();
2833 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2834 "Must have a class type to perform a user-defined conversion");
2835
2836 // Build the candidate set directly in the initialization sequence
2837 // structure, so that it will persist if we fail.
2838 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2839 CandidateSet.clear();
2840
2841 // Determine whether we are allowed to call explicit constructors or
2842 // explicit conversion operators.
2843 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2844
2845 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2846 // The type we're converting to is a class type. Enumerate its constructors
2847 // to see if there is a suitable conversion.
2848 CXXRecordDecl *DestRecordDecl
2849 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2850
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002851 // Try to complete the type we're converting to.
2852 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2853 DeclarationName ConstructorName
2854 = S.Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4a520a22009-12-14 17:27:33 +00002855 S.Context.getCanonicalType(DestType).getUnqualifiedType());
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002856 DeclContext::lookup_iterator Con, ConEnd;
2857 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2858 Con != ConEnd; ++Con) {
2859 NamedDecl *D = *Con;
2860 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002861
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002862 // Find the constructor (which may be a template).
2863 CXXConstructorDecl *Constructor = 0;
2864 FunctionTemplateDecl *ConstructorTmpl
2865 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002866 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002867 Constructor = cast<CXXConstructorDecl>(
2868 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002869 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002870 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002871
2872 if (!Constructor->isInvalidDecl() &&
2873 Constructor->isConvertingConstructor(AllowExplicit)) {
2874 if (ConstructorTmpl)
2875 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2876 /*ExplicitArgs*/ 0,
2877 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002878 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002879 else
2880 S.AddOverloadCandidate(Constructor, FoundDecl,
2881 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002882 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002883 }
2884 }
2885 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002886 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002887
2888 SourceLocation DeclLoc = Initializer->getLocStart();
2889
Douglas Gregor4a520a22009-12-14 17:27:33 +00002890 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2891 // The type we're converting from is a class type, enumerate its conversion
2892 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002893
Eli Friedman33c2da92009-12-20 22:12:03 +00002894 // We can only enumerate the conversion functions for a complete type; if
2895 // the type isn't complete, simply skip this step.
2896 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2897 CXXRecordDecl *SourceRecordDecl
2898 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002899
John McCalleec51cf2010-01-20 00:46:10 +00002900 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002901 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002902 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002903 E = Conversions->end();
2904 I != E; ++I) {
2905 NamedDecl *D = *I;
2906 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2907 if (isa<UsingShadowDecl>(D))
2908 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2909
2910 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2911 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002912 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002913 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002914 else
John McCall32daa422010-03-31 01:36:47 +00002915 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00002916
2917 if (AllowExplicit || !Conv->isExplicit()) {
2918 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002919 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002920 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002921 CandidateSet);
2922 else
John McCall9aa472c2010-03-19 07:35:19 +00002923 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00002924 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002925 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002926 }
2927 }
2928 }
2929
Douglas Gregor4a520a22009-12-14 17:27:33 +00002930 // Perform overload resolution. If it fails, return the failed result.
2931 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002932 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002933 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2934 Sequence.SetOverloadFailure(
2935 InitializationSequence::FK_UserConversionOverloadFailed,
2936 Result);
2937 return;
2938 }
John McCall1d318332010-01-12 00:44:57 +00002939
Douglas Gregor4a520a22009-12-14 17:27:33 +00002940 FunctionDecl *Function = Best->Function;
2941
2942 if (isa<CXXConstructorDecl>(Function)) {
2943 // Add the user-defined conversion step. Any cv-qualification conversion is
2944 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00002945 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002946 return;
2947 }
2948
2949 // Add the user-defined conversion step that calls the conversion function.
2950 QualType ConvType = Function->getResultType().getNonReferenceType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002951 if (ConvType->getAs<RecordType>()) {
2952 // If we're converting to a class type, there may be an copy if
2953 // the resulting temporary object (possible to create an object of
2954 // a base class type). That copy is not a separate conversion, so
2955 // we just make a note of the actual destination type (possibly a
2956 // base class of the type returned by the conversion function) and
2957 // let the user-defined conversion step handle the conversion.
2958 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
2959 return;
2960 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002961
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002962 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
2963
2964 // If the conversion following the call to the conversion function
2965 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00002966 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2967 Best->FinalConversion.Third) {
2968 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002969 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002970 ICS.Standard = Best->FinalConversion;
2971 Sequence.AddConversionSequenceStep(ICS, DestType);
2972 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002973}
2974
John McCall369371c2010-06-04 02:29:22 +00002975bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
2976 const InitializedEntity &Entity,
2977 Expr *Initializer,
2978 bool SuppressUserConversions,
2979 bool AllowExplicitConversions,
2980 bool InOverloadResolution) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002981 ImplicitConversionSequence ICS
John McCall369371c2010-06-04 02:29:22 +00002982 = TryImplicitConversion(Initializer, Entity.getType(),
2983 SuppressUserConversions,
2984 AllowExplicitConversions,
2985 InOverloadResolution);
2986 if (ICS.isBad()) return true;
2987
2988 // Perform the actual conversion.
Douglas Gregord6542d82009-12-22 15:35:07 +00002989 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
John McCall369371c2010-06-04 02:29:22 +00002990 return false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002991}
2992
2993InitializationSequence::InitializationSequence(Sema &S,
2994 const InitializedEntity &Entity,
2995 const InitializationKind &Kind,
2996 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00002997 unsigned NumArgs)
2998 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002999 ASTContext &Context = S.Context;
3000
3001 // C++0x [dcl.init]p16:
3002 // The semantics of initializers are as follows. The destination type is
3003 // the type of the object or reference being initialized and the source
3004 // type is the type of the initializer expression. The source type is not
3005 // defined when the initializer is a braced-init-list or when it is a
3006 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003007 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003008
3009 if (DestType->isDependentType() ||
3010 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3011 SequenceKind = DependentSequence;
3012 return;
3013 }
3014
3015 QualType SourceType;
3016 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003017 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003018 Initializer = Args[0];
3019 if (!isa<InitListExpr>(Initializer))
3020 SourceType = Initializer->getType();
3021 }
3022
3023 // - If the initializer is a braced-init-list, the object is
3024 // list-initialized (8.5.4).
3025 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3026 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003027 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003028 }
3029
3030 // - If the destination type is a reference type, see 8.5.3.
3031 if (DestType->isReferenceType()) {
3032 // C++0x [dcl.init.ref]p1:
3033 // A variable declared to be a T& or T&&, that is, "reference to type T"
3034 // (8.3.2), shall be initialized by an object, or function, of type T or
3035 // by an object that can be converted into a T.
3036 // (Therefore, multiple arguments are not permitted.)
3037 if (NumArgs != 1)
3038 SetFailed(FK_TooManyInitsForReference);
3039 else
3040 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3041 return;
3042 }
3043
3044 // - If the destination type is an array of characters, an array of
3045 // char16_t, an array of char32_t, or an array of wchar_t, and the
3046 // initializer is a string literal, see 8.5.2.
3047 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3048 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3049 return;
3050 }
3051
3052 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003053 if (Kind.getKind() == InitializationKind::IK_Value ||
3054 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003055 TryValueInitialization(S, Entity, Kind, *this);
3056 return;
3057 }
3058
Douglas Gregor99a2e602009-12-16 01:38:02 +00003059 // Handle default initialization.
3060 if (Kind.getKind() == InitializationKind::IK_Default){
3061 TryDefaultInitialization(S, Entity, Kind, *this);
3062 return;
3063 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003064
Douglas Gregor20093b42009-12-09 23:02:17 +00003065 // - Otherwise, if the destination type is an array, the program is
3066 // ill-formed.
3067 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3068 if (AT->getElementType()->isAnyCharacterType())
3069 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3070 else
3071 SetFailed(FK_ArrayNeedsInitList);
3072
3073 return;
3074 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003075
3076 // Handle initialization in C
3077 if (!S.getLangOptions().CPlusPlus) {
3078 setSequenceKind(CAssignment);
3079 AddCAssignmentStep(DestType);
3080 return;
3081 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003082
3083 // - If the destination type is a (possibly cv-qualified) class type:
3084 if (DestType->isRecordType()) {
3085 // - If the initialization is direct-initialization, or if it is
3086 // copy-initialization where the cv-unqualified version of the
3087 // source type is the same class as, or a derived class of, the
3088 // class of the destination, constructors are considered. [...]
3089 if (Kind.getKind() == InitializationKind::IK_Direct ||
3090 (Kind.getKind() == InitializationKind::IK_Copy &&
3091 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3092 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003093 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003094 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003095 // - Otherwise (i.e., for the remaining copy-initialization cases),
3096 // user-defined conversion sequences that can convert from the source
3097 // type to the destination type or (when a conversion function is
3098 // used) to a derived class thereof are enumerated as described in
3099 // 13.3.1.4, and the best one is chosen through overload resolution
3100 // (13.3).
3101 else
3102 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3103 return;
3104 }
3105
Douglas Gregor99a2e602009-12-16 01:38:02 +00003106 if (NumArgs > 1) {
3107 SetFailed(FK_TooManyInitsForScalar);
3108 return;
3109 }
3110 assert(NumArgs == 1 && "Zero-argument case handled above");
3111
Douglas Gregor20093b42009-12-09 23:02:17 +00003112 // - Otherwise, if the source type is a (possibly cv-qualified) class
3113 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003114 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003115 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3116 return;
3117 }
3118
3119 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003120 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003121 // conversions (Clause 4) will be used, if necessary, to convert the
3122 // initializer expression to the cv-unqualified version of the
3123 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003124 if (S.TryImplicitConversion(*this, Entity, Initializer,
3125 /*SuppressUserConversions*/ true,
3126 /*AllowExplicitConversions*/ false,
3127 /*InOverloadResolution*/ false))
3128 SetFailed(InitializationSequence::FK_ConversionFailed);
3129 else
3130 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003131}
3132
3133InitializationSequence::~InitializationSequence() {
3134 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3135 StepEnd = Steps.end();
3136 Step != StepEnd; ++Step)
3137 Step->Destroy();
3138}
3139
3140//===----------------------------------------------------------------------===//
3141// Perform initialization
3142//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003143static Sema::AssignmentAction
3144getAssignmentAction(const InitializedEntity &Entity) {
3145 switch(Entity.getKind()) {
3146 case InitializedEntity::EK_Variable:
3147 case InitializedEntity::EK_New:
3148 return Sema::AA_Initializing;
3149
3150 case InitializedEntity::EK_Parameter:
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003151 if (Entity.getDecl() &&
3152 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3153 return Sema::AA_Sending;
3154
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003155 return Sema::AA_Passing;
3156
3157 case InitializedEntity::EK_Result:
3158 return Sema::AA_Returning;
3159
3160 case InitializedEntity::EK_Exception:
3161 case InitializedEntity::EK_Base:
3162 llvm_unreachable("No assignment action for C++-specific initialization");
3163 break;
3164
3165 case InitializedEntity::EK_Temporary:
3166 // FIXME: Can we tell apart casting vs. converting?
3167 return Sema::AA_Casting;
3168
3169 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003170 case InitializedEntity::EK_ArrayElement:
3171 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003172 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003173 return Sema::AA_Initializing;
3174 }
3175
3176 return Sema::AA_Converting;
3177}
3178
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003179/// \brief Whether we should binding a created object as a temporary when
3180/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003181static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003182 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003183 case InitializedEntity::EK_ArrayElement:
3184 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003185 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003186 case InitializedEntity::EK_New:
3187 case InitializedEntity::EK_Variable:
3188 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003189 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003190 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003191 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003192 return false;
3193
3194 case InitializedEntity::EK_Parameter:
3195 case InitializedEntity::EK_Temporary:
3196 return true;
3197 }
3198
3199 llvm_unreachable("missed an InitializedEntity kind?");
3200}
3201
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003202/// \brief Whether the given entity, when initialized with an object
3203/// created for that initialization, requires destruction.
3204static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3205 switch (Entity.getKind()) {
3206 case InitializedEntity::EK_Member:
3207 case InitializedEntity::EK_Result:
3208 case InitializedEntity::EK_New:
3209 case InitializedEntity::EK_Base:
3210 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003211 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003212 return false;
3213
3214 case InitializedEntity::EK_Variable:
3215 case InitializedEntity::EK_Parameter:
3216 case InitializedEntity::EK_Temporary:
3217 case InitializedEntity::EK_ArrayElement:
3218 case InitializedEntity::EK_Exception:
3219 return true;
3220 }
3221
3222 llvm_unreachable("missed an InitializedEntity kind?");
3223}
3224
Douglas Gregor523d46a2010-04-18 07:40:54 +00003225/// \brief Make a (potentially elidable) temporary copy of the object
3226/// provided by the given initializer by calling the appropriate copy
3227/// constructor.
3228///
3229/// \param S The Sema object used for type-checking.
3230///
3231/// \param T The type of the temporary object, which must either by
3232/// the type of the initializer expression or a superclass thereof.
3233///
3234/// \param Enter The entity being initialized.
3235///
3236/// \param CurInit The initializer expression.
3237///
3238/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3239/// is permitted in C++03 (but not C++0x) when binding a reference to
3240/// an rvalue.
3241///
3242/// \returns An expression that copies the initializer expression into
3243/// a temporary object, or an error expression if a copy could not be
3244/// created.
Douglas Gregor2f599792010-04-02 18:24:57 +00003245static Sema::OwningExprResult CopyObject(Sema &S,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003246 QualType T,
Douglas Gregor2f599792010-04-02 18:24:57 +00003247 const InitializedEntity &Entity,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003248 Sema::OwningExprResult CurInit,
3249 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003250 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003251 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003252 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003253 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003254 Class = cast<CXXRecordDecl>(Record->getDecl());
3255 if (!Class)
3256 return move(CurInit);
3257
3258 // C++0x [class.copy]p34:
3259 // When certain criteria are met, an implementation is allowed to
3260 // omit the copy/move construction of a class object, even if the
3261 // copy/move constructor and/or destructor for the object have
3262 // side effects. [...]
3263 // - when a temporary class object that has not been bound to a
3264 // reference (12.2) would be copied/moved to a class object
3265 // with the same cv-unqualified type, the copy/move operation
3266 // can be omitted by constructing the temporary object
3267 // directly into the target of the omitted copy/move
3268 //
3269 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003270 // elision for return statements and throw expressions are handled as part
3271 // of constructor initialization, while copy elision for exception handlers
3272 // is handled by the run-time.
Douglas Gregor2f599792010-04-02 18:24:57 +00003273 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregor523d46a2010-04-18 07:40:54 +00003274 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003275 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003276 switch (Entity.getKind()) {
3277 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003278 Loc = Entity.getReturnLoc();
3279 break;
3280
3281 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003282 Loc = Entity.getThrowLoc();
3283 break;
3284
3285 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003286 Loc = Entity.getDecl()->getLocation();
3287 break;
3288
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003289 case InitializedEntity::EK_ArrayElement:
3290 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003291 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003292 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003293 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003294 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003295 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003296 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003297 Loc = CurInitExpr->getLocStart();
3298 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003299 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003300
3301 // Make sure that the type we are copying is complete.
3302 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3303 return move(CurInit);
3304
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003305 // Perform overload resolution using the class's copy constructors.
3306 DeclarationName ConstructorName
3307 = S.Context.DeclarationNames.getCXXConstructorName(
3308 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3309 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003310 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003311 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3312 Con != ConEnd; ++Con) {
Douglas Gregor2f599792010-04-02 18:24:57 +00003313 // Only consider copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003314 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3315 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor153b3ba2010-04-18 02:16:12 +00003316 !Constructor->isCopyConstructor() ||
3317 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003318 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003319
3320 DeclAccessPair FoundDecl
3321 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3322 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003323 &CurInitExpr, 1, CandidateSet);
Douglas Gregor2f599792010-04-02 18:24:57 +00003324 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003325
3326 OverloadCandidateSet::iterator Best;
3327 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3328 case OR_Success:
3329 break;
3330
3331 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003332 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3333 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3334 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003335 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003336 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003337 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3338 &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003339 if (!IsExtraneousCopy || S.isSFINAEContext())
3340 return S.ExprError();
3341 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003342
3343 case OR_Ambiguous:
3344 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003345 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003346 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003347 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3348 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003349 return S.ExprError();
3350
3351 case OR_Deleted:
3352 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003353 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003354 << CurInitExpr->getSourceRange();
3355 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3356 << Best->Function->isDeleted();
3357 return S.ExprError();
3358 }
3359
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003360 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3361 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3362 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003363
Anders Carlsson9a68a672010-04-21 18:47:17 +00003364 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003365 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003366
3367 if (IsExtraneousCopy) {
3368 // If this is a totally extraneous copy for C++03 reference
3369 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003370 // expression. We don't generate an (elided) copy operation here
3371 // because doing so would require us to pass down a flag to avoid
3372 // infinite recursion, where each step adds another extraneous,
3373 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003374
Douglas Gregor2559a702010-04-18 07:57:34 +00003375 // Instantiate the default arguments of any extra parameters in
3376 // the selected copy constructor, as if we were going to create a
3377 // proper call to the copy constructor.
3378 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3379 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3380 if (S.RequireCompleteType(Loc, Parm->getType(),
3381 S.PDiag(diag::err_call_incomplete_argument)))
3382 break;
3383
3384 // Build the default argument expression; we don't actually care
3385 // if this succeeds or not, because this routine will complain
3386 // if there was a problem.
3387 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3388 }
3389
Douglas Gregor523d46a2010-04-18 07:40:54 +00003390 return S.Owned(CurInitExpr);
3391 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003392
3393 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003394 // constructor call (we might have derived-to-base conversions, or
3395 // the copy constructor may have default arguments).
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003396 if (S.CompleteConstructorCall(Constructor,
3397 Sema::MultiExprArg(S,
3398 (void **)&CurInitExpr,
3399 1),
3400 Loc, ConstructorArgs))
3401 return S.ExprError();
3402
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003403 // Actually perform the constructor call.
3404 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
3405 move_arg(ConstructorArgs));
3406
3407 // If we're supposed to bind temporaries, do so.
3408 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3409 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3410 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003411}
Douglas Gregor20093b42009-12-09 23:02:17 +00003412
Douglas Gregora41a8c52010-04-22 00:20:18 +00003413void InitializationSequence::PrintInitLocationNote(Sema &S,
3414 const InitializedEntity &Entity) {
3415 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3416 if (Entity.getDecl()->getLocation().isInvalid())
3417 return;
3418
3419 if (Entity.getDecl()->getDeclName())
3420 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3421 << Entity.getDecl()->getDeclName();
3422 else
3423 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3424 }
3425}
3426
Douglas Gregor20093b42009-12-09 23:02:17 +00003427Action::OwningExprResult
3428InitializationSequence::Perform(Sema &S,
3429 const InitializedEntity &Entity,
3430 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003431 Action::MultiExprArg Args,
3432 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003433 if (SequenceKind == FailedSequence) {
3434 unsigned NumArgs = Args.size();
3435 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3436 return S.ExprError();
3437 }
3438
3439 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003440 // If the declaration is a non-dependent, incomplete array type
3441 // that has an initializer, then its type will be completed once
3442 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003443 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003444 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003445 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003446 if (const IncompleteArrayType *ArrayT
3447 = S.Context.getAsIncompleteArrayType(DeclType)) {
3448 // FIXME: We don't currently have the ability to accurately
3449 // compute the length of an initializer list without
3450 // performing full type-checking of the initializer list
3451 // (since we have to determine where braces are implicitly
3452 // introduced and such). So, we fall back to making the array
3453 // type a dependently-sized array type with no specified
3454 // bound.
3455 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3456 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003457
Douglas Gregord87b61f2009-12-10 17:56:55 +00003458 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003459 if (DeclaratorDecl *DD = Entity.getDecl()) {
3460 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3461 TypeLoc TL = TInfo->getTypeLoc();
3462 if (IncompleteArrayTypeLoc *ArrayLoc
3463 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3464 Brackets = ArrayLoc->getBracketsRange();
3465 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003466 }
3467
3468 *ResultType
3469 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3470 /*NumElts=*/0,
3471 ArrayT->getSizeModifier(),
3472 ArrayT->getIndexTypeCVRQualifiers(),
3473 Brackets);
3474 }
3475
3476 }
3477 }
3478
Eli Friedman08544622009-12-22 02:35:53 +00003479 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003480 return Sema::OwningExprResult(S, Args.release()[0]);
3481
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003482 if (Args.size() == 0)
3483 return S.Owned((Expr *)0);
3484
Douglas Gregor20093b42009-12-09 23:02:17 +00003485 unsigned NumArgs = Args.size();
3486 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3487 SourceLocation(),
3488 (Expr **)Args.release(),
3489 NumArgs,
3490 SourceLocation()));
3491 }
3492
Douglas Gregor99a2e602009-12-16 01:38:02 +00003493 if (SequenceKind == NoInitialization)
3494 return S.Owned((Expr *)0);
3495
Douglas Gregord6542d82009-12-22 15:35:07 +00003496 QualType DestType = Entity.getType().getNonReferenceType();
3497 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003498 // the same as Entity.getDecl()->getType() in cases involving type merging,
3499 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003500 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003501 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003502 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003503
Douglas Gregor99a2e602009-12-16 01:38:02 +00003504 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3505
3506 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3507
3508 // For initialization steps that start with a single initializer,
3509 // grab the only argument out the Args and place it into the "current"
3510 // initializer.
3511 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003512 case SK_ResolveAddressOfOverloadedFunction:
3513 case SK_CastDerivedToBaseRValue:
3514 case SK_CastDerivedToBaseLValue:
3515 case SK_BindReference:
3516 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003517 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003518 case SK_UserConversion:
3519 case SK_QualificationConversionLValue:
3520 case SK_QualificationConversionRValue:
3521 case SK_ConversionSequence:
3522 case SK_ListInitialization:
3523 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003524 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003525 assert(Args.size() == 1);
3526 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3527 if (CurInit.isInvalid())
3528 return S.ExprError();
3529 break;
3530
3531 case SK_ConstructorInitialization:
3532 case SK_ZeroInitialization:
3533 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003534 }
3535
3536 // Walk through the computed steps for the initialization sequence,
3537 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003538 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 for (step_iterator Step = step_begin(), StepEnd = step_end();
3540 Step != StepEnd; ++Step) {
3541 if (CurInit.isInvalid())
3542 return S.ExprError();
3543
3544 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003545 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003546
3547 switch (Step->Kind) {
3548 case SK_ResolveAddressOfOverloadedFunction:
3549 // Overload resolution determined which function invoke; update the
3550 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003551 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003552 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003553 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003554 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003555 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003556 break;
3557
3558 case SK_CastDerivedToBaseRValue:
3559 case SK_CastDerivedToBaseLValue: {
3560 // We have a derived-to-base cast that produces either an rvalue or an
3561 // lvalue. Perform that cast.
3562
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003563 CXXBaseSpecifierArray BasePath;
3564
Douglas Gregor20093b42009-12-09 23:02:17 +00003565 // Casts to inaccessible base classes are allowed with C-style casts.
3566 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3567 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3568 CurInitExpr->getLocStart(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003569 CurInitExpr->getSourceRange(),
3570 &BasePath, IgnoreBaseAccess))
Douglas Gregor20093b42009-12-09 23:02:17 +00003571 return S.ExprError();
3572
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003573 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3574 QualType T = SourceType;
3575 if (const PointerType *Pointer = T->getAs<PointerType>())
3576 T = Pointer->getPointeeType();
3577 if (const RecordType *RecordTy = T->getAs<RecordType>())
3578 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3579 cast<CXXRecordDecl>(RecordTy->getDecl()));
3580 }
3581
Douglas Gregor20093b42009-12-09 23:02:17 +00003582 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3583 CastExpr::CK_DerivedToBase,
Anders Carlsson88465d32010-04-23 22:18:37 +00003584 (Expr*)CurInit.release(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003585 BasePath,
Douglas Gregor20093b42009-12-09 23:02:17 +00003586 Step->Kind == SK_CastDerivedToBaseLValue));
3587 break;
3588 }
3589
3590 case SK_BindReference:
3591 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3592 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3593 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003594 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003595 << BitField->getDeclName()
3596 << CurInitExpr->getSourceRange();
3597 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3598 return S.ExprError();
3599 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003600
Anders Carlsson09380262010-01-31 17:18:49 +00003601 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003602 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003603 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3604 << Entity.getType().isVolatileQualified()
3605 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003606 PrintInitLocationNote(S, Entity);
Anders Carlsson09380262010-01-31 17:18:49 +00003607 return S.ExprError();
3608 }
3609
Douglas Gregor20093b42009-12-09 23:02:17 +00003610 // Reference binding does not have any corresponding ASTs.
3611
3612 // Check exception specifications
3613 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3614 return S.ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003615
Douglas Gregor20093b42009-12-09 23:02:17 +00003616 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003617
Douglas Gregor20093b42009-12-09 23:02:17 +00003618 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003619 // Reference binding does not have any corresponding ASTs.
3620
Douglas Gregor20093b42009-12-09 23:02:17 +00003621 // Check exception specifications
3622 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3623 return S.ExprError();
3624
Douglas Gregor20093b42009-12-09 23:02:17 +00003625 break;
3626
Douglas Gregor523d46a2010-04-18 07:40:54 +00003627 case SK_ExtraneousCopyToTemporary:
3628 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3629 /*IsExtraneousCopy=*/true);
3630 break;
3631
Douglas Gregor20093b42009-12-09 23:02:17 +00003632 case SK_UserConversion: {
3633 // We have a user-defined conversion that invokes either a constructor
3634 // or a conversion function.
3635 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003636 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003637 FunctionDecl *Fn = Step->Function.Function;
3638 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003639 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003640 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003641 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003642 // Build a call to the selected constructor.
3643 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3644 SourceLocation Loc = CurInitExpr->getLocStart();
3645 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003646
Douglas Gregor20093b42009-12-09 23:02:17 +00003647 // Determine the arguments required to actually perform the constructor
3648 // call.
3649 if (S.CompleteConstructorCall(Constructor,
3650 Sema::MultiExprArg(S,
3651 (void **)&CurInitExpr,
3652 1),
3653 Loc, ConstructorArgs))
3654 return S.ExprError();
3655
3656 // Build the an expression that constructs a temporary.
3657 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3658 move_arg(ConstructorArgs));
3659 if (CurInit.isInvalid())
3660 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003661
Anders Carlsson9a68a672010-04-21 18:47:17 +00003662 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003663 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003664 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor20093b42009-12-09 23:02:17 +00003665
3666 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003667 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3668 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3669 S.IsDerivedFrom(SourceType, Class))
3670 IsCopy = true;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003671
3672 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003673 } else {
3674 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003675 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003676 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003677 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003678 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003679 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003680
Douglas Gregor20093b42009-12-09 23:02:17 +00003681 // FIXME: Should we move this initialization into a separate
3682 // derived-to-base conversion? I believe the answer is "no", because
3683 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003684 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003685 FoundFn, Conversion))
Douglas Gregor20093b42009-12-09 23:02:17 +00003686 return S.ExprError();
3687
3688 // Do a little dance to make sure that CurInit has the proper
3689 // pointer.
3690 CurInit.release();
3691
3692 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003693 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3694 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003695 if (CurInit.isInvalid() || !CurInit.get())
3696 return S.ExprError();
3697
3698 CastKind = CastExpr::CK_UserDefinedConversion;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003699
3700 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003701 }
3702
Douglas Gregor2f599792010-04-02 18:24:57 +00003703 bool RequiresCopy = !IsCopy &&
3704 getKind() != InitializationSequence::ReferenceBinding;
3705 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003706 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003707 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3708 CurInitExpr = static_cast<Expr *>(CurInit.get());
3709 QualType T = CurInitExpr->getType();
3710 if (const RecordType *Record = T->getAs<RecordType>()) {
3711 CXXDestructorDecl *Destructor
Douglas Gregor1d110e02010-07-01 14:13:13 +00003712 = cast<CXXRecordDecl>(Record->getDecl())->getDestructor();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003713 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3714 S.PDiag(diag::err_access_dtor_temp) << T);
3715 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3716 }
3717 }
3718
Douglas Gregor20093b42009-12-09 23:02:17 +00003719 CurInitExpr = CurInit.takeAs<Expr>();
3720 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003721 CastKind,
3722 CurInitExpr,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003723 CXXBaseSpecifierArray(),
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003724 IsLvalue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003725
Douglas Gregor2f599792010-04-02 18:24:57 +00003726 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003727 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3728 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003729
Douglas Gregor20093b42009-12-09 23:02:17 +00003730 break;
3731 }
3732
3733 case SK_QualificationConversionLValue:
3734 case SK_QualificationConversionRValue:
3735 // Perform a qualification conversion; these can never go wrong.
3736 S.ImpCastExprToType(CurInitExpr, Step->Type,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003737 CastExpr::CK_NoOp,
Douglas Gregor20093b42009-12-09 23:02:17 +00003738 Step->Kind == SK_QualificationConversionLValue);
3739 CurInit.release();
3740 CurInit = S.Owned(CurInitExpr);
3741 break;
3742
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003743 case SK_ConversionSequence: {
3744 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3745
3746 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3747 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor20093b42009-12-09 23:02:17 +00003748 return S.ExprError();
3749
3750 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003751 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003752 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003753 }
3754
Douglas Gregord87b61f2009-12-10 17:56:55 +00003755 case SK_ListInitialization: {
3756 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3757 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003758 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003759 return S.ExprError();
3760
3761 CurInit.release();
3762 CurInit = S.Owned(InitList);
3763 break;
3764 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003765
3766 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003767 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003768 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003769 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003770
Douglas Gregor51c56d62009-12-14 20:49:26 +00003771 // Build a call to the selected constructor.
3772 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3773 SourceLocation Loc = Kind.getLocation();
3774
3775 // Determine the arguments required to actually perform the constructor
3776 // call.
3777 if (S.CompleteConstructorCall(Constructor, move(Args),
3778 Loc, ConstructorArgs))
3779 return S.ExprError();
3780
Douglas Gregord6e44a32010-04-16 22:09:46 +00003781 // Build the expression that constructs a temporary.
Douglas Gregor91be6f52010-03-02 17:18:33 +00003782 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003783 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003784 (Kind.getKind() == InitializationKind::IK_Direct ||
3785 Kind.getKind() == InitializationKind::IK_Value)) {
3786 // An explicitly-constructed temporary, e.g., X(1, 2).
3787 unsigned NumExprs = ConstructorArgs.size();
3788 Expr **Exprs = (Expr **)ConstructorArgs.take();
3789 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3790 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3791 Constructor,
3792 Entity.getType(),
3793 Kind.getLocation(),
3794 Exprs,
3795 NumExprs,
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003796 Kind.getParenRange().getEnd(),
3797 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003798 } else {
3799 CXXConstructExpr::ConstructionKind ConstructKind =
3800 CXXConstructExpr::CK_Complete;
3801
3802 if (Entity.getKind() == InitializedEntity::EK_Base) {
3803 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3804 CXXConstructExpr::CK_VirtualBase :
3805 CXXConstructExpr::CK_NonVirtualBase;
3806 }
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003807
3808 // If the entity allows NRVO, mark the construction as elidable
3809 // unconditionally.
3810 if (Entity.allowsNRVO())
3811 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3812 Constructor, /*Elidable=*/true,
3813 move_arg(ConstructorArgs),
3814 ConstructorInitRequiresZeroInit,
3815 ConstructKind);
3816 else
3817 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3818 Constructor,
3819 move_arg(ConstructorArgs),
3820 ConstructorInitRequiresZeroInit,
3821 ConstructKind);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003822 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003823 if (CurInit.isInvalid())
3824 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003825
3826 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00003827 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003828 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003829 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003830
Douglas Gregor2f599792010-04-02 18:24:57 +00003831 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003832 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003833
Douglas Gregor51c56d62009-12-14 20:49:26 +00003834 break;
3835 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003836
3837 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003838 step_iterator NextStep = Step;
3839 ++NextStep;
3840 if (NextStep != StepEnd &&
3841 NextStep->Kind == SK_ConstructorInitialization) {
3842 // The need for zero-initialization is recorded directly into
3843 // the call to the object's constructor within the next step.
3844 ConstructorInitRequiresZeroInit = true;
3845 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3846 S.getLangOptions().CPlusPlus &&
3847 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003848 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3849 Kind.getRange().getBegin(),
3850 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003851 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003852 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003853 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003854 break;
3855 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003856
3857 case SK_CAssignment: {
3858 QualType SourceType = CurInitExpr->getType();
3859 Sema::AssignConvertType ConvTy =
3860 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003861
3862 // If this is a call, allow conversion to a transparent union.
3863 if (ConvTy != Sema::Compatible &&
3864 Entity.getKind() == InitializedEntity::EK_Parameter &&
3865 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3866 == Sema::Compatible)
3867 ConvTy = Sema::Compatible;
3868
Douglas Gregora41a8c52010-04-22 00:20:18 +00003869 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003870 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3871 Step->Type, SourceType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00003872 CurInitExpr,
3873 getAssignmentAction(Entity),
3874 &Complained)) {
3875 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003876 return S.ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003877 } else if (Complained)
3878 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003879
3880 CurInit.release();
3881 CurInit = S.Owned(CurInitExpr);
3882 break;
3883 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003884
3885 case SK_StringInit: {
3886 QualType Ty = Step->Type;
3887 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3888 break;
3889 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003890 }
3891 }
3892
3893 return move(CurInit);
3894}
3895
3896//===----------------------------------------------------------------------===//
3897// Diagnose initialization failures
3898//===----------------------------------------------------------------------===//
3899bool InitializationSequence::Diagnose(Sema &S,
3900 const InitializedEntity &Entity,
3901 const InitializationKind &Kind,
3902 Expr **Args, unsigned NumArgs) {
3903 if (SequenceKind != FailedSequence)
3904 return false;
3905
Douglas Gregord6542d82009-12-22 15:35:07 +00003906 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003907 switch (Failure) {
3908 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003909 // FIXME: Customize for the initialized entity?
3910 if (NumArgs == 0)
3911 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3912 << DestType.getNonReferenceType();
3913 else // FIXME: diagnostic below could be better!
3914 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3915 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003916 break;
3917
3918 case FK_ArrayNeedsInitList:
3919 case FK_ArrayNeedsInitListOrStringLiteral:
3920 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3921 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3922 break;
3923
John McCall6bb80172010-03-30 21:47:33 +00003924 case FK_AddressOfOverloadFailed: {
3925 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00003926 S.ResolveAddressOfOverloadedFunction(Args[0],
3927 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00003928 true,
3929 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00003930 break;
John McCall6bb80172010-03-30 21:47:33 +00003931 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003932
3933 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003934 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003935 switch (FailedOverloadResult) {
3936 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003937 if (Failure == FK_UserConversionOverloadFailed)
3938 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3939 << Args[0]->getType() << DestType
3940 << Args[0]->getSourceRange();
3941 else
3942 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3943 << DestType << Args[0]->getType()
3944 << Args[0]->getSourceRange();
3945
John McCallcbce6062010-01-12 07:18:19 +00003946 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3947 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003948 break;
3949
3950 case OR_No_Viable_Function:
3951 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3952 << Args[0]->getType() << DestType.getNonReferenceType()
3953 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003954 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3955 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003956 break;
3957
3958 case OR_Deleted: {
3959 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3960 << Args[0]->getType() << DestType.getNonReferenceType()
3961 << Args[0]->getSourceRange();
3962 OverloadCandidateSet::iterator Best;
3963 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3964 Kind.getLocation(),
3965 Best);
3966 if (Ovl == OR_Deleted) {
3967 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3968 << Best->Function->isDeleted();
3969 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003970 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003971 }
3972 break;
3973 }
3974
3975 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003976 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003977 break;
3978 }
3979 break;
3980
3981 case FK_NonConstLValueReferenceBindingToTemporary:
3982 case FK_NonConstLValueReferenceBindingToUnrelated:
3983 S.Diag(Kind.getLocation(),
3984 Failure == FK_NonConstLValueReferenceBindingToTemporary
3985 ? diag::err_lvalue_reference_bind_to_temporary
3986 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00003987 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003988 << DestType.getNonReferenceType()
3989 << Args[0]->getType()
3990 << Args[0]->getSourceRange();
3991 break;
3992
3993 case FK_RValueReferenceBindingToLValue:
3994 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3995 << Args[0]->getSourceRange();
3996 break;
3997
3998 case FK_ReferenceInitDropsQualifiers:
3999 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4000 << DestType.getNonReferenceType()
4001 << Args[0]->getType()
4002 << Args[0]->getSourceRange();
4003 break;
4004
4005 case FK_ReferenceInitFailed:
4006 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4007 << DestType.getNonReferenceType()
4008 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4009 << Args[0]->getType()
4010 << Args[0]->getSourceRange();
4011 break;
4012
4013 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004014 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4015 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004016 << DestType
4017 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4018 << Args[0]->getType()
4019 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004020 break;
4021
4022 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004023 SourceRange R;
4024
4025 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4026 R = SourceRange(InitList->getInit(1)->getLocStart(),
4027 InitList->getLocEnd());
4028 else
4029 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004030
4031 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00004032 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004033 break;
4034 }
4035
4036 case FK_ReferenceBindingToInitList:
4037 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4038 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4039 break;
4040
4041 case FK_InitListBadDestinationType:
4042 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4043 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4044 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00004045
4046 case FK_ConstructorOverloadFailed: {
4047 SourceRange ArgsRange;
4048 if (NumArgs)
4049 ArgsRange = SourceRange(Args[0]->getLocStart(),
4050 Args[NumArgs - 1]->getLocEnd());
4051
4052 // FIXME: Using "DestType" for the entity we're printing is probably
4053 // bad.
4054 switch (FailedOverloadResult) {
4055 case OR_Ambiguous:
4056 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4057 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00004058 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00004059 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004060 break;
4061
4062 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004063 if (Kind.getKind() == InitializationKind::IK_Default &&
4064 (Entity.getKind() == InitializedEntity::EK_Base ||
4065 Entity.getKind() == InitializedEntity::EK_Member) &&
4066 isa<CXXConstructorDecl>(S.CurContext)) {
4067 // This is implicit default initialization of a member or
4068 // base within a constructor. If no viable function was
4069 // found, notify the user that she needs to explicitly
4070 // initialize this base/member.
4071 CXXConstructorDecl *Constructor
4072 = cast<CXXConstructorDecl>(S.CurContext);
4073 if (Entity.getKind() == InitializedEntity::EK_Base) {
4074 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4075 << Constructor->isImplicit()
4076 << S.Context.getTypeDeclType(Constructor->getParent())
4077 << /*base=*/0
4078 << Entity.getType();
4079
4080 RecordDecl *BaseDecl
4081 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4082 ->getDecl();
4083 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4084 << S.Context.getTagDeclType(BaseDecl);
4085 } else {
4086 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4087 << Constructor->isImplicit()
4088 << S.Context.getTypeDeclType(Constructor->getParent())
4089 << /*member=*/1
4090 << Entity.getName();
4091 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4092
4093 if (const RecordType *Record
4094 = Entity.getType()->getAs<RecordType>())
4095 S.Diag(Record->getDecl()->getLocation(),
4096 diag::note_previous_decl)
4097 << S.Context.getTagDeclType(Record->getDecl());
4098 }
4099 break;
4100 }
4101
Douglas Gregor51c56d62009-12-14 20:49:26 +00004102 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4103 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00004104 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4105 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004106 break;
4107
4108 case OR_Deleted: {
4109 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4110 << true << DestType << ArgsRange;
4111 OverloadCandidateSet::iterator Best;
4112 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4113 Kind.getLocation(),
4114 Best);
4115 if (Ovl == OR_Deleted) {
4116 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4117 << Best->Function->isDeleted();
4118 } else {
4119 llvm_unreachable("Inconsistent overload resolution?");
4120 }
4121 break;
4122 }
4123
4124 case OR_Success:
4125 llvm_unreachable("Conversion did not fail!");
4126 break;
4127 }
4128 break;
4129 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004130
4131 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004132 if (Entity.getKind() == InitializedEntity::EK_Member &&
4133 isa<CXXConstructorDecl>(S.CurContext)) {
4134 // This is implicit default-initialization of a const member in
4135 // a constructor. Complain that it needs to be explicitly
4136 // initialized.
4137 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4138 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4139 << Constructor->isImplicit()
4140 << S.Context.getTypeDeclType(Constructor->getParent())
4141 << /*const=*/1
4142 << Entity.getName();
4143 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4144 << Entity.getName();
4145 } else {
4146 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4147 << DestType << (bool)DestType->getAs<RecordType>();
4148 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004149 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004150
4151 case FK_Incomplete:
4152 S.RequireCompleteType(Kind.getLocation(), DestType,
4153 diag::err_init_incomplete_type);
4154 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004155 }
4156
Douglas Gregora41a8c52010-04-22 00:20:18 +00004157 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004158 return true;
4159}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004160
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004161void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4162 switch (SequenceKind) {
4163 case FailedSequence: {
4164 OS << "Failed sequence: ";
4165 switch (Failure) {
4166 case FK_TooManyInitsForReference:
4167 OS << "too many initializers for reference";
4168 break;
4169
4170 case FK_ArrayNeedsInitList:
4171 OS << "array requires initializer list";
4172 break;
4173
4174 case FK_ArrayNeedsInitListOrStringLiteral:
4175 OS << "array requires initializer list or string literal";
4176 break;
4177
4178 case FK_AddressOfOverloadFailed:
4179 OS << "address of overloaded function failed";
4180 break;
4181
4182 case FK_ReferenceInitOverloadFailed:
4183 OS << "overload resolution for reference initialization failed";
4184 break;
4185
4186 case FK_NonConstLValueReferenceBindingToTemporary:
4187 OS << "non-const lvalue reference bound to temporary";
4188 break;
4189
4190 case FK_NonConstLValueReferenceBindingToUnrelated:
4191 OS << "non-const lvalue reference bound to unrelated type";
4192 break;
4193
4194 case FK_RValueReferenceBindingToLValue:
4195 OS << "rvalue reference bound to an lvalue";
4196 break;
4197
4198 case FK_ReferenceInitDropsQualifiers:
4199 OS << "reference initialization drops qualifiers";
4200 break;
4201
4202 case FK_ReferenceInitFailed:
4203 OS << "reference initialization failed";
4204 break;
4205
4206 case FK_ConversionFailed:
4207 OS << "conversion failed";
4208 break;
4209
4210 case FK_TooManyInitsForScalar:
4211 OS << "too many initializers for scalar";
4212 break;
4213
4214 case FK_ReferenceBindingToInitList:
4215 OS << "referencing binding to initializer list";
4216 break;
4217
4218 case FK_InitListBadDestinationType:
4219 OS << "initializer list for non-aggregate, non-scalar type";
4220 break;
4221
4222 case FK_UserConversionOverloadFailed:
4223 OS << "overloading failed for user-defined conversion";
4224 break;
4225
4226 case FK_ConstructorOverloadFailed:
4227 OS << "constructor overloading failed";
4228 break;
4229
4230 case FK_DefaultInitOfConst:
4231 OS << "default initialization of a const variable";
4232 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004233
4234 case FK_Incomplete:
4235 OS << "initialization of incomplete type";
4236 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004237 }
4238 OS << '\n';
4239 return;
4240 }
4241
4242 case DependentSequence:
4243 OS << "Dependent sequence: ";
4244 return;
4245
4246 case UserDefinedConversion:
4247 OS << "User-defined conversion sequence: ";
4248 break;
4249
4250 case ConstructorInitialization:
4251 OS << "Constructor initialization sequence: ";
4252 break;
4253
4254 case ReferenceBinding:
4255 OS << "Reference binding: ";
4256 break;
4257
4258 case ListInitialization:
4259 OS << "List initialization: ";
4260 break;
4261
4262 case ZeroInitialization:
4263 OS << "Zero initialization\n";
4264 return;
4265
4266 case NoInitialization:
4267 OS << "No initialization\n";
4268 return;
4269
4270 case StandardConversion:
4271 OS << "Standard conversion: ";
4272 break;
4273
4274 case CAssignment:
4275 OS << "C assignment: ";
4276 break;
4277
4278 case StringInit:
4279 OS << "String initialization: ";
4280 break;
4281 }
4282
4283 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4284 if (S != step_begin()) {
4285 OS << " -> ";
4286 }
4287
4288 switch (S->Kind) {
4289 case SK_ResolveAddressOfOverloadedFunction:
4290 OS << "resolve address of overloaded function";
4291 break;
4292
4293 case SK_CastDerivedToBaseRValue:
4294 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4295 break;
4296
4297 case SK_CastDerivedToBaseLValue:
4298 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4299 break;
4300
4301 case SK_BindReference:
4302 OS << "bind reference to lvalue";
4303 break;
4304
4305 case SK_BindReferenceToTemporary:
4306 OS << "bind reference to a temporary";
4307 break;
4308
Douglas Gregor523d46a2010-04-18 07:40:54 +00004309 case SK_ExtraneousCopyToTemporary:
4310 OS << "extraneous C++03 copy to temporary";
4311 break;
4312
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004313 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004314 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004315 break;
4316
4317 case SK_QualificationConversionRValue:
4318 OS << "qualification conversion (rvalue)";
4319
4320 case SK_QualificationConversionLValue:
4321 OS << "qualification conversion (lvalue)";
4322 break;
4323
4324 case SK_ConversionSequence:
4325 OS << "implicit conversion sequence (";
4326 S->ICS->DebugPrint(); // FIXME: use OS
4327 OS << ")";
4328 break;
4329
4330 case SK_ListInitialization:
4331 OS << "list initialization";
4332 break;
4333
4334 case SK_ConstructorInitialization:
4335 OS << "constructor initialization";
4336 break;
4337
4338 case SK_ZeroInitialization:
4339 OS << "zero initialization";
4340 break;
4341
4342 case SK_CAssignment:
4343 OS << "C assignment";
4344 break;
4345
4346 case SK_StringInit:
4347 OS << "string initialization";
4348 break;
4349 }
4350 }
4351}
4352
4353void InitializationSequence::dump() const {
4354 dump(llvm::errs());
4355}
4356
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004357//===----------------------------------------------------------------------===//
4358// Initialization helper functions
4359//===----------------------------------------------------------------------===//
4360Sema::OwningExprResult
4361Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4362 SourceLocation EqualLoc,
4363 OwningExprResult Init) {
4364 if (Init.isInvalid())
4365 return ExprError();
4366
4367 Expr *InitE = (Expr *)Init.get();
4368 assert(InitE && "No initialization expression?");
4369
4370 if (EqualLoc.isInvalid())
4371 EqualLoc = InitE->getLocStart();
4372
4373 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4374 EqualLoc);
4375 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4376 Init.release();
4377 return Seq.Perform(*this, Entity, Kind,
4378 MultiExprArg(*this, (void**)&InitE, 1));
4379}