blob: a746cb7f503ba8daebbfe5b84eba39997afa3399 [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 Kremenekba7bc552010-02-19 01:50:18 +0000284 ILE->updateInit(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 Kremenekba7bc552010-02-19 01:50:18 +0000394 ILE->updateInit(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);
461 else if (T->isStructureType() || T->isUnionType())
462 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()
507 << CodeModificationHint::CreateInsertion(
508 StructuredSubobjectInitList->getLocStart(),
Tanya Lattner47f164e2010-03-07 04:40:06 +0000509 "{")
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000510 << CodeModificationHint::CreateInsertion(
511 SemaRef.PP.getLocForEndOfToken(
Tanya Lattner47f164e2010-03-07 04:40:06 +0000512 StructuredSubobjectInitList->getLocEnd()), "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000513 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000514}
515
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000516void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000517 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000518 unsigned &Index,
519 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000520 unsigned &StructuredIndex,
521 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000522 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000523 SyntacticToSemantic[IList] = StructuredList;
524 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000525 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
526 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor2c792812010-02-09 00:50:06 +0000527 IList->setType(T.getNonReferenceType());
528 StructuredList->setType(T.getNonReferenceType());
Eli Friedman638e1442008-05-25 13:22:35 +0000529 if (hadError)
530 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000531
Eli Friedman638e1442008-05-25 13:22:35 +0000532 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000533 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000534 if (StructuredIndex == 1 &&
535 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000536 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000537 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000538 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000539 hadError = true;
540 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000541 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000542 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000543 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000544 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000545 // Don't complain for incomplete types, since we'll get an error
546 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000547 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000548 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000549 CurrentObjectType->isArrayType()? 0 :
550 CurrentObjectType->isVectorType()? 1 :
551 CurrentObjectType->isScalarType()? 2 :
552 CurrentObjectType->isUnionType()? 3 :
553 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000554
555 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000556 if (SemaRef.getLangOptions().CPlusPlus) {
557 DK = diag::err_excess_initializers;
558 hadError = true;
559 }
Nate Begeman08634522009-07-07 21:53:06 +0000560 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
561 DK = diag::err_excess_initializers;
562 hadError = true;
563 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000564
Chris Lattner08202542009-02-24 22:50:46 +0000565 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000566 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000567 }
568 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000569
Eli Friedman759f2522009-05-16 11:45:48 +0000570 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000571 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000572 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000573 << CodeModificationHint::CreateRemoval(IList->getLocStart())
574 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000575}
576
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000577void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000578 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000579 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000580 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000581 unsigned &Index,
582 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000583 unsigned &StructuredIndex,
584 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000585 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000586 CheckScalarType(Entity, IList, DeclType, Index,
587 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000588 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000589 CheckVectorType(Entity, IList, DeclType, Index,
590 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000591 } else if (DeclType->isAggregateType()) {
592 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000593 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000594 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000596 StructuredList, StructuredIndex,
597 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000598 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000599 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000600 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000601 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000602 CheckArrayType(Entity, IList, DeclType, Zero,
603 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000604 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000605 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000607 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
608 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000609 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000610 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000611 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000612 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000613 } else if (DeclType->isRecordType()) {
614 // C++ [dcl.init]p14:
615 // [...] If the class is an aggregate (8.5.1), and the initializer
616 // is a brace-enclosed list, see 8.5.1.
617 //
618 // Note: 8.5.1 is handled below; here, we diagnose the case where
619 // we have an initializer list and a destination type that is not
620 // an aggregate.
621 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000622 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000623 << DeclType << IList->getSourceRange();
624 hadError = true;
625 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000626 CheckReferenceType(Entity, IList, DeclType, Index,
627 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000628 } else {
629 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000630 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000631 assert(0 && "Unsupported initializer type");
632 }
633}
634
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000635void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000636 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000637 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 unsigned &Index,
639 InitListExpr *StructuredList,
640 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000641 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000642 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
643 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000644 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000645 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000646 = getStructuredSubobjectInit(IList, Index, ElemType,
647 StructuredList, StructuredIndex,
648 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000649 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000650 newStructuredList, newStructuredIndex);
651 ++StructuredIndex;
652 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000653 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
654 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000655 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000656 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000657 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000658 CheckScalarType(Entity, IList, ElemType, Index,
659 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000660 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000661 CheckReferenceType(Entity, IList, ElemType, Index,
662 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000663 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000664 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000665 // C++ [dcl.init.aggr]p12:
666 // All implicit type conversions (clause 4) are considered when
667 // initializing the aggregate member with an ini- tializer from
668 // an initializer-list. If the initializer can initialize a
669 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000670
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000671 // FIXME: Better EqualLoc?
672 InitializationKind Kind =
673 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
674 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
675
676 if (Seq) {
677 Sema::OwningExprResult Result =
678 Seq.Perform(SemaRef, Entity, Kind,
679 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
680 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000681 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000682
683 UpdateStructuredListElement(StructuredList, StructuredIndex,
684 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 ++Index;
686 return;
687 }
688
689 // Fall through for subaggregate initialization
690 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000691 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000692 //
693 // The initializer for a structure or union object that has
694 // automatic storage duration shall be either an initializer
695 // list as described below, or a single expression that has
696 // compatible structure or union type. In the latter case, the
697 // initial value of the object, including unnamed members, is
698 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000699 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000700 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000701 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
702 ++Index;
703 return;
704 }
705
706 // Fall through for subaggregate initialization
707 }
708
709 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000710 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000711 // [...] Otherwise, if the member is itself a non-empty
712 // subaggregate, brace elision is assumed and the initializer is
713 // considered for the initialization of the first member of
714 // the subaggregate.
715 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000716 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000717 StructuredIndex);
718 ++StructuredIndex;
719 } else {
720 // We cannot initialize this element, so let
721 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000722 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
723 SemaRef.Owned(expr));
724 IList->setInit(Index, 0);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000725 hadError = true;
726 ++Index;
727 ++StructuredIndex;
728 }
729 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000730}
731
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000732void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000733 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000734 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000735 InitListExpr *StructuredList,
736 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000737 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000738 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000739 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000740 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000741 diag::err_many_braces_around_scalar_init)
742 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000743 hadError = true;
744 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000745 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000746 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000747 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000748 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000749 diag::err_designator_for_scalar_init)
750 << DeclType << expr->getSourceRange();
751 hadError = true;
752 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000753 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000754 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000755 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000756
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000757 Sema::OwningExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000758 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
759 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000760
Chandler Carruthb5719242010-02-13 07:23:01 +0000761 Expr *ResultExpr = 0;
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000762
763 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000764 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000765 else {
766 ResultExpr = Result.takeAs<Expr>();
767
768 if (ResultExpr != expr) {
769 // The type was promoted, update initializer list.
770 IList->setInit(Index, ResultExpr);
771 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000772 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000773 if (hadError)
774 ++StructuredIndex;
775 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000776 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000777 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000778 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000779 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000780 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000781 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000782 ++Index;
783 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000784 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000785 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000786}
787
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000788void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
789 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000790 unsigned &Index,
791 InitListExpr *StructuredList,
792 unsigned &StructuredIndex) {
793 if (Index < IList->getNumInits()) {
794 Expr *expr = IList->getInit(Index);
795 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000796 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000797 << DeclType << IList->getSourceRange();
798 hadError = true;
799 ++Index;
800 ++StructuredIndex;
801 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000802 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000803
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000804 Sema::OwningExprResult Result =
805 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
806 SemaRef.Owned(expr));
807
808 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000809 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000810
811 expr = Result.takeAs<Expr>();
812 IList->setInit(Index, expr);
813
Douglas Gregor930d8b52009-01-30 22:09:00 +0000814 if (hadError)
815 ++StructuredIndex;
816 else
817 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
818 ++Index;
819 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000820 // FIXME: It would be wonderful if we could point at the actual member. In
821 // general, it would be useful to pass location information down the stack,
822 // so that we know the location (or decl) of the "current object" being
823 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000824 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000825 diag::err_init_reference_member_uninitialized)
826 << DeclType
827 << IList->getSourceRange();
828 hadError = true;
829 ++Index;
830 ++StructuredIndex;
831 return;
832 }
833}
834
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000835void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000836 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000837 unsigned &Index,
838 InitListExpr *StructuredList,
839 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000840 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000841 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000842 unsigned maxElements = VT->getNumElements();
843 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000844 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Nate Begeman2ef13e52009-08-10 23:49:36 +0000846 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000847 InitializedEntity ElementEntity =
848 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000849
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000850 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
851 // Don't attempt to go past the end of the init list
852 if (Index >= IList->getNumInits())
853 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000854
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000855 ElementEntity.setElementIndex(Index);
856 CheckSubElementType(ElementEntity, IList, elementType, Index,
857 StructuredList, StructuredIndex);
858 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000859 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000860 InitializedEntity ElementEntity =
861 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
862
Nate Begeman2ef13e52009-08-10 23:49:36 +0000863 // OpenCL initializers allows vectors to be constructed from vectors.
864 for (unsigned i = 0; i < maxElements; ++i) {
865 // Don't attempt to go past the end of the init list
866 if (Index >= IList->getNumInits())
867 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000868
869 ElementEntity.setElementIndex(Index);
870
Nate Begeman2ef13e52009-08-10 23:49:36 +0000871 QualType IType = IList->getInit(Index)->getType();
872 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000873 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000874 StructuredList, StructuredIndex);
875 ++numEltsInit;
876 } else {
John McCall183700f2009-09-21 23:43:11 +0000877 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000878 unsigned numIElts = IVT->getNumElements();
879 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
880 numIElts);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000881 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000882 StructuredList, StructuredIndex);
883 numEltsInit += numIElts;
884 }
885 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Nate Begeman2ef13e52009-08-10 23:49:36 +0000888 // OpenCL & AltiVec require all elements to be initialized.
889 if (numEltsInit != maxElements)
890 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
891 SemaRef.Diag(IList->getSourceRange().getBegin(),
892 diag::err_vector_incorrect_num_initializers)
893 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000894 }
895}
896
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000897void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000898 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000899 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000900 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000901 unsigned &Index,
902 InitListExpr *StructuredList,
903 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000904 // Check for the special-case of initializing an array with a string.
905 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000906 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
907 SemaRef.Context)) {
908 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000909 // We place the string literal directly into the resulting
910 // initializer list. This is the only place where the structure
911 // of the structured initializer list doesn't match exactly,
912 // because doing so would involve allocating one character
913 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000914 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000915 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000916 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000917 return;
918 }
919 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000920 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000921 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000922 // Check for VLAs; in standard C it would be possible to check this
923 // earlier, but I don't know where clang accepts VLAs (gcc accepts
924 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000925 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000926 diag::err_variable_object_no_init)
927 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000928 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000929 ++Index;
930 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000931 return;
932 }
933
Douglas Gregor05c13a32009-01-22 00:58:24 +0000934 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000935 llvm::APSInt maxElements(elementIndex.getBitWidth(),
936 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000937 bool maxElementsKnown = false;
938 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000939 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000940 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000941 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000942 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000943 maxElementsKnown = true;
944 }
945
Chris Lattner08202542009-02-24 22:50:46 +0000946 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000947 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000948 while (Index < IList->getNumInits()) {
949 Expr *Init = IList->getInit(Index);
950 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000951 // If we're not the subobject that matches up with the '{' for
952 // the designator, we shouldn't be handling the
953 // designator. Return immediately.
954 if (!SubobjectIsDesignatorContext)
955 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000956
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000957 // Handle this designated initializer. elementIndex will be
958 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000959 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000960 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000961 StructuredList, StructuredIndex, true,
962 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000963 hadError = true;
964 continue;
965 }
966
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000967 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
968 maxElements.extend(elementIndex.getBitWidth());
969 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
970 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000971 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000972
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000973 // If the array is of incomplete type, keep track of the number of
974 // elements in the initializer.
975 if (!maxElementsKnown && elementIndex > maxElements)
976 maxElements = elementIndex;
977
Douglas Gregor05c13a32009-01-22 00:58:24 +0000978 continue;
979 }
980
981 // If we know the maximum number of elements, and we've already
982 // hit it, stop consuming elements in the initializer list.
983 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000984 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000985
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000986 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000987 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000988 Entity);
989 // Check this element.
990 CheckSubElementType(ElementEntity, IList, elementType, Index,
991 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000992 ++elementIndex;
993
994 // If the array is of incomplete type, keep track of the number of
995 // elements in the initializer.
996 if (!maxElementsKnown && elementIndex > maxElements)
997 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000998 }
Eli Friedman587cbdf2009-05-29 20:17:55 +0000999 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001000 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001001 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001002 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001003 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001004 // Sizing an array implicitly to zero is not allowed by ISO C,
1005 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001006 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001007 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001008 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001009
Mike Stump1eb44332009-09-09 15:08:12 +00001010 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001011 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001012 }
1013}
1014
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001015void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001016 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001017 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001018 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001019 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001020 unsigned &Index,
1021 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001022 unsigned &StructuredIndex,
1023 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001024 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Eli Friedmanb85f7072008-05-19 19:16:24 +00001026 // If the record is invalid, some of it's members are invalid. To avoid
1027 // confusion, we forgo checking the intializer for the entire record.
1028 if (structDecl->isInvalidDecl()) {
1029 hadError = true;
1030 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001031 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001032
1033 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1034 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001035 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001036 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001037 Field != FieldEnd; ++Field) {
1038 if (Field->getDeclName()) {
1039 StructuredList->setInitializedFieldInUnion(*Field);
1040 break;
1041 }
1042 }
1043 return;
1044 }
1045
Douglas Gregor05c13a32009-01-22 00:58:24 +00001046 // If structDecl is a forward declaration, this loop won't do
1047 // anything except look at designated initializers; That's okay,
1048 // because an error should get printed out elsewhere. It might be
1049 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001050 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001051 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001052 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001053 while (Index < IList->getNumInits()) {
1054 Expr *Init = IList->getInit(Index);
1055
1056 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001057 // If we're not the subobject that matches up with the '{' for
1058 // the designator, we shouldn't be handling the
1059 // designator. Return immediately.
1060 if (!SubobjectIsDesignatorContext)
1061 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001062
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001063 // Handle this designated initializer. Field will be updated to
1064 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001065 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001066 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001067 StructuredList, StructuredIndex,
1068 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001069 hadError = true;
1070
Douglas Gregordfb5e592009-02-12 19:00:39 +00001071 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001072 continue;
1073 }
1074
1075 if (Field == FieldEnd) {
1076 // We've run out of fields. We're done.
1077 break;
1078 }
1079
Douglas Gregordfb5e592009-02-12 19:00:39 +00001080 // We've already initialized a member of a union. We're done.
1081 if (InitializedSomething && DeclType->isUnionType())
1082 break;
1083
Douglas Gregor44b43212008-12-11 16:49:14 +00001084 // If we've hit the flexible array member at the end, we're done.
1085 if (Field->getType()->isIncompleteArrayType())
1086 break;
1087
Douglas Gregor0bb76892009-01-29 16:53:55 +00001088 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001089 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001090 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001091 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001092 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001093
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001094 InitializedEntity MemberEntity =
1095 InitializedEntity::InitializeMember(*Field, &Entity);
1096 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1097 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001098 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001099
1100 if (DeclType->isUnionType()) {
1101 // Initialize the first field within the union.
1102 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001103 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001104
1105 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001106 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001107
Mike Stump1eb44332009-09-09 15:08:12 +00001108 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001109 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001110 return;
1111
1112 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001113 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001114 (!isa<InitListExpr>(IList->getInit(Index)) ||
1115 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001116 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001117 diag::err_flexible_array_init_nonempty)
1118 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001119 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001120 << *Field;
1121 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001122 ++Index;
1123 return;
1124 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001125 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001126 diag::ext_flexible_array_init)
1127 << IList->getInit(Index)->getSourceRange().getBegin();
1128 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1129 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001130 }
1131
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001132 InitializedEntity MemberEntity =
1133 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001134
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001135 if (isa<InitListExpr>(IList->getInit(Index)))
1136 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1137 StructuredList, StructuredIndex);
1138 else
1139 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001140 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001141}
Steve Naroff0cca7492008-05-01 22:18:59 +00001142
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001143/// \brief Expand a field designator that refers to a member of an
1144/// anonymous struct or union into a series of field designators that
1145/// refers to the field within the appropriate subobject.
1146///
1147/// Field/FieldIndex will be updated to point to the (new)
1148/// currently-designated field.
1149static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001150 DesignatedInitExpr *DIE,
1151 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001152 FieldDecl *Field,
1153 RecordDecl::field_iterator &FieldIter,
1154 unsigned &FieldIndex) {
1155 typedef DesignatedInitExpr::Designator Designator;
1156
1157 // Build the path from the current object to the member of the
1158 // anonymous struct/union (backwards).
1159 llvm::SmallVector<FieldDecl *, 4> Path;
1160 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001162 // Build the replacement designators.
1163 llvm::SmallVector<Designator, 4> Replacements;
1164 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1165 FI = Path.rbegin(), FIEnd = Path.rend();
1166 FI != FIEnd; ++FI) {
1167 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001168 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001169 DIE->getDesignator(DesigIdx)->getDotLoc(),
1170 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1171 else
1172 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1173 SourceLocation()));
1174 Replacements.back().setField(*FI);
1175 }
1176
1177 // Expand the current designator into the set of replacement
1178 // designators, so we have a full subobject path down to where the
1179 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001180 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001181 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001183 // Update FieldIter/FieldIndex;
1184 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001185 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001186 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001187 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001188 FieldIter != FEnd; ++FieldIter) {
1189 if (FieldIter->isUnnamedBitfield())
1190 continue;
1191
1192 if (*FieldIter == Path.back())
1193 return;
1194
1195 ++FieldIndex;
1196 }
1197
1198 assert(false && "Unable to find anonymous struct/union field");
1199}
1200
Douglas Gregor05c13a32009-01-22 00:58:24 +00001201/// @brief Check the well-formedness of a C99 designated initializer.
1202///
1203/// Determines whether the designated initializer @p DIE, which
1204/// resides at the given @p Index within the initializer list @p
1205/// IList, is well-formed for a current object of type @p DeclType
1206/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001207/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001208/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001209///
1210/// @param IList The initializer list in which this designated
1211/// initializer occurs.
1212///
Douglas Gregor71199712009-04-15 04:56:10 +00001213/// @param DIE The designated initializer expression.
1214///
1215/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001216///
1217/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1218/// into which the designation in @p DIE should refer.
1219///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001220/// @param NextField If non-NULL and the first designator in @p DIE is
1221/// a field, this will be set to the field declaration corresponding
1222/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001223///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001224/// @param NextElementIndex If non-NULL and the first designator in @p
1225/// DIE is an array designator or GNU array-range designator, this
1226/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001227///
1228/// @param Index Index into @p IList where the designated initializer
1229/// @p DIE occurs.
1230///
Douglas Gregor4c678342009-01-28 21:54:33 +00001231/// @param StructuredList The initializer list expression that
1232/// describes all of the subobject initializers in the order they'll
1233/// actually be initialized.
1234///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001235/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001236bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001237InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001238 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001239 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001240 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001241 QualType &CurrentObjectType,
1242 RecordDecl::field_iterator *NextField,
1243 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001244 unsigned &Index,
1245 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001246 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001247 bool FinishSubobjectInit,
1248 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001249 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001250 // Check the actual initialization for the designated object type.
1251 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001252
1253 // Temporarily remove the designator expression from the
1254 // initializer list that the child calls see, so that we don't try
1255 // to re-process the designator.
1256 unsigned OldIndex = Index;
1257 IList->setInit(OldIndex, DIE->getInit());
1258
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001259 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001260 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001261
1262 // Restore the designated initializer expression in the syntactic
1263 // form of the initializer list.
1264 if (IList->getInit(OldIndex) != DIE->getInit())
1265 DIE->setInit(IList->getInit(OldIndex));
1266 IList->setInit(OldIndex, DIE);
1267
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001268 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001269 }
1270
Douglas Gregor71199712009-04-15 04:56:10 +00001271 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001272 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001273 "Need a non-designated initializer list to start from");
1274
Douglas Gregor71199712009-04-15 04:56:10 +00001275 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001276 // Determine the structural initializer list that corresponds to the
1277 // current subobject.
1278 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001279 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001280 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001281 SourceRange(D->getStartLocation(),
1282 DIE->getSourceRange().getEnd()));
1283 assert(StructuredList && "Expected a structured initializer list");
1284
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001285 if (D->isFieldDesignator()) {
1286 // C99 6.7.8p7:
1287 //
1288 // If a designator has the form
1289 //
1290 // . identifier
1291 //
1292 // then the current object (defined below) shall have
1293 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001294 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001295 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001296 if (!RT) {
1297 SourceLocation Loc = D->getDotLoc();
1298 if (Loc.isInvalid())
1299 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001300 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1301 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001302 ++Index;
1303 return true;
1304 }
1305
Douglas Gregor4c678342009-01-28 21:54:33 +00001306 // Note: we perform a linear search of the fields here, despite
1307 // the fact that we have a faster lookup method, because we always
1308 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001309 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001310 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001311 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001312 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001313 Field = RT->getDecl()->field_begin(),
1314 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001315 for (; Field != FieldEnd; ++Field) {
1316 if (Field->isUnnamedBitfield())
1317 continue;
1318
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001319 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001320 break;
1321
1322 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001323 }
1324
Douglas Gregor4c678342009-01-28 21:54:33 +00001325 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001326 // There was no normal field in the struct with the designated
1327 // name. Perform another lookup for this name, which may find
1328 // something that we can't designate (e.g., a member function),
1329 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001330 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001331 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001332 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001333 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001334 // Name lookup didn't find anything. Determine whether this
1335 // was a typo for another field name.
1336 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1337 Sema::LookupMemberName);
1338 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1339 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1340 ReplacementField->getDeclContext()->getLookupContext()
1341 ->Equals(RT->getDecl())) {
1342 SemaRef.Diag(D->getFieldLoc(),
1343 diag::err_field_designator_unknown_suggest)
1344 << FieldName << CurrentObjectType << R.getLookupName()
1345 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1346 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001347 SemaRef.Diag(ReplacementField->getLocation(),
1348 diag::note_previous_decl)
1349 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001350 } else {
1351 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1352 << FieldName << CurrentObjectType;
1353 ++Index;
1354 return true;
1355 }
1356 } else if (!KnownField) {
1357 // Determine whether we found a field at all.
1358 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1359 }
1360
1361 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001362 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001363 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001364 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001365 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001366 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001367 ++Index;
1368 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001369 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001370
1371 if (!KnownField &&
1372 cast<RecordDecl>((ReplacementField)->getDeclContext())
1373 ->isAnonymousStructOrUnion()) {
1374 // Handle an field designator that refers to a member of an
1375 // anonymous struct or union.
1376 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1377 ReplacementField,
1378 Field, FieldIndex);
1379 D = DIE->getDesignator(DesigIdx);
1380 } else if (!KnownField) {
1381 // The replacement field comes from typo correction; find it
1382 // in the list of fields.
1383 FieldIndex = 0;
1384 Field = RT->getDecl()->field_begin();
1385 for (; Field != FieldEnd; ++Field) {
1386 if (Field->isUnnamedBitfield())
1387 continue;
1388
1389 if (ReplacementField == *Field ||
1390 Field->getIdentifier() == ReplacementField->getIdentifier())
1391 break;
1392
1393 ++FieldIndex;
1394 }
1395 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001396 } else if (!KnownField &&
1397 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001398 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001399 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1400 Field, FieldIndex);
1401 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001402 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001403
1404 // All of the fields of a union are located at the same place in
1405 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001406 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001407 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001408 StructuredList->setInitializedFieldInUnion(*Field);
1409 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001410
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001411 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001412 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Douglas Gregor4c678342009-01-28 21:54:33 +00001414 // Make sure that our non-designated initializer list has space
1415 // for a subobject corresponding to this field.
1416 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001417 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001418
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001419 // This designator names a flexible array member.
1420 if (Field->getType()->isIncompleteArrayType()) {
1421 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001422 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001423 // We can't designate an object within the flexible array
1424 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001425 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001426 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001427 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001428 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001429 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001430 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001431 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001432 << *Field;
1433 Invalid = true;
1434 }
1435
1436 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1437 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001438 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001439 diag::err_flexible_array_init_needs_braces)
1440 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001441 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001442 << *Field;
1443 Invalid = true;
1444 }
1445
1446 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001447 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001448 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001449 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001450 diag::err_flexible_array_init_nonempty)
1451 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001452 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001453 << *Field;
1454 Invalid = true;
1455 }
1456
1457 if (Invalid) {
1458 ++Index;
1459 return true;
1460 }
1461
1462 // Initialize the array.
1463 bool prevHadError = hadError;
1464 unsigned newStructuredIndex = FieldIndex;
1465 unsigned OldIndex = Index;
1466 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001467
1468 InitializedEntity MemberEntity =
1469 InitializedEntity::InitializeMember(*Field, &Entity);
1470 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001471 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001472
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001473 IList->setInit(OldIndex, DIE);
1474 if (hadError && !prevHadError) {
1475 ++Field;
1476 ++FieldIndex;
1477 if (NextField)
1478 *NextField = Field;
1479 StructuredIndex = FieldIndex;
1480 return true;
1481 }
1482 } else {
1483 // Recurse to check later designated subobjects.
1484 QualType FieldType = (*Field)->getType();
1485 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001486
1487 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001488 InitializedEntity::InitializeMember(*Field, &Entity);
1489 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001490 FieldType, 0, 0, Index,
1491 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001492 true, false))
1493 return true;
1494 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001495
1496 // Find the position of the next field to be initialized in this
1497 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001498 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001499 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001500
1501 // If this the first designator, our caller will continue checking
1502 // the rest of this struct/class/union subobject.
1503 if (IsFirstDesignator) {
1504 if (NextField)
1505 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001506 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001507 return false;
1508 }
1509
Douglas Gregor34e79462009-01-28 23:36:17 +00001510 if (!FinishSubobjectInit)
1511 return false;
1512
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001513 // We've already initialized something in the union; we're done.
1514 if (RT->getDecl()->isUnion())
1515 return hadError;
1516
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001517 // Check the remaining fields within this class/struct/union subobject.
1518 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001519
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001520 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001521 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001522 return hadError && !prevHadError;
1523 }
1524
1525 // C99 6.7.8p6:
1526 //
1527 // If a designator has the form
1528 //
1529 // [ constant-expression ]
1530 //
1531 // then the current object (defined below) shall have array
1532 // type and the expression shall be an integer constant
1533 // expression. If the array is of unknown size, any
1534 // nonnegative value is valid.
1535 //
1536 // Additionally, cope with the GNU extension that permits
1537 // designators of the form
1538 //
1539 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001540 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001541 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001542 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001543 << CurrentObjectType;
1544 ++Index;
1545 return true;
1546 }
1547
1548 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001549 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1550 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001551 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001552 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001553 DesignatedEndIndex = DesignatedStartIndex;
1554 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001555 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001556
Mike Stump1eb44332009-09-09 15:08:12 +00001557
1558 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001559 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001560 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001561 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001562 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001563
Chris Lattner3bf68932009-04-25 21:59:05 +00001564 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001565 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001566 }
1567
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001568 if (isa<ConstantArrayType>(AT)) {
1569 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001570 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1571 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1572 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1573 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1574 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001575 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001576 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001577 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001578 << IndexExpr->getSourceRange();
1579 ++Index;
1580 return true;
1581 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001582 } else {
1583 // Make sure the bit-widths and signedness match.
1584 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1585 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001586 else if (DesignatedStartIndex.getBitWidth() <
1587 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001588 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1589 DesignatedStartIndex.setIsUnsigned(true);
1590 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Douglas Gregor4c678342009-01-28 21:54:33 +00001593 // Make sure that our non-designated initializer list has space
1594 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001595 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001596 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001597 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001598
Douglas Gregor34e79462009-01-28 23:36:17 +00001599 // Repeatedly perform subobject initializations in the range
1600 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001601
Douglas Gregor34e79462009-01-28 23:36:17 +00001602 // Move to the next designator
1603 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1604 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001605
1606 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001607 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001608
Douglas Gregor34e79462009-01-28 23:36:17 +00001609 while (DesignatedStartIndex <= DesignatedEndIndex) {
1610 // Recurse to check later designated subobjects.
1611 QualType ElementType = AT->getElementType();
1612 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001613
1614 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001615 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001616 ElementType, 0, 0, Index,
1617 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001618 (DesignatedStartIndex == DesignatedEndIndex),
1619 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001620 return true;
1621
1622 // Move to the next index in the array that we'll be initializing.
1623 ++DesignatedStartIndex;
1624 ElementIndex = DesignatedStartIndex.getZExtValue();
1625 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001626
1627 // If this the first designator, our caller will continue checking
1628 // the rest of this array subobject.
1629 if (IsFirstDesignator) {
1630 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001631 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001632 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001633 return false;
1634 }
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Douglas Gregor34e79462009-01-28 23:36:17 +00001636 if (!FinishSubobjectInit)
1637 return false;
1638
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001639 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001640 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001641 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001642 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001643 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001644 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001645}
1646
Douglas Gregor4c678342009-01-28 21:54:33 +00001647// Get the structured initializer list for a subobject of type
1648// @p CurrentObjectType.
1649InitListExpr *
1650InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1651 QualType CurrentObjectType,
1652 InitListExpr *StructuredList,
1653 unsigned StructuredIndex,
1654 SourceRange InitRange) {
1655 Expr *ExistingInit = 0;
1656 if (!StructuredList)
1657 ExistingInit = SyntacticToSemantic[IList];
1658 else if (StructuredIndex < StructuredList->getNumInits())
1659 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Douglas Gregor4c678342009-01-28 21:54:33 +00001661 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1662 return Result;
1663
1664 if (ExistingInit) {
1665 // We are creating an initializer list that initializes the
1666 // subobjects of the current object, but there was already an
1667 // initialization that completely initialized the current
1668 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001669 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001670 // struct X { int a, b; };
1671 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001672 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001673 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1674 // designated initializer re-initializes the whole
1675 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001676 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001677 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001678 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001679 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001680 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001681 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001682 << ExistingInit->getSourceRange();
1683 }
1684
Mike Stump1eb44332009-09-09 15:08:12 +00001685 InitListExpr *Result
Ted Kremenekba7bc552010-02-19 01:50:18 +00001686 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1687 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001688
Douglas Gregor2c792812010-02-09 00:50:06 +00001689 Result->setType(CurrentObjectType.getNonReferenceType());
Douglas Gregor4c678342009-01-28 21:54:33 +00001690
Douglas Gregorfa219202009-03-20 23:58:33 +00001691 // Pre-allocate storage for the structured initializer list.
1692 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001693 unsigned NumInits = 0;
1694 if (!StructuredList)
1695 NumInits = IList->getNumInits();
1696 else if (Index < IList->getNumInits()) {
1697 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1698 NumInits = SubList->getNumInits();
1699 }
1700
Mike Stump1eb44332009-09-09 15:08:12 +00001701 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001702 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1703 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1704 NumElements = CAType->getSize().getZExtValue();
1705 // Simple heuristic so that we don't allocate a very large
1706 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001707 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001708 NumElements = 0;
1709 }
John McCall183700f2009-09-21 23:43:11 +00001710 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001711 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001712 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001713 RecordDecl *RDecl = RType->getDecl();
1714 if (RDecl->isUnion())
1715 NumElements = 1;
1716 else
Mike Stump1eb44332009-09-09 15:08:12 +00001717 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001718 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001719 }
1720
Douglas Gregor08457732009-03-21 18:13:52 +00001721 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001722 NumElements = IList->getNumInits();
1723
Ted Kremenekba7bc552010-02-19 01:50:18 +00001724 Result->reserveInits(NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001725
Douglas Gregor4c678342009-01-28 21:54:33 +00001726 // Link this new initializer list into the structured initializer
1727 // lists.
1728 if (StructuredList)
Ted Kremenekba7bc552010-02-19 01:50:18 +00001729 StructuredList->updateInit(StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001730 else {
1731 Result->setSyntacticForm(IList);
1732 SyntacticToSemantic[IList] = Result;
1733 }
1734
1735 return Result;
1736}
1737
1738/// Update the initializer at index @p StructuredIndex within the
1739/// structured initializer list to the value @p expr.
1740void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1741 unsigned &StructuredIndex,
1742 Expr *expr) {
1743 // No structured initializer list to update
1744 if (!StructuredList)
1745 return;
1746
Ted Kremenekba7bc552010-02-19 01:50:18 +00001747 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001748 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001749 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001750 diag::warn_initializer_overrides)
1751 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001752 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001753 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001754 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001755 << PrevInit->getSourceRange();
1756 }
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Douglas Gregor4c678342009-01-28 21:54:33 +00001758 ++StructuredIndex;
1759}
1760
Douglas Gregor05c13a32009-01-22 00:58:24 +00001761/// Check that the given Index expression is a valid array designator
1762/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001763/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001764/// and produces a reasonable diagnostic if there is a
1765/// failure. Returns true if there was an error, false otherwise. If
1766/// everything went okay, Value will receive the value of the constant
1767/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001768static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001769CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001770 SourceLocation Loc = Index->getSourceRange().getBegin();
1771
1772 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001773 if (S.VerifyIntegerConstantExpression(Index, &Value))
1774 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001775
Chris Lattner3bf68932009-04-25 21:59:05 +00001776 if (Value.isSigned() && Value.isNegative())
1777 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001778 << Value.toString(10) << Index->getSourceRange();
1779
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001780 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001781 return false;
1782}
1783
1784Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1785 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001786 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001787 OwningExprResult Init) {
1788 typedef DesignatedInitExpr::Designator ASTDesignator;
1789
1790 bool Invalid = false;
1791 llvm::SmallVector<ASTDesignator, 32> Designators;
1792 llvm::SmallVector<Expr *, 32> InitExpressions;
1793
1794 // Build designators and check array designator expressions.
1795 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1796 const Designator &D = Desig.getDesignator(Idx);
1797 switch (D.getKind()) {
1798 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001799 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001800 D.getFieldLoc()));
1801 break;
1802
1803 case Designator::ArrayDesignator: {
1804 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1805 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001806 if (!Index->isTypeDependent() &&
1807 !Index->isValueDependent() &&
1808 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001809 Invalid = true;
1810 else {
1811 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001812 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001813 D.getRBracketLoc()));
1814 InitExpressions.push_back(Index);
1815 }
1816 break;
1817 }
1818
1819 case Designator::ArrayRangeDesignator: {
1820 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1821 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1822 llvm::APSInt StartValue;
1823 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001824 bool StartDependent = StartIndex->isTypeDependent() ||
1825 StartIndex->isValueDependent();
1826 bool EndDependent = EndIndex->isTypeDependent() ||
1827 EndIndex->isValueDependent();
1828 if ((!StartDependent &&
1829 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1830 (!EndDependent &&
1831 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001832 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001833 else {
1834 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001835 if (StartDependent || EndDependent) {
1836 // Nothing to compute.
1837 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001838 EndValue.extend(StartValue.getBitWidth());
1839 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1840 StartValue.extend(EndValue.getBitWidth());
1841
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001842 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001843 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001844 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001845 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1846 Invalid = true;
1847 } else {
1848 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001849 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001850 D.getEllipsisLoc(),
1851 D.getRBracketLoc()));
1852 InitExpressions.push_back(StartIndex);
1853 InitExpressions.push_back(EndIndex);
1854 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001855 }
1856 break;
1857 }
1858 }
1859 }
1860
1861 if (Invalid || Init.isInvalid())
1862 return ExprError();
1863
1864 // Clear out the expressions within the designation.
1865 Desig.ClearExprs(*this);
1866
1867 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001868 = DesignatedInitExpr::Create(Context,
1869 Designators.data(), Designators.size(),
1870 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001871 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001872 return Owned(DIE);
1873}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001874
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001875bool Sema::CheckInitList(const InitializedEntity &Entity,
1876 InitListExpr *&InitList, QualType &DeclType) {
1877 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001878 if (!CheckInitList.HadError())
1879 InitList = CheckInitList.getFullyStructuredList();
1880
1881 return CheckInitList.HadError();
1882}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001883
Douglas Gregor20093b42009-12-09 23:02:17 +00001884//===----------------------------------------------------------------------===//
1885// Initialization entity
1886//===----------------------------------------------------------------------===//
1887
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001888InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1889 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001890 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001891{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001892 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1893 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001894 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001895 } else {
1896 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001897 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001898 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001899}
1900
1901InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1902 CXXBaseSpecifier *Base)
1903{
1904 InitializedEntity Result;
1905 Result.Kind = EK_Base;
1906 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001907 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001908 return Result;
1909}
1910
Douglas Gregor99a2e602009-12-16 01:38:02 +00001911DeclarationName InitializedEntity::getName() const {
1912 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001913 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001914 if (!VariableOrMember)
1915 return DeclarationName();
1916 // Fall through
1917
1918 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001919 case EK_Member:
1920 return VariableOrMember->getDeclName();
1921
1922 case EK_Result:
1923 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001924 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001925 case EK_Temporary:
1926 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001927 case EK_ArrayElement:
1928 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001929 return DeclarationName();
1930 }
1931
1932 // Silence GCC warning
1933 return DeclarationName();
1934}
1935
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001936DeclaratorDecl *InitializedEntity::getDecl() const {
1937 switch (getKind()) {
1938 case EK_Variable:
1939 case EK_Parameter:
1940 case EK_Member:
1941 return VariableOrMember;
1942
1943 case EK_Result:
1944 case EK_Exception:
1945 case EK_New:
1946 case EK_Temporary:
1947 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001948 case EK_ArrayElement:
1949 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001950 return 0;
1951 }
1952
1953 // Silence GCC warning
1954 return 0;
1955}
1956
Douglas Gregor20093b42009-12-09 23:02:17 +00001957//===----------------------------------------------------------------------===//
1958// Initialization sequence
1959//===----------------------------------------------------------------------===//
1960
1961void InitializationSequence::Step::Destroy() {
1962 switch (Kind) {
1963 case SK_ResolveAddressOfOverloadedFunction:
1964 case SK_CastDerivedToBaseRValue:
1965 case SK_CastDerivedToBaseLValue:
1966 case SK_BindReference:
1967 case SK_BindReferenceToTemporary:
1968 case SK_UserConversion:
1969 case SK_QualificationConversionRValue:
1970 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001971 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001972 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001973 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001974 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001975 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001976 break;
1977
1978 case SK_ConversionSequence:
1979 delete ICS;
1980 }
1981}
1982
1983void InitializationSequence::AddAddressOverloadResolutionStep(
1984 FunctionDecl *Function) {
1985 Step S;
1986 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1987 S.Type = Function->getType();
John McCallb13b7372010-02-01 03:16:54 +00001988 // Access is currently ignored for these.
1989 S.Function = DeclAccessPair::make(Function, AccessSpecifier(0));
Douglas Gregor20093b42009-12-09 23:02:17 +00001990 Steps.push_back(S);
1991}
1992
1993void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1994 bool IsLValue) {
1995 Step S;
1996 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1997 S.Type = BaseType;
1998 Steps.push_back(S);
1999}
2000
2001void InitializationSequence::AddReferenceBindingStep(QualType T,
2002 bool BindingTemporary) {
2003 Step S;
2004 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2005 S.Type = T;
2006 Steps.push_back(S);
2007}
2008
Eli Friedman03981012009-12-11 02:42:07 +00002009void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCallb13b7372010-02-01 03:16:54 +00002010 AccessSpecifier Access,
Eli Friedman03981012009-12-11 02:42:07 +00002011 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002012 Step S;
2013 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002014 S.Type = T;
John McCallb13b7372010-02-01 03:16:54 +00002015 S.Function = DeclAccessPair::make(Function, Access);
Douglas Gregor20093b42009-12-09 23:02:17 +00002016 Steps.push_back(S);
2017}
2018
2019void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2020 bool IsLValue) {
2021 Step S;
2022 S.Kind = IsLValue? SK_QualificationConversionLValue
2023 : SK_QualificationConversionRValue;
2024 S.Type = Ty;
2025 Steps.push_back(S);
2026}
2027
2028void InitializationSequence::AddConversionSequenceStep(
2029 const ImplicitConversionSequence &ICS,
2030 QualType T) {
2031 Step S;
2032 S.Kind = SK_ConversionSequence;
2033 S.Type = T;
2034 S.ICS = new ImplicitConversionSequence(ICS);
2035 Steps.push_back(S);
2036}
2037
Douglas Gregord87b61f2009-12-10 17:56:55 +00002038void InitializationSequence::AddListInitializationStep(QualType T) {
2039 Step S;
2040 S.Kind = SK_ListInitialization;
2041 S.Type = T;
2042 Steps.push_back(S);
2043}
2044
Douglas Gregor51c56d62009-12-14 20:49:26 +00002045void
2046InitializationSequence::AddConstructorInitializationStep(
2047 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002048 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002049 QualType T) {
2050 Step S;
2051 S.Kind = SK_ConstructorInitialization;
2052 S.Type = T;
John McCallb13b7372010-02-01 03:16:54 +00002053 S.Function = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002054 Steps.push_back(S);
2055}
2056
Douglas Gregor71d17402009-12-15 00:01:57 +00002057void InitializationSequence::AddZeroInitializationStep(QualType T) {
2058 Step S;
2059 S.Kind = SK_ZeroInitialization;
2060 S.Type = T;
2061 Steps.push_back(S);
2062}
2063
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002064void InitializationSequence::AddCAssignmentStep(QualType T) {
2065 Step S;
2066 S.Kind = SK_CAssignment;
2067 S.Type = T;
2068 Steps.push_back(S);
2069}
2070
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002071void InitializationSequence::AddStringInitStep(QualType T) {
2072 Step S;
2073 S.Kind = SK_StringInit;
2074 S.Type = T;
2075 Steps.push_back(S);
2076}
2077
Douglas Gregor20093b42009-12-09 23:02:17 +00002078void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2079 OverloadingResult Result) {
2080 SequenceKind = FailedSequence;
2081 this->Failure = Failure;
2082 this->FailedOverloadResult = Result;
2083}
2084
2085//===----------------------------------------------------------------------===//
2086// Attempt initialization
2087//===----------------------------------------------------------------------===//
2088
2089/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002090static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002091 const InitializedEntity &Entity,
2092 const InitializationKind &Kind,
2093 InitListExpr *InitList,
2094 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002095 // FIXME: We only perform rudimentary checking of list
2096 // initializations at this point, then assume that any list
2097 // initialization of an array, aggregate, or scalar will be
2098 // well-formed. We we actually "perform" list initialization, we'll
2099 // do all of the necessary checking. C++0x initializer lists will
2100 // force us to perform more checking here.
2101 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2102
Douglas Gregord6542d82009-12-22 15:35:07 +00002103 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002104
2105 // C++ [dcl.init]p13:
2106 // If T is a scalar type, then a declaration of the form
2107 //
2108 // T x = { a };
2109 //
2110 // is equivalent to
2111 //
2112 // T x = a;
2113 if (DestType->isScalarType()) {
2114 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2115 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2116 return;
2117 }
2118
2119 // Assume scalar initialization from a single value works.
2120 } else if (DestType->isAggregateType()) {
2121 // Assume aggregate initialization works.
2122 } else if (DestType->isVectorType()) {
2123 // Assume vector initialization works.
2124 } else if (DestType->isReferenceType()) {
2125 // FIXME: C++0x defines behavior for this.
2126 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2127 return;
2128 } else if (DestType->isRecordType()) {
2129 // FIXME: C++0x defines behavior for this
2130 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2131 }
2132
2133 // Add a general "list initialization" step.
2134 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002135}
2136
2137/// \brief Try a reference initialization that involves calling a conversion
2138/// function.
2139///
2140/// FIXME: look intos DRs 656, 896
2141static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2142 const InitializedEntity &Entity,
2143 const InitializationKind &Kind,
2144 Expr *Initializer,
2145 bool AllowRValues,
2146 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002147 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002148 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2149 QualType T1 = cv1T1.getUnqualifiedType();
2150 QualType cv2T2 = Initializer->getType();
2151 QualType T2 = cv2T2.getUnqualifiedType();
2152
2153 bool DerivedToBase;
2154 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2155 T1, T2, DerivedToBase) &&
2156 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002157 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002158
2159 // Build the candidate set directly in the initialization sequence
2160 // structure, so that it will persist if we fail.
2161 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2162 CandidateSet.clear();
2163
2164 // Determine whether we are allowed to call explicit constructors or
2165 // explicit conversion operators.
2166 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2167
2168 const RecordType *T1RecordType = 0;
2169 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2170 // The type we're converting to is a class type. Enumerate its constructors
2171 // to see if there is a suitable conversion.
2172 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2173
2174 DeclarationName ConstructorName
2175 = S.Context.DeclarationNames.getCXXConstructorName(
2176 S.Context.getCanonicalType(T1).getUnqualifiedType());
2177 DeclContext::lookup_iterator Con, ConEnd;
2178 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2179 Con != ConEnd; ++Con) {
2180 // Find the constructor (which may be a template).
2181 CXXConstructorDecl *Constructor = 0;
2182 FunctionTemplateDecl *ConstructorTmpl
2183 = dyn_cast<FunctionTemplateDecl>(*Con);
2184 if (ConstructorTmpl)
2185 Constructor = cast<CXXConstructorDecl>(
2186 ConstructorTmpl->getTemplatedDecl());
2187 else
2188 Constructor = cast<CXXConstructorDecl>(*Con);
2189
2190 if (!Constructor->isInvalidDecl() &&
2191 Constructor->isConvertingConstructor(AllowExplicit)) {
2192 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002193 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2194 ConstructorTmpl->getAccess(),
2195 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002196 &Initializer, 1, CandidateSet);
2197 else
John McCall86820f52010-01-26 01:37:31 +00002198 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2199 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002200 }
2201 }
2202 }
2203
2204 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2205 // The type we're converting from is a class type, enumerate its conversion
2206 // functions.
2207 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2208
2209 // Determine the type we are converting to. If we are allowed to
2210 // convert to an rvalue, take the type that the destination type
2211 // refers to.
2212 QualType ToType = AllowRValues? cv1T1 : DestType;
2213
John McCalleec51cf2010-01-20 00:46:10 +00002214 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002215 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002216 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2217 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002218 NamedDecl *D = *I;
2219 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2220 if (isa<UsingShadowDecl>(D))
2221 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2222
2223 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2224 CXXConversionDecl *Conv;
2225 if (ConvTemplate)
2226 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2227 else
2228 Conv = cast<CXXConversionDecl>(*I);
2229
2230 // If the conversion function doesn't return a reference type,
2231 // it can't be considered for this conversion unless we're allowed to
2232 // consider rvalues.
2233 // FIXME: Do we need to make sure that we only consider conversion
2234 // candidates with reference-compatible results? That might be needed to
2235 // break recursion.
2236 if ((AllowExplicit || !Conv->isExplicit()) &&
2237 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2238 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00002239 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2240 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002241 ToType, CandidateSet);
2242 else
John McCall86820f52010-01-26 01:37:31 +00002243 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002244 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002245 }
2246 }
2247 }
2248
2249 SourceLocation DeclLoc = Initializer->getLocStart();
2250
2251 // Perform overload resolution. If it fails, return the failed result.
2252 OverloadCandidateSet::iterator Best;
2253 if (OverloadingResult Result
2254 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2255 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002256
Douglas Gregor20093b42009-12-09 23:02:17 +00002257 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002258
2259 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002260 if (isa<CXXConversionDecl>(Function))
2261 T2 = Function->getResultType();
2262 else
2263 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002264
2265 // Add the user-defined conversion step.
John McCallb13b7372010-02-01 03:16:54 +00002266 Sequence.AddUserConversionStep(Function, Best->getAccess(),
2267 T2.getNonReferenceType());
Eli Friedman03981012009-12-11 02:42:07 +00002268
2269 // Determine whether we need to perform derived-to-base or
2270 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002271 bool NewDerivedToBase = false;
2272 Sema::ReferenceCompareResult NewRefRelationship
2273 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2274 NewDerivedToBase);
2275 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2276 "Overload resolution picked a bad conversion function");
2277 (void)NewRefRelationship;
2278 if (NewDerivedToBase)
2279 Sequence.AddDerivedToBaseCastStep(
2280 S.Context.getQualifiedType(T1,
2281 T2.getNonReferenceType().getQualifiers()),
2282 /*isLValue=*/true);
2283
2284 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2285 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2286
2287 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2288 return OR_Success;
2289}
2290
2291/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2292static void TryReferenceInitialization(Sema &S,
2293 const InitializedEntity &Entity,
2294 const InitializationKind &Kind,
2295 Expr *Initializer,
2296 InitializationSequence &Sequence) {
2297 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2298
Douglas Gregord6542d82009-12-22 15:35:07 +00002299 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002300 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002301 Qualifiers T1Quals;
2302 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002303 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002304 Qualifiers T2Quals;
2305 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002306 SourceLocation DeclLoc = Initializer->getLocStart();
2307
2308 // If the initializer is the address of an overloaded function, try
2309 // to resolve the overloaded function. If all goes well, T2 is the
2310 // type of the resulting function.
2311 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2312 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2313 T1,
2314 false);
2315 if (!Fn) {
2316 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2317 return;
2318 }
2319
2320 Sequence.AddAddressOverloadResolutionStep(Fn);
2321 cv2T2 = Fn->getType();
2322 T2 = cv2T2.getUnqualifiedType();
2323 }
2324
2325 // FIXME: Rvalue references
2326 bool ForceRValue = false;
2327
2328 // Compute some basic properties of the types and the initializer.
2329 bool isLValueRef = DestType->isLValueReferenceType();
2330 bool isRValueRef = !isLValueRef;
2331 bool DerivedToBase = false;
2332 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2333 Initializer->isLvalue(S.Context);
2334 Sema::ReferenceCompareResult RefRelationship
2335 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2336
2337 // C++0x [dcl.init.ref]p5:
2338 // A reference to type "cv1 T1" is initialized by an expression of type
2339 // "cv2 T2" as follows:
2340 //
2341 // - If the reference is an lvalue reference and the initializer
2342 // expression
2343 OverloadingResult ConvOvlResult = OR_Success;
2344 if (isLValueRef) {
2345 if (InitLvalue == Expr::LV_Valid &&
2346 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2347 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2348 // reference-compatible with "cv2 T2," or
2349 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002350 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002351 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002352 // can occur. However, we do pay attention to whether it is a bit-field
2353 // to decide whether we're actually binding to a temporary created from
2354 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002355 if (DerivedToBase)
2356 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002357 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002358 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002359 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002360 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002361 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002362 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002363 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002364 return;
2365 }
2366
2367 // - has a class type (i.e., T2 is a class type), where T1 is not
2368 // reference-related to T2, and can be implicitly converted to an
2369 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2370 // with "cv3 T3" (this conversion is selected by enumerating the
2371 // applicable conversion functions (13.3.1.6) and choosing the best
2372 // one through overload resolution (13.3)),
2373 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2374 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2375 Initializer,
2376 /*AllowRValues=*/false,
2377 Sequence);
2378 if (ConvOvlResult == OR_Success)
2379 return;
John McCall1d318332010-01-12 00:44:57 +00002380 if (ConvOvlResult != OR_No_Viable_Function) {
2381 Sequence.SetOverloadFailure(
2382 InitializationSequence::FK_ReferenceInitOverloadFailed,
2383 ConvOvlResult);
2384 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002385 }
2386 }
2387
2388 // - Otherwise, the reference shall be an lvalue reference to a
2389 // non-volatile const type (i.e., cv1 shall be const), or the reference
2390 // shall be an rvalue reference and the initializer expression shall
2391 // be an rvalue.
Douglas Gregoref06e242010-01-29 19:39:15 +00002392 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002393 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2394 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2395 Sequence.SetOverloadFailure(
2396 InitializationSequence::FK_ReferenceInitOverloadFailed,
2397 ConvOvlResult);
2398 else if (isLValueRef)
2399 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2400 ? (RefRelationship == Sema::Ref_Related
2401 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2402 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2403 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2404 else
2405 Sequence.SetFailed(
2406 InitializationSequence::FK_RValueReferenceBindingToLValue);
2407
2408 return;
2409 }
2410
2411 // - If T1 and T2 are class types and
2412 if (T1->isRecordType() && T2->isRecordType()) {
2413 // - the initializer expression is an rvalue and "cv1 T1" is
2414 // reference-compatible with "cv2 T2", or
2415 if (InitLvalue != Expr::LV_Valid &&
2416 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2417 if (DerivedToBase)
2418 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002419 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002420 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002421 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002422 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2423 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2424 return;
2425 }
2426
2427 // - T1 is not reference-related to T2 and the initializer expression
2428 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2429 // conversion is selected by enumerating the applicable conversion
2430 // functions (13.3.1.6) and choosing the best one through overload
2431 // resolution (13.3)),
2432 if (RefRelationship == Sema::Ref_Incompatible) {
2433 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2434 Kind, Initializer,
2435 /*AllowRValues=*/true,
2436 Sequence);
2437 if (ConvOvlResult)
2438 Sequence.SetOverloadFailure(
2439 InitializationSequence::FK_ReferenceInitOverloadFailed,
2440 ConvOvlResult);
2441
2442 return;
2443 }
2444
2445 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2446 return;
2447 }
2448
2449 // - If the initializer expression is an rvalue, with T2 an array type,
2450 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2451 // is bound to the object represented by the rvalue (see 3.10).
2452 // FIXME: How can an array type be reference-compatible with anything?
2453 // Don't we mean the element types of T1 and T2?
2454
2455 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2456 // from the initializer expression using the rules for a non-reference
2457 // copy initialization (8.5). The reference is then bound to the
2458 // temporary. [...]
2459 // Determine whether we are allowed to call explicit constructors or
2460 // explicit conversion operators.
2461 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2462 ImplicitConversionSequence ICS
2463 = S.TryImplicitConversion(Initializer, cv1T1,
2464 /*SuppressUserConversions=*/false, AllowExplicit,
2465 /*ForceRValue=*/false,
2466 /*FIXME:InOverloadResolution=*/false,
2467 /*UserCast=*/Kind.isExplicitCast());
2468
John McCall1d318332010-01-12 00:44:57 +00002469 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002470 // FIXME: Use the conversion function set stored in ICS to turn
2471 // this into an overloading ambiguity diagnostic. However, we need
2472 // to keep that set as an OverloadCandidateSet rather than as some
2473 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002474 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2475 Sequence.SetOverloadFailure(
2476 InitializationSequence::FK_ReferenceInitOverloadFailed,
2477 ConvOvlResult);
2478 else
2479 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002480 return;
2481 }
2482
2483 // [...] If T1 is reference-related to T2, cv1 must be the
2484 // same cv-qualification as, or greater cv-qualification
2485 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002486 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2487 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002488 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002489 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002490 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2491 return;
2492 }
2493
2494 // Perform the actual conversion.
2495 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2496 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2497 return;
2498}
2499
2500/// \brief Attempt character array initialization from a string literal
2501/// (C++ [dcl.init.string], C99 6.7.8).
2502static void TryStringLiteralInitialization(Sema &S,
2503 const InitializedEntity &Entity,
2504 const InitializationKind &Kind,
2505 Expr *Initializer,
2506 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002507 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002508 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002509}
2510
Douglas Gregor20093b42009-12-09 23:02:17 +00002511/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2512/// enumerates the constructors of the initialized entity and performs overload
2513/// resolution to select the best.
2514static void TryConstructorInitialization(Sema &S,
2515 const InitializedEntity &Entity,
2516 const InitializationKind &Kind,
2517 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002518 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002519 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002520 if (Kind.getKind() == InitializationKind::IK_Copy)
2521 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2522 else
2523 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002524
2525 // Build the candidate set directly in the initialization sequence
2526 // structure, so that it will persist if we fail.
2527 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2528 CandidateSet.clear();
2529
2530 // Determine whether we are allowed to call explicit constructors or
2531 // explicit conversion operators.
2532 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2533 Kind.getKind() == InitializationKind::IK_Value ||
2534 Kind.getKind() == InitializationKind::IK_Default);
2535
2536 // The type we're converting to is a class type. Enumerate its constructors
2537 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002538 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2539 assert(DestRecordType && "Constructor initialization requires record type");
2540 CXXRecordDecl *DestRecordDecl
2541 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2542
2543 DeclarationName ConstructorName
2544 = S.Context.DeclarationNames.getCXXConstructorName(
2545 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2546 DeclContext::lookup_iterator Con, ConEnd;
2547 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2548 Con != ConEnd; ++Con) {
2549 // Find the constructor (which may be a template).
2550 CXXConstructorDecl *Constructor = 0;
2551 FunctionTemplateDecl *ConstructorTmpl
2552 = dyn_cast<FunctionTemplateDecl>(*Con);
2553 if (ConstructorTmpl)
2554 Constructor = cast<CXXConstructorDecl>(
2555 ConstructorTmpl->getTemplatedDecl());
2556 else
2557 Constructor = cast<CXXConstructorDecl>(*Con);
2558
2559 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002560 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002561 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002562 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2563 ConstructorTmpl->getAccess(),
2564 /*ExplicitArgs*/ 0,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002565 Args, NumArgs, CandidateSet);
2566 else
John McCall86820f52010-01-26 01:37:31 +00002567 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2568 Args, NumArgs, CandidateSet);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002569 }
2570 }
2571
2572 SourceLocation DeclLoc = Kind.getLocation();
2573
2574 // Perform overload resolution. If it fails, return the failed result.
2575 OverloadCandidateSet::iterator Best;
2576 if (OverloadingResult Result
2577 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2578 Sequence.SetOverloadFailure(
2579 InitializationSequence::FK_ConstructorOverloadFailed,
2580 Result);
2581 return;
2582 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002583
2584 // C++0x [dcl.init]p6:
2585 // If a program calls for the default initialization of an object
2586 // of a const-qualified type T, T shall be a class type with a
2587 // user-provided default constructor.
2588 if (Kind.getKind() == InitializationKind::IK_Default &&
2589 Entity.getType().isConstQualified() &&
2590 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2591 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2592 return;
2593 }
2594
Douglas Gregor51c56d62009-12-14 20:49:26 +00002595 // Add the constructor initialization step. Any cv-qualification conversion is
2596 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002597 if (Kind.getKind() == InitializationKind::IK_Copy) {
John McCallb13b7372010-02-01 03:16:54 +00002598 Sequence.AddUserConversionStep(Best->Function, Best->getAccess(), DestType);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002599 } else {
2600 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002601 cast<CXXConstructorDecl>(Best->Function),
John McCallb13b7372010-02-01 03:16:54 +00002602 Best->getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002603 DestType);
2604 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002605}
2606
Douglas Gregor71d17402009-12-15 00:01:57 +00002607/// \brief Attempt value initialization (C++ [dcl.init]p7).
2608static void TryValueInitialization(Sema &S,
2609 const InitializedEntity &Entity,
2610 const InitializationKind &Kind,
2611 InitializationSequence &Sequence) {
2612 // C++ [dcl.init]p5:
2613 //
2614 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002615 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002616
2617 // -- if T is an array type, then each element is value-initialized;
2618 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2619 T = AT->getElementType();
2620
2621 if (const RecordType *RT = T->getAs<RecordType>()) {
2622 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2623 // -- if T is a class type (clause 9) with a user-declared
2624 // constructor (12.1), then the default constructor for T is
2625 // called (and the initialization is ill-formed if T has no
2626 // accessible default constructor);
2627 //
2628 // FIXME: we really want to refer to a single subobject of the array,
2629 // but Entity doesn't have a way to capture that (yet).
2630 if (ClassDecl->hasUserDeclaredConstructor())
2631 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2632
Douglas Gregor16006c92009-12-16 18:50:27 +00002633 // -- if T is a (possibly cv-qualified) non-union class type
2634 // without a user-provided constructor, then the object is
2635 // zero-initialized and, if T’s implicitly-declared default
2636 // constructor is non-trivial, that constructor is called.
2637 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2638 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2639 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002640 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002641 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2642 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002643 }
2644 }
2645
Douglas Gregord6542d82009-12-22 15:35:07 +00002646 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002647 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2648}
2649
Douglas Gregor99a2e602009-12-16 01:38:02 +00002650/// \brief Attempt default initialization (C++ [dcl.init]p6).
2651static void TryDefaultInitialization(Sema &S,
2652 const InitializedEntity &Entity,
2653 const InitializationKind &Kind,
2654 InitializationSequence &Sequence) {
2655 assert(Kind.getKind() == InitializationKind::IK_Default);
2656
2657 // C++ [dcl.init]p6:
2658 // To default-initialize an object of type T means:
2659 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002660 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002661 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2662 DestType = Array->getElementType();
2663
2664 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2665 // constructor for T is called (and the initialization is ill-formed if
2666 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002667 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00002668 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2669 Sequence);
2670 }
2671
2672 // - otherwise, no initialization is performed.
2673 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2674
2675 // If a program calls for the default initialization of an object of
2676 // a const-qualified type T, T shall be a class type with a user-provided
2677 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002678 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002679 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2680}
2681
Douglas Gregor20093b42009-12-09 23:02:17 +00002682/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2683/// which enumerates all conversion functions and performs overload resolution
2684/// to select the best.
2685static void TryUserDefinedConversion(Sema &S,
2686 const InitializedEntity &Entity,
2687 const InitializationKind &Kind,
2688 Expr *Initializer,
2689 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002690 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2691
Douglas Gregord6542d82009-12-22 15:35:07 +00002692 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002693 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2694 QualType SourceType = Initializer->getType();
2695 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2696 "Must have a class type to perform a user-defined conversion");
2697
2698 // Build the candidate set directly in the initialization sequence
2699 // structure, so that it will persist if we fail.
2700 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2701 CandidateSet.clear();
2702
2703 // Determine whether we are allowed to call explicit constructors or
2704 // explicit conversion operators.
2705 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2706
2707 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2708 // The type we're converting to is a class type. Enumerate its constructors
2709 // to see if there is a suitable conversion.
2710 CXXRecordDecl *DestRecordDecl
2711 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2712
2713 DeclarationName ConstructorName
2714 = S.Context.DeclarationNames.getCXXConstructorName(
2715 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2716 DeclContext::lookup_iterator Con, ConEnd;
2717 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2718 Con != ConEnd; ++Con) {
2719 // Find the constructor (which may be a template).
2720 CXXConstructorDecl *Constructor = 0;
2721 FunctionTemplateDecl *ConstructorTmpl
2722 = dyn_cast<FunctionTemplateDecl>(*Con);
2723 if (ConstructorTmpl)
2724 Constructor = cast<CXXConstructorDecl>(
2725 ConstructorTmpl->getTemplatedDecl());
2726 else
2727 Constructor = cast<CXXConstructorDecl>(*Con);
2728
2729 if (!Constructor->isInvalidDecl() &&
2730 Constructor->isConvertingConstructor(AllowExplicit)) {
2731 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002732 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2733 ConstructorTmpl->getAccess(),
2734 /*ExplicitArgs*/ 0,
Douglas Gregor4a520a22009-12-14 17:27:33 +00002735 &Initializer, 1, CandidateSet);
2736 else
John McCall86820f52010-01-26 01:37:31 +00002737 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2738 &Initializer, 1, CandidateSet);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002739 }
2740 }
2741 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002742
2743 SourceLocation DeclLoc = Initializer->getLocStart();
2744
Douglas Gregor4a520a22009-12-14 17:27:33 +00002745 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2746 // The type we're converting from is a class type, enumerate its conversion
2747 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002748
Eli Friedman33c2da92009-12-20 22:12:03 +00002749 // We can only enumerate the conversion functions for a complete type; if
2750 // the type isn't complete, simply skip this step.
2751 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2752 CXXRecordDecl *SourceRecordDecl
2753 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002754
John McCalleec51cf2010-01-20 00:46:10 +00002755 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002756 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002757 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002758 E = Conversions->end();
2759 I != E; ++I) {
2760 NamedDecl *D = *I;
2761 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2762 if (isa<UsingShadowDecl>(D))
2763 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2764
2765 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2766 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002767 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002768 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002769 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002770 Conv = cast<CXXConversionDecl>(*I);
2771
2772 if (AllowExplicit || !Conv->isExplicit()) {
2773 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00002774 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2775 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002776 CandidateSet);
2777 else
John McCall86820f52010-01-26 01:37:31 +00002778 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2779 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002780 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002781 }
2782 }
2783 }
2784
Douglas Gregor4a520a22009-12-14 17:27:33 +00002785 // Perform overload resolution. If it fails, return the failed result.
2786 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002787 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002788 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2789 Sequence.SetOverloadFailure(
2790 InitializationSequence::FK_UserConversionOverloadFailed,
2791 Result);
2792 return;
2793 }
John McCall1d318332010-01-12 00:44:57 +00002794
Douglas Gregor4a520a22009-12-14 17:27:33 +00002795 FunctionDecl *Function = Best->Function;
2796
2797 if (isa<CXXConstructorDecl>(Function)) {
2798 // Add the user-defined conversion step. Any cv-qualification conversion is
2799 // subsumed by the initialization.
John McCallb13b7372010-02-01 03:16:54 +00002800 Sequence.AddUserConversionStep(Function, Best->getAccess(), DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002801 return;
2802 }
2803
2804 // Add the user-defined conversion step that calls the conversion function.
2805 QualType ConvType = Function->getResultType().getNonReferenceType();
John McCallb13b7372010-02-01 03:16:54 +00002806 Sequence.AddUserConversionStep(Function, Best->getAccess(), ConvType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002807
2808 // If the conversion following the call to the conversion function is
2809 // interesting, add it as a separate step.
2810 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2811 Best->FinalConversion.Third) {
2812 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002813 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002814 ICS.Standard = Best->FinalConversion;
2815 Sequence.AddConversionSequenceStep(ICS, DestType);
2816 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002817}
2818
2819/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2820/// non-class type to another.
2821static void TryImplicitConversion(Sema &S,
2822 const InitializedEntity &Entity,
2823 const InitializationKind &Kind,
2824 Expr *Initializer,
2825 InitializationSequence &Sequence) {
2826 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002827 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002828 /*SuppressUserConversions=*/true,
2829 /*AllowExplicit=*/false,
2830 /*ForceRValue=*/false,
2831 /*FIXME:InOverloadResolution=*/false,
2832 /*UserCast=*/Kind.isExplicitCast());
2833
John McCall1d318332010-01-12 00:44:57 +00002834 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002835 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2836 return;
2837 }
2838
Douglas Gregord6542d82009-12-22 15:35:07 +00002839 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002840}
2841
2842InitializationSequence::InitializationSequence(Sema &S,
2843 const InitializedEntity &Entity,
2844 const InitializationKind &Kind,
2845 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00002846 unsigned NumArgs)
2847 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002848 ASTContext &Context = S.Context;
2849
2850 // C++0x [dcl.init]p16:
2851 // The semantics of initializers are as follows. The destination type is
2852 // the type of the object or reference being initialized and the source
2853 // type is the type of the initializer expression. The source type is not
2854 // defined when the initializer is a braced-init-list or when it is a
2855 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002856 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002857
2858 if (DestType->isDependentType() ||
2859 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2860 SequenceKind = DependentSequence;
2861 return;
2862 }
2863
2864 QualType SourceType;
2865 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002866 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002867 Initializer = Args[0];
2868 if (!isa<InitListExpr>(Initializer))
2869 SourceType = Initializer->getType();
2870 }
2871
2872 // - If the initializer is a braced-init-list, the object is
2873 // list-initialized (8.5.4).
2874 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2875 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002876 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002877 }
2878
2879 // - If the destination type is a reference type, see 8.5.3.
2880 if (DestType->isReferenceType()) {
2881 // C++0x [dcl.init.ref]p1:
2882 // A variable declared to be a T& or T&&, that is, "reference to type T"
2883 // (8.3.2), shall be initialized by an object, or function, of type T or
2884 // by an object that can be converted into a T.
2885 // (Therefore, multiple arguments are not permitted.)
2886 if (NumArgs != 1)
2887 SetFailed(FK_TooManyInitsForReference);
2888 else
2889 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2890 return;
2891 }
2892
2893 // - If the destination type is an array of characters, an array of
2894 // char16_t, an array of char32_t, or an array of wchar_t, and the
2895 // initializer is a string literal, see 8.5.2.
2896 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2897 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2898 return;
2899 }
2900
2901 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002902 if (Kind.getKind() == InitializationKind::IK_Value ||
2903 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002904 TryValueInitialization(S, Entity, Kind, *this);
2905 return;
2906 }
2907
Douglas Gregor99a2e602009-12-16 01:38:02 +00002908 // Handle default initialization.
2909 if (Kind.getKind() == InitializationKind::IK_Default){
2910 TryDefaultInitialization(S, Entity, Kind, *this);
2911 return;
2912 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002913
Douglas Gregor20093b42009-12-09 23:02:17 +00002914 // - Otherwise, if the destination type is an array, the program is
2915 // ill-formed.
2916 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2917 if (AT->getElementType()->isAnyCharacterType())
2918 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2919 else
2920 SetFailed(FK_ArrayNeedsInitList);
2921
2922 return;
2923 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002924
2925 // Handle initialization in C
2926 if (!S.getLangOptions().CPlusPlus) {
2927 setSequenceKind(CAssignment);
2928 AddCAssignmentStep(DestType);
2929 return;
2930 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002931
2932 // - If the destination type is a (possibly cv-qualified) class type:
2933 if (DestType->isRecordType()) {
2934 // - If the initialization is direct-initialization, or if it is
2935 // copy-initialization where the cv-unqualified version of the
2936 // source type is the same class as, or a derived class of, the
2937 // class of the destination, constructors are considered. [...]
2938 if (Kind.getKind() == InitializationKind::IK_Direct ||
2939 (Kind.getKind() == InitializationKind::IK_Copy &&
2940 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2941 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002942 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00002943 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002944 // - Otherwise (i.e., for the remaining copy-initialization cases),
2945 // user-defined conversion sequences that can convert from the source
2946 // type to the destination type or (when a conversion function is
2947 // used) to a derived class thereof are enumerated as described in
2948 // 13.3.1.4, and the best one is chosen through overload resolution
2949 // (13.3).
2950 else
2951 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2952 return;
2953 }
2954
Douglas Gregor99a2e602009-12-16 01:38:02 +00002955 if (NumArgs > 1) {
2956 SetFailed(FK_TooManyInitsForScalar);
2957 return;
2958 }
2959 assert(NumArgs == 1 && "Zero-argument case handled above");
2960
Douglas Gregor20093b42009-12-09 23:02:17 +00002961 // - Otherwise, if the source type is a (possibly cv-qualified) class
2962 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002963 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002964 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2965 return;
2966 }
2967
2968 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002969 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002970 // conversions (Clause 4) will be used, if necessary, to convert the
2971 // initializer expression to the cv-unqualified version of the
2972 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002973 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002974 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2975}
2976
2977InitializationSequence::~InitializationSequence() {
2978 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2979 StepEnd = Steps.end();
2980 Step != StepEnd; ++Step)
2981 Step->Destroy();
2982}
2983
2984//===----------------------------------------------------------------------===//
2985// Perform initialization
2986//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002987static Sema::AssignmentAction
2988getAssignmentAction(const InitializedEntity &Entity) {
2989 switch(Entity.getKind()) {
2990 case InitializedEntity::EK_Variable:
2991 case InitializedEntity::EK_New:
2992 return Sema::AA_Initializing;
2993
2994 case InitializedEntity::EK_Parameter:
2995 // FIXME: Can we tell when we're sending vs. passing?
2996 return Sema::AA_Passing;
2997
2998 case InitializedEntity::EK_Result:
2999 return Sema::AA_Returning;
3000
3001 case InitializedEntity::EK_Exception:
3002 case InitializedEntity::EK_Base:
3003 llvm_unreachable("No assignment action for C++-specific initialization");
3004 break;
3005
3006 case InitializedEntity::EK_Temporary:
3007 // FIXME: Can we tell apart casting vs. converting?
3008 return Sema::AA_Casting;
3009
3010 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003011 case InitializedEntity::EK_ArrayElement:
3012 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003013 return Sema::AA_Initializing;
3014 }
3015
3016 return Sema::AA_Converting;
3017}
3018
3019static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3020 bool IsCopy) {
3021 switch (Entity.getKind()) {
3022 case InitializedEntity::EK_Result:
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003023 case InitializedEntity::EK_ArrayElement:
3024 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003025 return !IsCopy;
3026
3027 case InitializedEntity::EK_New:
3028 case InitializedEntity::EK_Variable:
3029 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003030 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003031 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003032 return false;
3033
3034 case InitializedEntity::EK_Parameter:
3035 case InitializedEntity::EK_Temporary:
3036 return true;
3037 }
3038
3039 llvm_unreachable("missed an InitializedEntity kind?");
3040}
3041
3042/// \brief If we need to perform an additional copy of the initialized object
3043/// for this kind of entity (e.g., the result of a function or an object being
3044/// thrown), make the copy.
3045static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3046 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003047 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003048 Sema::OwningExprResult CurInit) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003049 Expr *CurInitExpr = (Expr *)CurInit.get();
3050
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003051 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003052
3053 switch (Entity.getKind()) {
3054 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00003055 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003056 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003057 Loc = Entity.getReturnLoc();
3058 break;
3059
3060 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003061 Loc = Entity.getThrowLoc();
3062 break;
3063
3064 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00003065 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003066 Kind.getKind() != InitializationKind::IK_Copy)
3067 return move(CurInit);
3068 Loc = Entity.getDecl()->getLocation();
3069 break;
3070
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003071 case InitializedEntity::EK_ArrayElement:
3072 case InitializedEntity::EK_Member:
3073 if (Entity.getType()->isReferenceType() ||
3074 Kind.getKind() != InitializationKind::IK_Copy)
3075 return move(CurInit);
3076 Loc = CurInitExpr->getLocStart();
3077 break;
3078
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003079 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003080 // FIXME: Do we need this initialization for a parameter?
3081 return move(CurInit);
3082
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003083 case InitializedEntity::EK_New:
3084 case InitializedEntity::EK_Temporary:
3085 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003086 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003087 // We don't need to copy for any of these initialized entities.
3088 return move(CurInit);
3089 }
3090
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003091 CXXRecordDecl *Class = 0;
3092 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3093 Class = cast<CXXRecordDecl>(Record->getDecl());
3094 if (!Class)
3095 return move(CurInit);
3096
3097 // Perform overload resolution using the class's copy constructors.
3098 DeclarationName ConstructorName
3099 = S.Context.DeclarationNames.getCXXConstructorName(
3100 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3101 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003102 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003103 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3104 Con != ConEnd; ++Con) {
3105 // Find the constructor (which may be a template).
3106 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3107 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003108 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003109 continue;
3110
John McCall86820f52010-01-26 01:37:31 +00003111 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
3112 &CurInitExpr, 1, CandidateSet);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003113 }
3114
3115 OverloadCandidateSet::iterator Best;
3116 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3117 case OR_Success:
3118 break;
3119
3120 case OR_No_Viable_Function:
3121 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003122 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003123 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003124 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3125 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003126 return S.ExprError();
3127
3128 case OR_Ambiguous:
3129 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003130 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003131 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003132 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3133 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003134 return S.ExprError();
3135
3136 case OR_Deleted:
3137 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003138 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003139 << CurInitExpr->getSourceRange();
3140 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3141 << Best->Function->isDeleted();
3142 return S.ExprError();
3143 }
3144
3145 CurInit.release();
3146 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3147 cast<CXXConstructorDecl>(Best->Function),
3148 /*Elidable=*/true,
3149 Sema::MultiExprArg(S,
3150 (void**)&CurInitExpr, 1));
3151}
Douglas Gregor20093b42009-12-09 23:02:17 +00003152
3153Action::OwningExprResult
3154InitializationSequence::Perform(Sema &S,
3155 const InitializedEntity &Entity,
3156 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003157 Action::MultiExprArg Args,
3158 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003159 if (SequenceKind == FailedSequence) {
3160 unsigned NumArgs = Args.size();
3161 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3162 return S.ExprError();
3163 }
3164
3165 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003166 // If the declaration is a non-dependent, incomplete array type
3167 // that has an initializer, then its type will be completed once
3168 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003169 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003170 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003171 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003172 if (const IncompleteArrayType *ArrayT
3173 = S.Context.getAsIncompleteArrayType(DeclType)) {
3174 // FIXME: We don't currently have the ability to accurately
3175 // compute the length of an initializer list without
3176 // performing full type-checking of the initializer list
3177 // (since we have to determine where braces are implicitly
3178 // introduced and such). So, we fall back to making the array
3179 // type a dependently-sized array type with no specified
3180 // bound.
3181 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3182 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003183
Douglas Gregord87b61f2009-12-10 17:56:55 +00003184 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003185 if (DeclaratorDecl *DD = Entity.getDecl()) {
3186 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3187 TypeLoc TL = TInfo->getTypeLoc();
3188 if (IncompleteArrayTypeLoc *ArrayLoc
3189 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3190 Brackets = ArrayLoc->getBracketsRange();
3191 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003192 }
3193
3194 *ResultType
3195 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3196 /*NumElts=*/0,
3197 ArrayT->getSizeModifier(),
3198 ArrayT->getIndexTypeCVRQualifiers(),
3199 Brackets);
3200 }
3201
3202 }
3203 }
3204
Eli Friedman08544622009-12-22 02:35:53 +00003205 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003206 return Sema::OwningExprResult(S, Args.release()[0]);
3207
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003208 if (Args.size() == 0)
3209 return S.Owned((Expr *)0);
3210
Douglas Gregor20093b42009-12-09 23:02:17 +00003211 unsigned NumArgs = Args.size();
3212 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3213 SourceLocation(),
3214 (Expr **)Args.release(),
3215 NumArgs,
3216 SourceLocation()));
3217 }
3218
Douglas Gregor99a2e602009-12-16 01:38:02 +00003219 if (SequenceKind == NoInitialization)
3220 return S.Owned((Expr *)0);
3221
Douglas Gregord6542d82009-12-22 15:35:07 +00003222 QualType DestType = Entity.getType().getNonReferenceType();
3223 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003224 // the same as Entity.getDecl()->getType() in cases involving type merging,
3225 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003226 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003227 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003228 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003229
Douglas Gregor99a2e602009-12-16 01:38:02 +00003230 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3231
3232 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3233
3234 // For initialization steps that start with a single initializer,
3235 // grab the only argument out the Args and place it into the "current"
3236 // initializer.
3237 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003238 case SK_ResolveAddressOfOverloadedFunction:
3239 case SK_CastDerivedToBaseRValue:
3240 case SK_CastDerivedToBaseLValue:
3241 case SK_BindReference:
3242 case SK_BindReferenceToTemporary:
3243 case SK_UserConversion:
3244 case SK_QualificationConversionLValue:
3245 case SK_QualificationConversionRValue:
3246 case SK_ConversionSequence:
3247 case SK_ListInitialization:
3248 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003249 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003250 assert(Args.size() == 1);
3251 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3252 if (CurInit.isInvalid())
3253 return S.ExprError();
3254 break;
3255
3256 case SK_ConstructorInitialization:
3257 case SK_ZeroInitialization:
3258 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003259 }
3260
3261 // Walk through the computed steps for the initialization sequence,
3262 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003263 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003264 for (step_iterator Step = step_begin(), StepEnd = step_end();
3265 Step != StepEnd; ++Step) {
3266 if (CurInit.isInvalid())
3267 return S.ExprError();
3268
3269 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003270 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003271
3272 switch (Step->Kind) {
3273 case SK_ResolveAddressOfOverloadedFunction:
3274 // Overload resolution determined which function invoke; update the
3275 // initializer to reflect that choice.
John McCallb13b7372010-02-01 03:16:54 +00003276 // Access control was done in overload resolution.
3277 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
3278 cast<FunctionDecl>(Step->Function.getDecl()));
Douglas Gregor20093b42009-12-09 23:02:17 +00003279 break;
3280
3281 case SK_CastDerivedToBaseRValue:
3282 case SK_CastDerivedToBaseLValue: {
3283 // We have a derived-to-base cast that produces either an rvalue or an
3284 // lvalue. Perform that cast.
3285
3286 // Casts to inaccessible base classes are allowed with C-style casts.
3287 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3288 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3289 CurInitExpr->getLocStart(),
3290 CurInitExpr->getSourceRange(),
3291 IgnoreBaseAccess))
3292 return S.ExprError();
3293
3294 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3295 CastExpr::CK_DerivedToBase,
3296 (Expr*)CurInit.release(),
3297 Step->Kind == SK_CastDerivedToBaseLValue));
3298 break;
3299 }
3300
3301 case SK_BindReference:
3302 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3303 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3304 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003305 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003306 << BitField->getDeclName()
3307 << CurInitExpr->getSourceRange();
3308 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3309 return S.ExprError();
3310 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003311
Anders Carlsson09380262010-01-31 17:18:49 +00003312 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003313 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003314 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3315 << Entity.getType().isVolatileQualified()
3316 << CurInitExpr->getSourceRange();
3317 return S.ExprError();
3318 }
3319
Douglas Gregor20093b42009-12-09 23:02:17 +00003320 // Reference binding does not have any corresponding ASTs.
3321
3322 // Check exception specifications
3323 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3324 return S.ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003325
Douglas Gregor20093b42009-12-09 23:02:17 +00003326 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003327
Douglas Gregor20093b42009-12-09 23:02:17 +00003328 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003329 // Reference binding does not have any corresponding ASTs.
3330
Douglas Gregor20093b42009-12-09 23:02:17 +00003331 // Check exception specifications
3332 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3333 return S.ExprError();
3334
Douglas Gregor20093b42009-12-09 23:02:17 +00003335 break;
3336
3337 case SK_UserConversion: {
3338 // We have a user-defined conversion that invokes either a constructor
3339 // or a conversion function.
3340 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003341 bool IsCopy = false;
John McCallb13b7372010-02-01 03:16:54 +00003342 FunctionDecl *Fn = cast<FunctionDecl>(Step->Function.getDecl());
3343 AccessSpecifier FnAccess = Step->Function.getAccess();
3344 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003345 // Build a call to the selected constructor.
3346 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3347 SourceLocation Loc = CurInitExpr->getLocStart();
3348 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003349
Douglas Gregor20093b42009-12-09 23:02:17 +00003350 // Determine the arguments required to actually perform the constructor
3351 // call.
3352 if (S.CompleteConstructorCall(Constructor,
3353 Sema::MultiExprArg(S,
3354 (void **)&CurInitExpr,
3355 1),
3356 Loc, ConstructorArgs))
3357 return S.ExprError();
3358
3359 // Build the an expression that constructs a temporary.
3360 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3361 move_arg(ConstructorArgs));
3362 if (CurInit.isInvalid())
3363 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003364
3365 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FnAccess);
Douglas Gregor20093b42009-12-09 23:02:17 +00003366
3367 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003368 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3369 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3370 S.IsDerivedFrom(SourceType, Class))
3371 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003372 } else {
3373 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003374 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003375
John McCallb13b7372010-02-01 03:16:54 +00003376 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr,
3377 Conversion, FnAccess);
3378
Douglas Gregor20093b42009-12-09 23:02:17 +00003379 // FIXME: Should we move this initialization into a separate
3380 // derived-to-base conversion? I believe the answer is "no", because
3381 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003382 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
3383 Conversion))
Douglas Gregor20093b42009-12-09 23:02:17 +00003384 return S.ExprError();
3385
3386 // Do a little dance to make sure that CurInit has the proper
3387 // pointer.
3388 CurInit.release();
3389
3390 // Build the actual call to the conversion function.
3391 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3392 if (CurInit.isInvalid() || !CurInit.get())
3393 return S.ExprError();
3394
3395 CastKind = CastExpr::CK_UserDefinedConversion;
3396 }
3397
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003398 if (shouldBindAsTemporary(Entity, IsCopy))
3399 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3400
Douglas Gregor20093b42009-12-09 23:02:17 +00003401 CurInitExpr = CurInit.takeAs<Expr>();
3402 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3403 CastKind,
3404 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003405 false));
3406
3407 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003408 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003409 break;
3410 }
3411
3412 case SK_QualificationConversionLValue:
3413 case SK_QualificationConversionRValue:
3414 // Perform a qualification conversion; these can never go wrong.
3415 S.ImpCastExprToType(CurInitExpr, Step->Type,
3416 CastExpr::CK_NoOp,
3417 Step->Kind == SK_QualificationConversionLValue);
3418 CurInit.release();
3419 CurInit = S.Owned(CurInitExpr);
3420 break;
3421
3422 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003423 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003424 false, false, *Step->ICS))
3425 return S.ExprError();
3426
3427 CurInit.release();
3428 CurInit = S.Owned(CurInitExpr);
3429 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003430
3431 case SK_ListInitialization: {
3432 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3433 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003434 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003435 return S.ExprError();
3436
3437 CurInit.release();
3438 CurInit = S.Owned(InitList);
3439 break;
3440 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003441
3442 case SK_ConstructorInitialization: {
3443 CXXConstructorDecl *Constructor
John McCallb13b7372010-02-01 03:16:54 +00003444 = cast<CXXConstructorDecl>(Step->Function.getDecl());
3445
Douglas Gregor51c56d62009-12-14 20:49:26 +00003446 // Build a call to the selected constructor.
3447 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3448 SourceLocation Loc = Kind.getLocation();
3449
3450 // Determine the arguments required to actually perform the constructor
3451 // call.
3452 if (S.CompleteConstructorCall(Constructor, move(Args),
3453 Loc, ConstructorArgs))
3454 return S.ExprError();
3455
3456 // Build the an expression that constructs a temporary.
Douglas Gregor91be6f52010-03-02 17:18:33 +00003457 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
3458 (Kind.getKind() == InitializationKind::IK_Direct ||
3459 Kind.getKind() == InitializationKind::IK_Value)) {
3460 // An explicitly-constructed temporary, e.g., X(1, 2).
3461 unsigned NumExprs = ConstructorArgs.size();
3462 Expr **Exprs = (Expr **)ConstructorArgs.take();
3463 S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3464 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3465 Constructor,
3466 Entity.getType(),
3467 Kind.getLocation(),
3468 Exprs,
3469 NumExprs,
3470 Kind.getParenRange().getEnd()));
3471 } else
3472 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3473 Constructor,
3474 move_arg(ConstructorArgs),
3475 ConstructorInitRequiresZeroInit,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003476 Entity.getKind() == InitializedEntity::EK_Base);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003477 if (CurInit.isInvalid())
3478 return S.ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003479
3480 // Only check access if all of that succeeded.
3481 S.CheckConstructorAccess(Loc, Constructor, Step->Function.getAccess());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003482
3483 bool Elidable
3484 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3485 if (shouldBindAsTemporary(Entity, Elidable))
3486 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3487
3488 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003489 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003490 break;
3491 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003492
3493 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003494 step_iterator NextStep = Step;
3495 ++NextStep;
3496 if (NextStep != StepEnd &&
3497 NextStep->Kind == SK_ConstructorInitialization) {
3498 // The need for zero-initialization is recorded directly into
3499 // the call to the object's constructor within the next step.
3500 ConstructorInitRequiresZeroInit = true;
3501 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3502 S.getLangOptions().CPlusPlus &&
3503 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003504 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3505 Kind.getRange().getBegin(),
3506 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003507 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003508 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003509 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003510 break;
3511 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003512
3513 case SK_CAssignment: {
3514 QualType SourceType = CurInitExpr->getType();
3515 Sema::AssignConvertType ConvTy =
3516 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003517
3518 // If this is a call, allow conversion to a transparent union.
3519 if (ConvTy != Sema::Compatible &&
3520 Entity.getKind() == InitializedEntity::EK_Parameter &&
3521 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3522 == Sema::Compatible)
3523 ConvTy = Sema::Compatible;
3524
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003525 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3526 Step->Type, SourceType,
3527 CurInitExpr, getAssignmentAction(Entity)))
3528 return S.ExprError();
3529
3530 CurInit.release();
3531 CurInit = S.Owned(CurInitExpr);
3532 break;
3533 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003534
3535 case SK_StringInit: {
3536 QualType Ty = Step->Type;
3537 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3538 break;
3539 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003540 }
3541 }
3542
3543 return move(CurInit);
3544}
3545
3546//===----------------------------------------------------------------------===//
3547// Diagnose initialization failures
3548//===----------------------------------------------------------------------===//
3549bool InitializationSequence::Diagnose(Sema &S,
3550 const InitializedEntity &Entity,
3551 const InitializationKind &Kind,
3552 Expr **Args, unsigned NumArgs) {
3553 if (SequenceKind != FailedSequence)
3554 return false;
3555
Douglas Gregord6542d82009-12-22 15:35:07 +00003556 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003557 switch (Failure) {
3558 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003559 // FIXME: Customize for the initialized entity?
3560 if (NumArgs == 0)
3561 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3562 << DestType.getNonReferenceType();
3563 else // FIXME: diagnostic below could be better!
3564 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3565 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003566 break;
3567
3568 case FK_ArrayNeedsInitList:
3569 case FK_ArrayNeedsInitListOrStringLiteral:
3570 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3571 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3572 break;
3573
3574 case FK_AddressOfOverloadFailed:
3575 S.ResolveAddressOfOverloadedFunction(Args[0],
3576 DestType.getNonReferenceType(),
3577 true);
3578 break;
3579
3580 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003581 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003582 switch (FailedOverloadResult) {
3583 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003584 if (Failure == FK_UserConversionOverloadFailed)
3585 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3586 << Args[0]->getType() << DestType
3587 << Args[0]->getSourceRange();
3588 else
3589 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3590 << DestType << Args[0]->getType()
3591 << Args[0]->getSourceRange();
3592
John McCallcbce6062010-01-12 07:18:19 +00003593 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3594 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003595 break;
3596
3597 case OR_No_Viable_Function:
3598 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3599 << Args[0]->getType() << DestType.getNonReferenceType()
3600 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003601 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3602 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003603 break;
3604
3605 case OR_Deleted: {
3606 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3607 << Args[0]->getType() << DestType.getNonReferenceType()
3608 << Args[0]->getSourceRange();
3609 OverloadCandidateSet::iterator Best;
3610 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3611 Kind.getLocation(),
3612 Best);
3613 if (Ovl == OR_Deleted) {
3614 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3615 << Best->Function->isDeleted();
3616 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003617 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003618 }
3619 break;
3620 }
3621
3622 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003623 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003624 break;
3625 }
3626 break;
3627
3628 case FK_NonConstLValueReferenceBindingToTemporary:
3629 case FK_NonConstLValueReferenceBindingToUnrelated:
3630 S.Diag(Kind.getLocation(),
3631 Failure == FK_NonConstLValueReferenceBindingToTemporary
3632 ? diag::err_lvalue_reference_bind_to_temporary
3633 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00003634 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003635 << DestType.getNonReferenceType()
3636 << Args[0]->getType()
3637 << Args[0]->getSourceRange();
3638 break;
3639
3640 case FK_RValueReferenceBindingToLValue:
3641 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3642 << Args[0]->getSourceRange();
3643 break;
3644
3645 case FK_ReferenceInitDropsQualifiers:
3646 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3647 << DestType.getNonReferenceType()
3648 << Args[0]->getType()
3649 << Args[0]->getSourceRange();
3650 break;
3651
3652 case FK_ReferenceInitFailed:
3653 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3654 << DestType.getNonReferenceType()
3655 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3656 << Args[0]->getType()
3657 << Args[0]->getSourceRange();
3658 break;
3659
3660 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003661 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3662 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003663 << DestType
3664 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3665 << Args[0]->getType()
3666 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003667 break;
3668
3669 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003670 SourceRange R;
3671
3672 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3673 R = SourceRange(InitList->getInit(1)->getLocStart(),
3674 InitList->getLocEnd());
3675 else
3676 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003677
3678 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003679 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003680 break;
3681 }
3682
3683 case FK_ReferenceBindingToInitList:
3684 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3685 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3686 break;
3687
3688 case FK_InitListBadDestinationType:
3689 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3690 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3691 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003692
3693 case FK_ConstructorOverloadFailed: {
3694 SourceRange ArgsRange;
3695 if (NumArgs)
3696 ArgsRange = SourceRange(Args[0]->getLocStart(),
3697 Args[NumArgs - 1]->getLocEnd());
3698
3699 // FIXME: Using "DestType" for the entity we're printing is probably
3700 // bad.
3701 switch (FailedOverloadResult) {
3702 case OR_Ambiguous:
3703 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3704 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003705 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003706 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003707 break;
3708
3709 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003710 if (Kind.getKind() == InitializationKind::IK_Default &&
3711 (Entity.getKind() == InitializedEntity::EK_Base ||
3712 Entity.getKind() == InitializedEntity::EK_Member) &&
3713 isa<CXXConstructorDecl>(S.CurContext)) {
3714 // This is implicit default initialization of a member or
3715 // base within a constructor. If no viable function was
3716 // found, notify the user that she needs to explicitly
3717 // initialize this base/member.
3718 CXXConstructorDecl *Constructor
3719 = cast<CXXConstructorDecl>(S.CurContext);
3720 if (Entity.getKind() == InitializedEntity::EK_Base) {
3721 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3722 << Constructor->isImplicit()
3723 << S.Context.getTypeDeclType(Constructor->getParent())
3724 << /*base=*/0
3725 << Entity.getType();
3726
3727 RecordDecl *BaseDecl
3728 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
3729 ->getDecl();
3730 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
3731 << S.Context.getTagDeclType(BaseDecl);
3732 } else {
3733 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
3734 << Constructor->isImplicit()
3735 << S.Context.getTypeDeclType(Constructor->getParent())
3736 << /*member=*/1
3737 << Entity.getName();
3738 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
3739
3740 if (const RecordType *Record
3741 = Entity.getType()->getAs<RecordType>())
3742 S.Diag(Record->getDecl()->getLocation(),
3743 diag::note_previous_decl)
3744 << S.Context.getTagDeclType(Record->getDecl());
3745 }
3746 break;
3747 }
3748
Douglas Gregor51c56d62009-12-14 20:49:26 +00003749 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3750 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003751 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3752 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003753 break;
3754
3755 case OR_Deleted: {
3756 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3757 << true << DestType << ArgsRange;
3758 OverloadCandidateSet::iterator Best;
3759 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3760 Kind.getLocation(),
3761 Best);
3762 if (Ovl == OR_Deleted) {
3763 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3764 << Best->Function->isDeleted();
3765 } else {
3766 llvm_unreachable("Inconsistent overload resolution?");
3767 }
3768 break;
3769 }
3770
3771 case OR_Success:
3772 llvm_unreachable("Conversion did not fail!");
3773 break;
3774 }
3775 break;
3776 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003777
3778 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003779 if (Entity.getKind() == InitializedEntity::EK_Member &&
3780 isa<CXXConstructorDecl>(S.CurContext)) {
3781 // This is implicit default-initialization of a const member in
3782 // a constructor. Complain that it needs to be explicitly
3783 // initialized.
3784 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
3785 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
3786 << Constructor->isImplicit()
3787 << S.Context.getTypeDeclType(Constructor->getParent())
3788 << /*const=*/1
3789 << Entity.getName();
3790 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
3791 << Entity.getName();
3792 } else {
3793 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3794 << DestType << (bool)DestType->getAs<RecordType>();
3795 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003796 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003797 }
3798
3799 return true;
3800}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003801
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003802void InitializationSequence::dump(llvm::raw_ostream &OS) const {
3803 switch (SequenceKind) {
3804 case FailedSequence: {
3805 OS << "Failed sequence: ";
3806 switch (Failure) {
3807 case FK_TooManyInitsForReference:
3808 OS << "too many initializers for reference";
3809 break;
3810
3811 case FK_ArrayNeedsInitList:
3812 OS << "array requires initializer list";
3813 break;
3814
3815 case FK_ArrayNeedsInitListOrStringLiteral:
3816 OS << "array requires initializer list or string literal";
3817 break;
3818
3819 case FK_AddressOfOverloadFailed:
3820 OS << "address of overloaded function failed";
3821 break;
3822
3823 case FK_ReferenceInitOverloadFailed:
3824 OS << "overload resolution for reference initialization failed";
3825 break;
3826
3827 case FK_NonConstLValueReferenceBindingToTemporary:
3828 OS << "non-const lvalue reference bound to temporary";
3829 break;
3830
3831 case FK_NonConstLValueReferenceBindingToUnrelated:
3832 OS << "non-const lvalue reference bound to unrelated type";
3833 break;
3834
3835 case FK_RValueReferenceBindingToLValue:
3836 OS << "rvalue reference bound to an lvalue";
3837 break;
3838
3839 case FK_ReferenceInitDropsQualifiers:
3840 OS << "reference initialization drops qualifiers";
3841 break;
3842
3843 case FK_ReferenceInitFailed:
3844 OS << "reference initialization failed";
3845 break;
3846
3847 case FK_ConversionFailed:
3848 OS << "conversion failed";
3849 break;
3850
3851 case FK_TooManyInitsForScalar:
3852 OS << "too many initializers for scalar";
3853 break;
3854
3855 case FK_ReferenceBindingToInitList:
3856 OS << "referencing binding to initializer list";
3857 break;
3858
3859 case FK_InitListBadDestinationType:
3860 OS << "initializer list for non-aggregate, non-scalar type";
3861 break;
3862
3863 case FK_UserConversionOverloadFailed:
3864 OS << "overloading failed for user-defined conversion";
3865 break;
3866
3867 case FK_ConstructorOverloadFailed:
3868 OS << "constructor overloading failed";
3869 break;
3870
3871 case FK_DefaultInitOfConst:
3872 OS << "default initialization of a const variable";
3873 break;
3874 }
3875 OS << '\n';
3876 return;
3877 }
3878
3879 case DependentSequence:
3880 OS << "Dependent sequence: ";
3881 return;
3882
3883 case UserDefinedConversion:
3884 OS << "User-defined conversion sequence: ";
3885 break;
3886
3887 case ConstructorInitialization:
3888 OS << "Constructor initialization sequence: ";
3889 break;
3890
3891 case ReferenceBinding:
3892 OS << "Reference binding: ";
3893 break;
3894
3895 case ListInitialization:
3896 OS << "List initialization: ";
3897 break;
3898
3899 case ZeroInitialization:
3900 OS << "Zero initialization\n";
3901 return;
3902
3903 case NoInitialization:
3904 OS << "No initialization\n";
3905 return;
3906
3907 case StandardConversion:
3908 OS << "Standard conversion: ";
3909 break;
3910
3911 case CAssignment:
3912 OS << "C assignment: ";
3913 break;
3914
3915 case StringInit:
3916 OS << "String initialization: ";
3917 break;
3918 }
3919
3920 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
3921 if (S != step_begin()) {
3922 OS << " -> ";
3923 }
3924
3925 switch (S->Kind) {
3926 case SK_ResolveAddressOfOverloadedFunction:
3927 OS << "resolve address of overloaded function";
3928 break;
3929
3930 case SK_CastDerivedToBaseRValue:
3931 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
3932 break;
3933
3934 case SK_CastDerivedToBaseLValue:
3935 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
3936 break;
3937
3938 case SK_BindReference:
3939 OS << "bind reference to lvalue";
3940 break;
3941
3942 case SK_BindReferenceToTemporary:
3943 OS << "bind reference to a temporary";
3944 break;
3945
3946 case SK_UserConversion:
3947 OS << "user-defined conversion via " << S->Function->getNameAsString();
3948 break;
3949
3950 case SK_QualificationConversionRValue:
3951 OS << "qualification conversion (rvalue)";
3952
3953 case SK_QualificationConversionLValue:
3954 OS << "qualification conversion (lvalue)";
3955 break;
3956
3957 case SK_ConversionSequence:
3958 OS << "implicit conversion sequence (";
3959 S->ICS->DebugPrint(); // FIXME: use OS
3960 OS << ")";
3961 break;
3962
3963 case SK_ListInitialization:
3964 OS << "list initialization";
3965 break;
3966
3967 case SK_ConstructorInitialization:
3968 OS << "constructor initialization";
3969 break;
3970
3971 case SK_ZeroInitialization:
3972 OS << "zero initialization";
3973 break;
3974
3975 case SK_CAssignment:
3976 OS << "C assignment";
3977 break;
3978
3979 case SK_StringInit:
3980 OS << "string initialization";
3981 break;
3982 }
3983 }
3984}
3985
3986void InitializationSequence::dump() const {
3987 dump(llvm::errs());
3988}
3989
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003990//===----------------------------------------------------------------------===//
3991// Initialization helper functions
3992//===----------------------------------------------------------------------===//
3993Sema::OwningExprResult
3994Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3995 SourceLocation EqualLoc,
3996 OwningExprResult Init) {
3997 if (Init.isInvalid())
3998 return ExprError();
3999
4000 Expr *InitE = (Expr *)Init.get();
4001 assert(InitE && "No initialization expression?");
4002
4003 if (EqualLoc.isInvalid())
4004 EqualLoc = InitE->getLocStart();
4005
4006 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4007 EqualLoc);
4008 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4009 Init.release();
4010 return Seq.Perform(*this, Entity, Kind,
4011 MultiExprArg(*this, (void**)&InitE, 1));
4012}