blob: 865b4e50bb2b29045298202a4ab9a96bd770a67f [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"
Douglas Gregor05c13a32009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattner79e079d2009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman8718a6a2009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner8879e3b2009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000057
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000064 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 return 0;
67}
68
Chris Lattner79e079d2009-02-24 23:10:27 +000069static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
70 // Get the length of the string as parsed.
71 uint64_t StrLength =
72 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
73
Mike Stump1eb44332009-09-09 15:08:12 +000074
Chris Lattner79e079d2009-02-24 23:10:27 +000075 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000077 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000078 // being initialized to a string literal.
79 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000080 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000081 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000082 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
83 ConstVal,
84 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000085 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086 }
Mike Stump1eb44332009-09-09 15:08:12 +000087
Eli Friedman8718a6a2009-05-29 18:22:49 +000088 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000089
Eli Friedman8718a6a2009-05-29 18:22:49 +000090 // C99 6.7.8p14. We have an array of character type with known size. However,
91 // the size may be smaller or larger than the string we are initializing.
92 // FIXME: Avoid truncation for 64-bit length strings.
93 if (StrLength-1 > CAT->getSize().getZExtValue())
94 S.Diag(Str->getSourceRange().getBegin(),
95 diag::warn_initializer_string_for_char_array_too_long)
96 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000097
Eli Friedman8718a6a2009-05-29 18:22:49 +000098 // Set the type to the actual size that we are initializing. If we have
99 // something like:
100 // char x[1] = "foo";
101 // then this will set the string literal's type to char[1].
102 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000103}
104
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000105//===----------------------------------------------------------------------===//
106// Semantic checking for initializer lists.
107//===----------------------------------------------------------------------===//
108
Douglas Gregor9e80f722009-01-29 01:05:33 +0000109/// @brief Semantic checking for initializer lists.
110///
111/// The InitListChecker class contains a set of routines that each
112/// handle the initialization of a certain kind of entity, e.g.,
113/// arrays, vectors, struct/union types, scalars, etc. The
114/// InitListChecker itself performs a recursive walk of the subobject
115/// structure of the type to be initialized, while stepping through
116/// the initializer list one element at a time. The IList and Index
117/// parameters to each of the Check* routines contain the active
118/// (syntactic) initializer list and the index into that initializer
119/// list that represents the current initializer. Each routine is
120/// responsible for moving that Index forward as it consumes elements.
121///
122/// Each Check* routine also has a StructuredList/StructuredIndex
123/// arguments, which contains the current the "structured" (semantic)
124/// initializer list and the index into that initializer list where we
125/// are copying initializers as we map them over to the semantic
126/// list. Once we have completed our recursive walk of the subobject
127/// structure, we will have constructed a full semantic initializer
128/// list.
129///
130/// C99 designators cause changes in the initializer list traversal,
131/// because they make the initialization "jump" into a specific
132/// subobject and then continue the initialization from that
133/// point. CheckDesignatedInitializer() recursively steps into the
134/// designated subobject and manages backing out the recursion to
135/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000136namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000137class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000138 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000139 bool hadError;
140 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
141 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000143 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000144 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000145 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000146 unsigned &StructuredIndex,
147 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000148 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000149 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000153 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000155 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000156 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000158 unsigned &StructuredIndex,
159 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000160 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000161 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000162 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000163 InitListExpr *StructuredList,
164 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000165 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000170 void CheckReferenceType(const InitializedEntity &Entity,
171 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000172 unsigned &Index,
173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000175 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000176 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000177 InitListExpr *StructuredList,
178 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000179 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000180 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000181 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000182 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000183 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000186 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000188 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000189 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
191 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000192 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000193 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000194 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000195 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 RecordDecl::field_iterator *NextField,
197 llvm::APSInt *NextElementIndex,
198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000201 bool FinishSubobjectInit,
202 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000203 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
204 QualType CurrentObjectType,
205 InitListExpr *StructuredList,
206 unsigned StructuredIndex,
207 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 void UpdateStructuredListElement(InitListExpr *StructuredList,
209 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000210 Expr *expr);
211 int numArrayElements(QualType DeclType);
212 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000213
Douglas Gregord6d37de2009-12-22 00:05:34 +0000214 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
215 const InitializedEntity &ParentEntity,
216 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000217 void FillInValueInitializations(const InitializedEntity &Entity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000220 InitListChecker(Sema &S, const InitializedEntity &Entity,
221 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool HadError() { return hadError; }
223
224 // @brief Retrieves the fully-structured initializer list used for
225 // semantic analysis and code generation.
226 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
227};
Chris Lattner8b419b92009-02-24 22:48:58 +0000228} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000229
Douglas Gregord6d37de2009-12-22 00:05:34 +0000230void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
231 const InitializedEntity &ParentEntity,
232 InitListExpr *ILE,
233 bool &RequiresSecondPass) {
234 SourceLocation Loc = ILE->getSourceRange().getBegin();
235 unsigned NumInits = ILE->getNumInits();
236 InitializedEntity MemberEntity
237 = InitializedEntity::InitializeMember(Field, &ParentEntity);
238 if (Init >= NumInits || !ILE->getInit(Init)) {
239 // FIXME: We probably don't need to handle references
240 // specially here, since value-initialization of references is
241 // handled in InitializationSequence.
242 if (Field->getType()->isReferenceType()) {
243 // C++ [dcl.init.aggr]p9:
244 // If an incomplete or empty initializer-list leaves a
245 // member of reference type uninitialized, the program is
246 // ill-formed.
247 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
248 << Field->getType()
249 << ILE->getSyntacticForm()->getSourceRange();
250 SemaRef.Diag(Field->getLocation(),
251 diag::note_uninit_reference_member);
252 hadError = true;
253 return;
254 }
255
256 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
257 true);
258 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
259 if (!InitSeq) {
260 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
261 hadError = true;
262 return;
263 }
264
265 Sema::OwningExprResult MemberInit
266 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
267 Sema::MultiExprArg(SemaRef, 0, 0));
268 if (MemberInit.isInvalid()) {
269 hadError = true;
270 return;
271 }
272
273 if (hadError) {
274 // Do nothing
275 } else if (Init < NumInits) {
276 ILE->setInit(Init, MemberInit.takeAs<Expr>());
277 } else if (InitSeq.getKind()
278 == InitializationSequence::ConstructorInitialization) {
279 // Value-initialization requires a constructor call, so
280 // extend the initializer list to include the constructor
281 // call and make a note that we'll need to take another pass
282 // through the initializer list.
283 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
284 RequiresSecondPass = true;
285 }
286 } else if (InitListExpr *InnerILE
287 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
288 FillInValueInitializations(MemberEntity, InnerILE,
289 RequiresSecondPass);
290}
291
Douglas Gregor4c678342009-01-28 21:54:33 +0000292/// Recursively replaces NULL values within the given initializer list
293/// with expressions that perform value-initialization of the
294/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000295void
296InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
297 InitListExpr *ILE,
298 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000299 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000300 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000301 SourceLocation Loc = ILE->getSourceRange().getBegin();
302 if (ILE->getSyntacticForm())
303 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Ted Kremenek6217b802009-07-29 21:53:49 +0000305 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000306 if (RType->getDecl()->isUnion() &&
307 ILE->getInitializedFieldInUnion())
308 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
309 Entity, ILE, RequiresSecondPass);
310 else {
311 unsigned Init = 0;
312 for (RecordDecl::field_iterator
313 Field = RType->getDecl()->field_begin(),
314 FieldEnd = RType->getDecl()->field_end();
315 Field != FieldEnd; ++Field) {
316 if (Field->isUnnamedBitfield())
317 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000318
Douglas Gregord6d37de2009-12-22 00:05:34 +0000319 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000320 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000321
322 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
323 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000324 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000325
Douglas Gregord6d37de2009-12-22 00:05:34 +0000326 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000327
Douglas Gregord6d37de2009-12-22 00:05:34 +0000328 // Only look at the first initialization of a union.
329 if (RType->getDecl()->isUnion())
330 break;
331 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000332 }
333
334 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000335 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000336
337 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000339 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000340 unsigned NumInits = ILE->getNumInits();
341 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000342 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000343 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000344 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
345 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000346 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
347 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000348 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000349 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000350 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000351 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
352 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000353 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000354 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000356
Douglas Gregor87fd7032009-02-02 17:43:21 +0000357 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000358 if (hadError)
359 return;
360
Anders Carlssond3d824d2010-01-23 04:34:47 +0000361 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
362 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000363 ElementEntity.setElementIndex(Init);
364
Douglas Gregor87fd7032009-02-02 17:43:21 +0000365 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000366 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
367 true);
368 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
369 if (!InitSeq) {
370 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000371 hadError = true;
372 return;
373 }
374
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000375 Sema::OwningExprResult ElementInit
376 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
377 Sema::MultiExprArg(SemaRef, 0, 0));
378 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000379 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000380 return;
381 }
382
383 if (hadError) {
384 // Do nothing
385 } else if (Init < NumInits) {
386 ILE->setInit(Init, ElementInit.takeAs<Expr>());
387 } else if (InitSeq.getKind()
388 == InitializationSequence::ConstructorInitialization) {
389 // Value-initialization requires a constructor call, so
390 // extend the initializer list to include the constructor
391 // call and make a note that we'll need to take another pass
392 // through the initializer list.
393 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
394 RequiresSecondPass = true;
395 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000396 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000397 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
398 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000399 }
400}
401
Chris Lattner68355a52009-01-29 05:10:57 +0000402
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000403InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
404 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000405 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000406 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000407
Eli Friedmanb85f7072008-05-19 19:16:24 +0000408 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000409 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000410 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000411 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000412 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000413 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000414 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000415
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000416 if (!hadError) {
417 bool RequiresSecondPass = false;
418 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000419 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000420 FillInValueInitializations(Entity, FullyStructuredList,
421 RequiresSecondPass);
422 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000423}
424
425int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000426 // FIXME: use a proper constant
427 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000428 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000429 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000430 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
431 }
432 return maxElements;
433}
434
435int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000436 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000437 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000438 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000439 Field = structDecl->field_begin(),
440 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000441 Field != FieldEnd; ++Field) {
442 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
443 ++InitializableMembers;
444 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000445 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000446 return std::min(InitializableMembers, 1);
447 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000448}
449
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000450void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000451 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000452 QualType T, unsigned &Index,
453 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000454 unsigned &StructuredIndex,
455 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000456 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Steve Naroff0cca7492008-05-01 22:18:59 +0000458 if (T->isArrayType())
459 maxElements = numArrayElements(T);
460 else if (T->isStructureType() || T->isUnionType())
461 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000462 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000463 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000464 else
465 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000466
Eli Friedman402256f2008-05-25 13:49:22 +0000467 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000468 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000469 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000470 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000471 hadError = true;
472 return;
473 }
474
Douglas Gregor4c678342009-01-28 21:54:33 +0000475 // Build a structured initializer list corresponding to this subobject.
476 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000477 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
478 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000479 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
480 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000482
Douglas Gregor4c678342009-01-28 21:54:33 +0000483 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000484 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000485 CheckListElementTypes(Entity, ParentIList, T,
486 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000487 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000488 StructuredSubobjectInitIndex,
489 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000490 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000491 StructuredSubobjectInitList->setType(T);
492
Douglas Gregored8a93d2009-03-01 17:12:46 +0000493 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000494 // range corresponds with the end of the last initializer it used.
495 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000496 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000497 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
498 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
499 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000500}
501
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000502void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000503 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000504 unsigned &Index,
505 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000506 unsigned &StructuredIndex,
507 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000508 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000509 SyntacticToSemantic[IList] = StructuredList;
510 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000511 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
512 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000513 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000515 if (hadError)
516 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000517
Eli Friedman638e1442008-05-25 13:22:35 +0000518 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000519 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000520 if (StructuredIndex == 1 &&
521 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000522 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000523 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000524 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000525 hadError = true;
526 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000527 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000528 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000529 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000530 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000531 // Don't complain for incomplete types, since we'll get an error
532 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000533 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000534 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000535 CurrentObjectType->isArrayType()? 0 :
536 CurrentObjectType->isVectorType()? 1 :
537 CurrentObjectType->isScalarType()? 2 :
538 CurrentObjectType->isUnionType()? 3 :
539 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000540
541 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000542 if (SemaRef.getLangOptions().CPlusPlus) {
543 DK = diag::err_excess_initializers;
544 hadError = true;
545 }
Nate Begeman08634522009-07-07 21:53:06 +0000546 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
547 DK = diag::err_excess_initializers;
548 hadError = true;
549 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000550
Chris Lattner08202542009-02-24 22:50:46 +0000551 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000552 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000553 }
554 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000555
Eli Friedman759f2522009-05-16 11:45:48 +0000556 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000557 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000558 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000559 << CodeModificationHint::CreateRemoval(IList->getLocStart())
560 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000561}
562
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000563void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000564 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000565 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000566 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000567 unsigned &Index,
568 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000569 unsigned &StructuredIndex,
570 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000571 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000572 CheckScalarType(Entity, IList, DeclType, Index,
573 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000574 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000575 CheckVectorType(Entity, IList, DeclType, Index,
576 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000577 } else if (DeclType->isAggregateType()) {
578 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000579 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000580 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000581 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000582 StructuredList, StructuredIndex,
583 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000584 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000585 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000586 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000587 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000588 CheckArrayType(Entity, IList, DeclType, Zero,
589 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000590 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000591 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000592 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000593 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
594 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000596 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000597 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000598 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000599 } else if (DeclType->isRecordType()) {
600 // C++ [dcl.init]p14:
601 // [...] If the class is an aggregate (8.5.1), and the initializer
602 // is a brace-enclosed list, see 8.5.1.
603 //
604 // Note: 8.5.1 is handled below; here, we diagnose the case where
605 // we have an initializer list and a destination type that is not
606 // an aggregate.
607 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000609 << DeclType << IList->getSourceRange();
610 hadError = true;
611 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000612 CheckReferenceType(Entity, IList, DeclType, Index,
613 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000614 } else {
615 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000616 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000617 assert(0 && "Unsupported initializer type");
618 }
619}
620
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000621void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000622 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000623 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000624 unsigned &Index,
625 InitListExpr *StructuredList,
626 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000627 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000628 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
629 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000630 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000631 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000632 = getStructuredSubobjectInit(IList, Index, ElemType,
633 StructuredList, StructuredIndex,
634 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000635 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000636 newStructuredList, newStructuredIndex);
637 ++StructuredIndex;
638 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000639 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
640 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000641 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000642 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000643 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000644 CheckScalarType(Entity, IList, ElemType, Index,
645 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000646 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000647 CheckReferenceType(Entity, IList, ElemType, Index,
648 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000649 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000650 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000651 // C++ [dcl.init.aggr]p12:
652 // All implicit type conversions (clause 4) are considered when
653 // initializing the aggregate member with an ini- tializer from
654 // an initializer-list. If the initializer can initialize a
655 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000656
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000657 // FIXME: Better EqualLoc?
658 InitializationKind Kind =
659 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
660 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
661
662 if (Seq) {
663 Sema::OwningExprResult Result =
664 Seq.Perform(SemaRef, Entity, Kind,
665 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
666 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000667 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000668
669 UpdateStructuredListElement(StructuredList, StructuredIndex,
670 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000671 ++Index;
672 return;
673 }
674
675 // Fall through for subaggregate initialization
676 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000677 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000678 //
679 // The initializer for a structure or union object that has
680 // automatic storage duration shall be either an initializer
681 // list as described below, or a single expression that has
682 // compatible structure or union type. In the latter case, the
683 // initial value of the object, including unnamed members, is
684 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000685 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000686 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000687 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
688 ++Index;
689 return;
690 }
691
692 // Fall through for subaggregate initialization
693 }
694
695 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000696 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000697 // [...] Otherwise, if the member is itself a non-empty
698 // subaggregate, brace elision is assumed and the initializer is
699 // considered for the initialization of the first member of
700 // the subaggregate.
701 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000702 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000703 StructuredIndex);
704 ++StructuredIndex;
705 } else {
706 // We cannot initialize this element, so let
707 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000708 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000709 hadError = true;
710 ++Index;
711 ++StructuredIndex;
712 }
713 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000714}
715
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000716void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000717 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000718 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000719 InitListExpr *StructuredList,
720 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000721 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000722 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000723 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000724 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000725 diag::err_many_braces_around_scalar_init)
726 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000727 hadError = true;
728 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000729 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000730 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000731 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000732 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000733 diag::err_designator_for_scalar_init)
734 << DeclType << expr->getSourceRange();
735 hadError = true;
736 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000737 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000738 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000739 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000740
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000741 Sema::OwningExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000742 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
743 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000744
745 Expr *ResultExpr;
746
747 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000748 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000749 else {
750 ResultExpr = Result.takeAs<Expr>();
751
752 if (ResultExpr != expr) {
753 // The type was promoted, update initializer list.
754 IList->setInit(Index, ResultExpr);
755 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000756 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000757 if (hadError)
758 ++StructuredIndex;
759 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000760 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000761 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000762 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000763 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000764 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000765 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000766 ++Index;
767 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000768 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000769 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000770}
771
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000772void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
773 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000774 unsigned &Index,
775 InitListExpr *StructuredList,
776 unsigned &StructuredIndex) {
777 if (Index < IList->getNumInits()) {
778 Expr *expr = IList->getInit(Index);
779 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000780 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000781 << DeclType << IList->getSourceRange();
782 hadError = true;
783 ++Index;
784 ++StructuredIndex;
785 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000786 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000787
788 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000789 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000790 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000791 /*SuppressUserConversions=*/false,
792 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000793 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000794 hadError = true;
795 else if (savExpr != expr) {
796 // The type was promoted, update initializer list.
797 IList->setInit(Index, expr);
798 }
799 if (hadError)
800 ++StructuredIndex;
801 else
802 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
803 ++Index;
804 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000805 // FIXME: It would be wonderful if we could point at the actual member. In
806 // general, it would be useful to pass location information down the stack,
807 // so that we know the location (or decl) of the "current object" being
808 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000809 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000810 diag::err_init_reference_member_uninitialized)
811 << DeclType
812 << IList->getSourceRange();
813 hadError = true;
814 ++Index;
815 ++StructuredIndex;
816 return;
817 }
818}
819
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000820void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000821 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000822 unsigned &Index,
823 InitListExpr *StructuredList,
824 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000825 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000826 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000827 unsigned maxElements = VT->getNumElements();
828 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000829 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Nate Begeman2ef13e52009-08-10 23:49:36 +0000831 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000832 InitializedEntity ElementEntity =
833 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000834
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000835 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
836 // Don't attempt to go past the end of the init list
837 if (Index >= IList->getNumInits())
838 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000839
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000840 ElementEntity.setElementIndex(Index);
841 CheckSubElementType(ElementEntity, IList, elementType, Index,
842 StructuredList, StructuredIndex);
843 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000844 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000845 InitializedEntity ElementEntity =
846 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
847
Nate Begeman2ef13e52009-08-10 23:49:36 +0000848 // OpenCL initializers allows vectors to be constructed from vectors.
849 for (unsigned i = 0; i < maxElements; ++i) {
850 // Don't attempt to go past the end of the init list
851 if (Index >= IList->getNumInits())
852 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000853
854 ElementEntity.setElementIndex(Index);
855
Nate Begeman2ef13e52009-08-10 23:49:36 +0000856 QualType IType = IList->getInit(Index)->getType();
857 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000858 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000859 StructuredList, StructuredIndex);
860 ++numEltsInit;
861 } else {
John McCall183700f2009-09-21 23:43:11 +0000862 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000863 unsigned numIElts = IVT->getNumElements();
864 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
865 numIElts);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000866 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000867 StructuredList, StructuredIndex);
868 numEltsInit += numIElts;
869 }
870 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000871 }
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Nate Begeman2ef13e52009-08-10 23:49:36 +0000873 // OpenCL & AltiVec require all elements to be initialized.
874 if (numEltsInit != maxElements)
875 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
876 SemaRef.Diag(IList->getSourceRange().getBegin(),
877 diag::err_vector_incorrect_num_initializers)
878 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000879 }
880}
881
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000882void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000883 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000884 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000885 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000886 unsigned &Index,
887 InitListExpr *StructuredList,
888 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000889 // Check for the special-case of initializing an array with a string.
890 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000891 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
892 SemaRef.Context)) {
893 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000894 // We place the string literal directly into the resulting
895 // initializer list. This is the only place where the structure
896 // of the structured initializer list doesn't match exactly,
897 // because doing so would involve allocating one character
898 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000899 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000900 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000901 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000902 return;
903 }
904 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000905 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000906 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000907 // Check for VLAs; in standard C it would be possible to check this
908 // earlier, but I don't know where clang accepts VLAs (gcc accepts
909 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000910 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000911 diag::err_variable_object_no_init)
912 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000913 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000914 ++Index;
915 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000916 return;
917 }
918
Douglas Gregor05c13a32009-01-22 00:58:24 +0000919 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000920 llvm::APSInt maxElements(elementIndex.getBitWidth(),
921 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000922 bool maxElementsKnown = false;
923 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000924 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000925 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000926 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000927 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000928 maxElementsKnown = true;
929 }
930
Chris Lattner08202542009-02-24 22:50:46 +0000931 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000932 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000933 while (Index < IList->getNumInits()) {
934 Expr *Init = IList->getInit(Index);
935 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000936 // If we're not the subobject that matches up with the '{' for
937 // the designator, we shouldn't be handling the
938 // designator. Return immediately.
939 if (!SubobjectIsDesignatorContext)
940 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000941
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000942 // Handle this designated initializer. elementIndex will be
943 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000944 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000945 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000946 StructuredList, StructuredIndex, true,
947 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000948 hadError = true;
949 continue;
950 }
951
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000952 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
953 maxElements.extend(elementIndex.getBitWidth());
954 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
955 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000956 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000957
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000958 // If the array is of incomplete type, keep track of the number of
959 // elements in the initializer.
960 if (!maxElementsKnown && elementIndex > maxElements)
961 maxElements = elementIndex;
962
Douglas Gregor05c13a32009-01-22 00:58:24 +0000963 continue;
964 }
965
966 // If we know the maximum number of elements, and we've already
967 // hit it, stop consuming elements in the initializer list.
968 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000969 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000970
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000971 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000972 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000973 Entity);
974 // Check this element.
975 CheckSubElementType(ElementEntity, IList, elementType, Index,
976 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000977 ++elementIndex;
978
979 // If the array is of incomplete type, keep track of the number of
980 // elements in the initializer.
981 if (!maxElementsKnown && elementIndex > maxElements)
982 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000983 }
Eli Friedman587cbdf2009-05-29 20:17:55 +0000984 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000985 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000986 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000987 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000988 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000989 // Sizing an array implicitly to zero is not allowed by ISO C,
990 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000991 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000992 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000993 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000994
Mike Stump1eb44332009-09-09 15:08:12 +0000995 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000996 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000997 }
998}
999
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001000void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001001 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001002 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001003 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001004 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001005 unsigned &Index,
1006 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001007 unsigned &StructuredIndex,
1008 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001009 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Eli Friedmanb85f7072008-05-19 19:16:24 +00001011 // If the record is invalid, some of it's members are invalid. To avoid
1012 // confusion, we forgo checking the intializer for the entire record.
1013 if (structDecl->isInvalidDecl()) {
1014 hadError = true;
1015 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001016 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001017
1018 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1019 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001020 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001021 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001022 Field != FieldEnd; ++Field) {
1023 if (Field->getDeclName()) {
1024 StructuredList->setInitializedFieldInUnion(*Field);
1025 break;
1026 }
1027 }
1028 return;
1029 }
1030
Douglas Gregor05c13a32009-01-22 00:58:24 +00001031 // If structDecl is a forward declaration, this loop won't do
1032 // anything except look at designated initializers; That's okay,
1033 // because an error should get printed out elsewhere. It might be
1034 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001035 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001036 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001037 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001038 while (Index < IList->getNumInits()) {
1039 Expr *Init = IList->getInit(Index);
1040
1041 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001042 // If we're not the subobject that matches up with the '{' for
1043 // the designator, we shouldn't be handling the
1044 // designator. Return immediately.
1045 if (!SubobjectIsDesignatorContext)
1046 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001047
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001048 // Handle this designated initializer. Field will be updated to
1049 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001050 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001051 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001052 StructuredList, StructuredIndex,
1053 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001054 hadError = true;
1055
Douglas Gregordfb5e592009-02-12 19:00:39 +00001056 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001057 continue;
1058 }
1059
1060 if (Field == FieldEnd) {
1061 // We've run out of fields. We're done.
1062 break;
1063 }
1064
Douglas Gregordfb5e592009-02-12 19:00:39 +00001065 // We've already initialized a member of a union. We're done.
1066 if (InitializedSomething && DeclType->isUnionType())
1067 break;
1068
Douglas Gregor44b43212008-12-11 16:49:14 +00001069 // If we've hit the flexible array member at the end, we're done.
1070 if (Field->getType()->isIncompleteArrayType())
1071 break;
1072
Douglas Gregor0bb76892009-01-29 16:53:55 +00001073 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001074 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001075 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001076 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001077 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001078
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001079 InitializedEntity MemberEntity =
1080 InitializedEntity::InitializeMember(*Field, &Entity);
1081 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1082 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001083 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001084
1085 if (DeclType->isUnionType()) {
1086 // Initialize the first field within the union.
1087 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001088 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001089
1090 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001091 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001092
Mike Stump1eb44332009-09-09 15:08:12 +00001093 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001094 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001095 return;
1096
1097 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001098 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001099 (!isa<InitListExpr>(IList->getInit(Index)) ||
1100 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001101 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001102 diag::err_flexible_array_init_nonempty)
1103 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001104 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001105 << *Field;
1106 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001107 ++Index;
1108 return;
1109 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001110 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001111 diag::ext_flexible_array_init)
1112 << IList->getInit(Index)->getSourceRange().getBegin();
1113 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1114 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001115 }
1116
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001117 InitializedEntity MemberEntity =
1118 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001119
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001120 if (isa<InitListExpr>(IList->getInit(Index)))
1121 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1122 StructuredList, StructuredIndex);
1123 else
1124 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001125 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001126}
Steve Naroff0cca7492008-05-01 22:18:59 +00001127
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001128/// \brief Expand a field designator that refers to a member of an
1129/// anonymous struct or union into a series of field designators that
1130/// refers to the field within the appropriate subobject.
1131///
1132/// Field/FieldIndex will be updated to point to the (new)
1133/// currently-designated field.
1134static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001135 DesignatedInitExpr *DIE,
1136 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001137 FieldDecl *Field,
1138 RecordDecl::field_iterator &FieldIter,
1139 unsigned &FieldIndex) {
1140 typedef DesignatedInitExpr::Designator Designator;
1141
1142 // Build the path from the current object to the member of the
1143 // anonymous struct/union (backwards).
1144 llvm::SmallVector<FieldDecl *, 4> Path;
1145 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001147 // Build the replacement designators.
1148 llvm::SmallVector<Designator, 4> Replacements;
1149 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1150 FI = Path.rbegin(), FIEnd = Path.rend();
1151 FI != FIEnd; ++FI) {
1152 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001153 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001154 DIE->getDesignator(DesigIdx)->getDotLoc(),
1155 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1156 else
1157 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1158 SourceLocation()));
1159 Replacements.back().setField(*FI);
1160 }
1161
1162 // Expand the current designator into the set of replacement
1163 // designators, so we have a full subobject path down to where the
1164 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001165 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001166 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001168 // Update FieldIter/FieldIndex;
1169 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001170 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001171 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001172 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001173 FieldIter != FEnd; ++FieldIter) {
1174 if (FieldIter->isUnnamedBitfield())
1175 continue;
1176
1177 if (*FieldIter == Path.back())
1178 return;
1179
1180 ++FieldIndex;
1181 }
1182
1183 assert(false && "Unable to find anonymous struct/union field");
1184}
1185
Douglas Gregor05c13a32009-01-22 00:58:24 +00001186/// @brief Check the well-formedness of a C99 designated initializer.
1187///
1188/// Determines whether the designated initializer @p DIE, which
1189/// resides at the given @p Index within the initializer list @p
1190/// IList, is well-formed for a current object of type @p DeclType
1191/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001192/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001193/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001194///
1195/// @param IList The initializer list in which this designated
1196/// initializer occurs.
1197///
Douglas Gregor71199712009-04-15 04:56:10 +00001198/// @param DIE The designated initializer expression.
1199///
1200/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001201///
1202/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1203/// into which the designation in @p DIE should refer.
1204///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001205/// @param NextField If non-NULL and the first designator in @p DIE is
1206/// a field, this will be set to the field declaration corresponding
1207/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001208///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001209/// @param NextElementIndex If non-NULL and the first designator in @p
1210/// DIE is an array designator or GNU array-range designator, this
1211/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001212///
1213/// @param Index Index into @p IList where the designated initializer
1214/// @p DIE occurs.
1215///
Douglas Gregor4c678342009-01-28 21:54:33 +00001216/// @param StructuredList The initializer list expression that
1217/// describes all of the subobject initializers in the order they'll
1218/// actually be initialized.
1219///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001220/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001221bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001222InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001223 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001224 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001225 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001226 QualType &CurrentObjectType,
1227 RecordDecl::field_iterator *NextField,
1228 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001229 unsigned &Index,
1230 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001231 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001232 bool FinishSubobjectInit,
1233 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001234 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001235 // Check the actual initialization for the designated object type.
1236 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001237
1238 // Temporarily remove the designator expression from the
1239 // initializer list that the child calls see, so that we don't try
1240 // to re-process the designator.
1241 unsigned OldIndex = Index;
1242 IList->setInit(OldIndex, DIE->getInit());
1243
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001244 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001245 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001246
1247 // Restore the designated initializer expression in the syntactic
1248 // form of the initializer list.
1249 if (IList->getInit(OldIndex) != DIE->getInit())
1250 DIE->setInit(IList->getInit(OldIndex));
1251 IList->setInit(OldIndex, DIE);
1252
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001253 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001254 }
1255
Douglas Gregor71199712009-04-15 04:56:10 +00001256 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001257 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001258 "Need a non-designated initializer list to start from");
1259
Douglas Gregor71199712009-04-15 04:56:10 +00001260 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001261 // Determine the structural initializer list that corresponds to the
1262 // current subobject.
1263 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001264 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001265 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001266 SourceRange(D->getStartLocation(),
1267 DIE->getSourceRange().getEnd()));
1268 assert(StructuredList && "Expected a structured initializer list");
1269
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001270 if (D->isFieldDesignator()) {
1271 // C99 6.7.8p7:
1272 //
1273 // If a designator has the form
1274 //
1275 // . identifier
1276 //
1277 // then the current object (defined below) shall have
1278 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001279 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001280 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001281 if (!RT) {
1282 SourceLocation Loc = D->getDotLoc();
1283 if (Loc.isInvalid())
1284 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001285 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1286 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001287 ++Index;
1288 return true;
1289 }
1290
Douglas Gregor4c678342009-01-28 21:54:33 +00001291 // Note: we perform a linear search of the fields here, despite
1292 // the fact that we have a faster lookup method, because we always
1293 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001294 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001295 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001296 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001297 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001298 Field = RT->getDecl()->field_begin(),
1299 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001300 for (; Field != FieldEnd; ++Field) {
1301 if (Field->isUnnamedBitfield())
1302 continue;
1303
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001304 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001305 break;
1306
1307 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001308 }
1309
Douglas Gregor4c678342009-01-28 21:54:33 +00001310 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001311 // There was no normal field in the struct with the designated
1312 // name. Perform another lookup for this name, which may find
1313 // something that we can't designate (e.g., a member function),
1314 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001315 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001316 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001317 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001318 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001319 // Name lookup didn't find anything. Determine whether this
1320 // was a typo for another field name.
1321 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1322 Sema::LookupMemberName);
1323 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1324 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1325 ReplacementField->getDeclContext()->getLookupContext()
1326 ->Equals(RT->getDecl())) {
1327 SemaRef.Diag(D->getFieldLoc(),
1328 diag::err_field_designator_unknown_suggest)
1329 << FieldName << CurrentObjectType << R.getLookupName()
1330 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1331 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001332 SemaRef.Diag(ReplacementField->getLocation(),
1333 diag::note_previous_decl)
1334 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001335 } else {
1336 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1337 << FieldName << CurrentObjectType;
1338 ++Index;
1339 return true;
1340 }
1341 } else if (!KnownField) {
1342 // Determine whether we found a field at all.
1343 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1344 }
1345
1346 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001347 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001348 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001350 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001351 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001352 ++Index;
1353 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001354 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001355
1356 if (!KnownField &&
1357 cast<RecordDecl>((ReplacementField)->getDeclContext())
1358 ->isAnonymousStructOrUnion()) {
1359 // Handle an field designator that refers to a member of an
1360 // anonymous struct or union.
1361 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1362 ReplacementField,
1363 Field, FieldIndex);
1364 D = DIE->getDesignator(DesigIdx);
1365 } else if (!KnownField) {
1366 // The replacement field comes from typo correction; find it
1367 // in the list of fields.
1368 FieldIndex = 0;
1369 Field = RT->getDecl()->field_begin();
1370 for (; Field != FieldEnd; ++Field) {
1371 if (Field->isUnnamedBitfield())
1372 continue;
1373
1374 if (ReplacementField == *Field ||
1375 Field->getIdentifier() == ReplacementField->getIdentifier())
1376 break;
1377
1378 ++FieldIndex;
1379 }
1380 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001381 } else if (!KnownField &&
1382 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001383 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001384 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1385 Field, FieldIndex);
1386 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001387 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001388
1389 // All of the fields of a union are located at the same place in
1390 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001391 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001392 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001393 StructuredList->setInitializedFieldInUnion(*Field);
1394 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001395
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001396 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001397 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Douglas Gregor4c678342009-01-28 21:54:33 +00001399 // Make sure that our non-designated initializer list has space
1400 // for a subobject corresponding to this field.
1401 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001402 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001403
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001404 // This designator names a flexible array member.
1405 if (Field->getType()->isIncompleteArrayType()) {
1406 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001407 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001408 // We can't designate an object within the flexible array
1409 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001410 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001411 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001412 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001413 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001414 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001415 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001416 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001417 << *Field;
1418 Invalid = true;
1419 }
1420
1421 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1422 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001423 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001424 diag::err_flexible_array_init_needs_braces)
1425 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001426 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001427 << *Field;
1428 Invalid = true;
1429 }
1430
1431 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001432 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001433 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001434 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001435 diag::err_flexible_array_init_nonempty)
1436 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001437 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001438 << *Field;
1439 Invalid = true;
1440 }
1441
1442 if (Invalid) {
1443 ++Index;
1444 return true;
1445 }
1446
1447 // Initialize the array.
1448 bool prevHadError = hadError;
1449 unsigned newStructuredIndex = FieldIndex;
1450 unsigned OldIndex = Index;
1451 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001452
1453 InitializedEntity MemberEntity =
1454 InitializedEntity::InitializeMember(*Field, &Entity);
1455 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001456 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001457
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001458 IList->setInit(OldIndex, DIE);
1459 if (hadError && !prevHadError) {
1460 ++Field;
1461 ++FieldIndex;
1462 if (NextField)
1463 *NextField = Field;
1464 StructuredIndex = FieldIndex;
1465 return true;
1466 }
1467 } else {
1468 // Recurse to check later designated subobjects.
1469 QualType FieldType = (*Field)->getType();
1470 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001471
1472 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001473 InitializedEntity::InitializeMember(*Field, &Entity);
1474 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001475 FieldType, 0, 0, Index,
1476 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001477 true, false))
1478 return true;
1479 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001480
1481 // Find the position of the next field to be initialized in this
1482 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001483 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001484 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001485
1486 // If this the first designator, our caller will continue checking
1487 // the rest of this struct/class/union subobject.
1488 if (IsFirstDesignator) {
1489 if (NextField)
1490 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001491 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001492 return false;
1493 }
1494
Douglas Gregor34e79462009-01-28 23:36:17 +00001495 if (!FinishSubobjectInit)
1496 return false;
1497
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001498 // We've already initialized something in the union; we're done.
1499 if (RT->getDecl()->isUnion())
1500 return hadError;
1501
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001502 // Check the remaining fields within this class/struct/union subobject.
1503 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001504
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001505 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001506 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001507 return hadError && !prevHadError;
1508 }
1509
1510 // C99 6.7.8p6:
1511 //
1512 // If a designator has the form
1513 //
1514 // [ constant-expression ]
1515 //
1516 // then the current object (defined below) shall have array
1517 // type and the expression shall be an integer constant
1518 // expression. If the array is of unknown size, any
1519 // nonnegative value is valid.
1520 //
1521 // Additionally, cope with the GNU extension that permits
1522 // designators of the form
1523 //
1524 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001525 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001526 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001527 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001528 << CurrentObjectType;
1529 ++Index;
1530 return true;
1531 }
1532
1533 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001534 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1535 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001536 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001537 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001538 DesignatedEndIndex = DesignatedStartIndex;
1539 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001540 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001541
Mike Stump1eb44332009-09-09 15:08:12 +00001542
1543 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001544 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001545 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001546 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001547 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001548
Chris Lattner3bf68932009-04-25 21:59:05 +00001549 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001550 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001551 }
1552
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001553 if (isa<ConstantArrayType>(AT)) {
1554 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001555 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1556 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1557 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1558 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1559 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001560 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001561 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001562 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001563 << IndexExpr->getSourceRange();
1564 ++Index;
1565 return true;
1566 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001567 } else {
1568 // Make sure the bit-widths and signedness match.
1569 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1570 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001571 else if (DesignatedStartIndex.getBitWidth() <
1572 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001573 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1574 DesignatedStartIndex.setIsUnsigned(true);
1575 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Douglas Gregor4c678342009-01-28 21:54:33 +00001578 // Make sure that our non-designated initializer list has space
1579 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001580 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001581 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001582 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001583
Douglas Gregor34e79462009-01-28 23:36:17 +00001584 // Repeatedly perform subobject initializations in the range
1585 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001586
Douglas Gregor34e79462009-01-28 23:36:17 +00001587 // Move to the next designator
1588 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1589 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001590
1591 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001592 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001593
Douglas Gregor34e79462009-01-28 23:36:17 +00001594 while (DesignatedStartIndex <= DesignatedEndIndex) {
1595 // Recurse to check later designated subobjects.
1596 QualType ElementType = AT->getElementType();
1597 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001598
1599 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001600 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001601 ElementType, 0, 0, Index,
1602 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001603 (DesignatedStartIndex == DesignatedEndIndex),
1604 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001605 return true;
1606
1607 // Move to the next index in the array that we'll be initializing.
1608 ++DesignatedStartIndex;
1609 ElementIndex = DesignatedStartIndex.getZExtValue();
1610 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001611
1612 // If this the first designator, our caller will continue checking
1613 // the rest of this array subobject.
1614 if (IsFirstDesignator) {
1615 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001616 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001617 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001618 return false;
1619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Douglas Gregor34e79462009-01-28 23:36:17 +00001621 if (!FinishSubobjectInit)
1622 return false;
1623
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001624 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001625 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001626 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001627 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001628 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001629 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001630}
1631
Douglas Gregor4c678342009-01-28 21:54:33 +00001632// Get the structured initializer list for a subobject of type
1633// @p CurrentObjectType.
1634InitListExpr *
1635InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1636 QualType CurrentObjectType,
1637 InitListExpr *StructuredList,
1638 unsigned StructuredIndex,
1639 SourceRange InitRange) {
1640 Expr *ExistingInit = 0;
1641 if (!StructuredList)
1642 ExistingInit = SyntacticToSemantic[IList];
1643 else if (StructuredIndex < StructuredList->getNumInits())
1644 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Douglas Gregor4c678342009-01-28 21:54:33 +00001646 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1647 return Result;
1648
1649 if (ExistingInit) {
1650 // We are creating an initializer list that initializes the
1651 // subobjects of the current object, but there was already an
1652 // initialization that completely initialized the current
1653 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001654 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001655 // struct X { int a, b; };
1656 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001657 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001658 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1659 // designated initializer re-initializes the whole
1660 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001661 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001662 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001663 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001664 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001665 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001666 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001667 << ExistingInit->getSourceRange();
1668 }
1669
Mike Stump1eb44332009-09-09 15:08:12 +00001670 InitListExpr *Result
1671 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001672 InitRange.getEnd());
1673
Douglas Gregor4c678342009-01-28 21:54:33 +00001674 Result->setType(CurrentObjectType);
1675
Douglas Gregorfa219202009-03-20 23:58:33 +00001676 // Pre-allocate storage for the structured initializer list.
1677 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001678 unsigned NumInits = 0;
1679 if (!StructuredList)
1680 NumInits = IList->getNumInits();
1681 else if (Index < IList->getNumInits()) {
1682 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1683 NumInits = SubList->getNumInits();
1684 }
1685
Mike Stump1eb44332009-09-09 15:08:12 +00001686 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001687 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1688 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1689 NumElements = CAType->getSize().getZExtValue();
1690 // Simple heuristic so that we don't allocate a very large
1691 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001692 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001693 NumElements = 0;
1694 }
John McCall183700f2009-09-21 23:43:11 +00001695 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001696 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001697 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001698 RecordDecl *RDecl = RType->getDecl();
1699 if (RDecl->isUnion())
1700 NumElements = 1;
1701 else
Mike Stump1eb44332009-09-09 15:08:12 +00001702 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001703 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001704 }
1705
Douglas Gregor08457732009-03-21 18:13:52 +00001706 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001707 NumElements = IList->getNumInits();
1708
1709 Result->reserveInits(NumElements);
1710
Douglas Gregor4c678342009-01-28 21:54:33 +00001711 // Link this new initializer list into the structured initializer
1712 // lists.
1713 if (StructuredList)
1714 StructuredList->updateInit(StructuredIndex, Result);
1715 else {
1716 Result->setSyntacticForm(IList);
1717 SyntacticToSemantic[IList] = Result;
1718 }
1719
1720 return Result;
1721}
1722
1723/// Update the initializer at index @p StructuredIndex within the
1724/// structured initializer list to the value @p expr.
1725void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1726 unsigned &StructuredIndex,
1727 Expr *expr) {
1728 // No structured initializer list to update
1729 if (!StructuredList)
1730 return;
1731
1732 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1733 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001734 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001735 diag::warn_initializer_overrides)
1736 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001737 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001738 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001739 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001740 << PrevInit->getSourceRange();
1741 }
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Douglas Gregor4c678342009-01-28 21:54:33 +00001743 ++StructuredIndex;
1744}
1745
Douglas Gregor05c13a32009-01-22 00:58:24 +00001746/// Check that the given Index expression is a valid array designator
1747/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001748/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001749/// and produces a reasonable diagnostic if there is a
1750/// failure. Returns true if there was an error, false otherwise. If
1751/// everything went okay, Value will receive the value of the constant
1752/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001753static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001754CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001755 SourceLocation Loc = Index->getSourceRange().getBegin();
1756
1757 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001758 if (S.VerifyIntegerConstantExpression(Index, &Value))
1759 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001760
Chris Lattner3bf68932009-04-25 21:59:05 +00001761 if (Value.isSigned() && Value.isNegative())
1762 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001763 << Value.toString(10) << Index->getSourceRange();
1764
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001765 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001766 return false;
1767}
1768
1769Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1770 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001771 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001772 OwningExprResult Init) {
1773 typedef DesignatedInitExpr::Designator ASTDesignator;
1774
1775 bool Invalid = false;
1776 llvm::SmallVector<ASTDesignator, 32> Designators;
1777 llvm::SmallVector<Expr *, 32> InitExpressions;
1778
1779 // Build designators and check array designator expressions.
1780 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1781 const Designator &D = Desig.getDesignator(Idx);
1782 switch (D.getKind()) {
1783 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001784 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001785 D.getFieldLoc()));
1786 break;
1787
1788 case Designator::ArrayDesignator: {
1789 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1790 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001791 if (!Index->isTypeDependent() &&
1792 !Index->isValueDependent() &&
1793 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001794 Invalid = true;
1795 else {
1796 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001797 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001798 D.getRBracketLoc()));
1799 InitExpressions.push_back(Index);
1800 }
1801 break;
1802 }
1803
1804 case Designator::ArrayRangeDesignator: {
1805 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1806 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1807 llvm::APSInt StartValue;
1808 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001809 bool StartDependent = StartIndex->isTypeDependent() ||
1810 StartIndex->isValueDependent();
1811 bool EndDependent = EndIndex->isTypeDependent() ||
1812 EndIndex->isValueDependent();
1813 if ((!StartDependent &&
1814 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1815 (!EndDependent &&
1816 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001817 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001818 else {
1819 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001820 if (StartDependent || EndDependent) {
1821 // Nothing to compute.
1822 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001823 EndValue.extend(StartValue.getBitWidth());
1824 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1825 StartValue.extend(EndValue.getBitWidth());
1826
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001827 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001828 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001829 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001830 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1831 Invalid = true;
1832 } else {
1833 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001834 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001835 D.getEllipsisLoc(),
1836 D.getRBracketLoc()));
1837 InitExpressions.push_back(StartIndex);
1838 InitExpressions.push_back(EndIndex);
1839 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001840 }
1841 break;
1842 }
1843 }
1844 }
1845
1846 if (Invalid || Init.isInvalid())
1847 return ExprError();
1848
1849 // Clear out the expressions within the designation.
1850 Desig.ClearExprs(*this);
1851
1852 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001853 = DesignatedInitExpr::Create(Context,
1854 Designators.data(), Designators.size(),
1855 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001856 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001857 return Owned(DIE);
1858}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001859
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001860bool Sema::CheckInitList(const InitializedEntity &Entity,
1861 InitListExpr *&InitList, QualType &DeclType) {
1862 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001863 if (!CheckInitList.HadError())
1864 InitList = CheckInitList.getFullyStructuredList();
1865
1866 return CheckInitList.HadError();
1867}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001868
Douglas Gregor20093b42009-12-09 23:02:17 +00001869//===----------------------------------------------------------------------===//
1870// Initialization entity
1871//===----------------------------------------------------------------------===//
1872
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001873InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1874 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001875 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001876{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001877 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1878 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001879 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001880 } else {
1881 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001882 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001883 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001884}
1885
1886InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1887 CXXBaseSpecifier *Base)
1888{
1889 InitializedEntity Result;
1890 Result.Kind = EK_Base;
1891 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001892 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001893 return Result;
1894}
1895
Douglas Gregor99a2e602009-12-16 01:38:02 +00001896DeclarationName InitializedEntity::getName() const {
1897 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001898 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001899 if (!VariableOrMember)
1900 return DeclarationName();
1901 // Fall through
1902
1903 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001904 case EK_Member:
1905 return VariableOrMember->getDeclName();
1906
1907 case EK_Result:
1908 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001909 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001910 case EK_Temporary:
1911 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001912 case EK_ArrayElement:
1913 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001914 return DeclarationName();
1915 }
1916
1917 // Silence GCC warning
1918 return DeclarationName();
1919}
1920
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001921DeclaratorDecl *InitializedEntity::getDecl() const {
1922 switch (getKind()) {
1923 case EK_Variable:
1924 case EK_Parameter:
1925 case EK_Member:
1926 return VariableOrMember;
1927
1928 case EK_Result:
1929 case EK_Exception:
1930 case EK_New:
1931 case EK_Temporary:
1932 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001933 case EK_ArrayElement:
1934 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001935 return 0;
1936 }
1937
1938 // Silence GCC warning
1939 return 0;
1940}
1941
Douglas Gregor20093b42009-12-09 23:02:17 +00001942//===----------------------------------------------------------------------===//
1943// Initialization sequence
1944//===----------------------------------------------------------------------===//
1945
1946void InitializationSequence::Step::Destroy() {
1947 switch (Kind) {
1948 case SK_ResolveAddressOfOverloadedFunction:
1949 case SK_CastDerivedToBaseRValue:
1950 case SK_CastDerivedToBaseLValue:
1951 case SK_BindReference:
1952 case SK_BindReferenceToTemporary:
1953 case SK_UserConversion:
1954 case SK_QualificationConversionRValue:
1955 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001956 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001957 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001958 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001959 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001960 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001961 break;
1962
1963 case SK_ConversionSequence:
1964 delete ICS;
1965 }
1966}
1967
1968void InitializationSequence::AddAddressOverloadResolutionStep(
1969 FunctionDecl *Function) {
1970 Step S;
1971 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1972 S.Type = Function->getType();
1973 S.Function = Function;
1974 Steps.push_back(S);
1975}
1976
1977void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1978 bool IsLValue) {
1979 Step S;
1980 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1981 S.Type = BaseType;
1982 Steps.push_back(S);
1983}
1984
1985void InitializationSequence::AddReferenceBindingStep(QualType T,
1986 bool BindingTemporary) {
1987 Step S;
1988 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1989 S.Type = T;
1990 Steps.push_back(S);
1991}
1992
Eli Friedman03981012009-12-11 02:42:07 +00001993void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1994 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001995 Step S;
1996 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00001997 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00001998 S.Function = Function;
1999 Steps.push_back(S);
2000}
2001
2002void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2003 bool IsLValue) {
2004 Step S;
2005 S.Kind = IsLValue? SK_QualificationConversionLValue
2006 : SK_QualificationConversionRValue;
2007 S.Type = Ty;
2008 Steps.push_back(S);
2009}
2010
2011void InitializationSequence::AddConversionSequenceStep(
2012 const ImplicitConversionSequence &ICS,
2013 QualType T) {
2014 Step S;
2015 S.Kind = SK_ConversionSequence;
2016 S.Type = T;
2017 S.ICS = new ImplicitConversionSequence(ICS);
2018 Steps.push_back(S);
2019}
2020
Douglas Gregord87b61f2009-12-10 17:56:55 +00002021void InitializationSequence::AddListInitializationStep(QualType T) {
2022 Step S;
2023 S.Kind = SK_ListInitialization;
2024 S.Type = T;
2025 Steps.push_back(S);
2026}
2027
Douglas Gregor51c56d62009-12-14 20:49:26 +00002028void
2029InitializationSequence::AddConstructorInitializationStep(
2030 CXXConstructorDecl *Constructor,
2031 QualType T) {
2032 Step S;
2033 S.Kind = SK_ConstructorInitialization;
2034 S.Type = T;
2035 S.Function = Constructor;
2036 Steps.push_back(S);
2037}
2038
Douglas Gregor71d17402009-12-15 00:01:57 +00002039void InitializationSequence::AddZeroInitializationStep(QualType T) {
2040 Step S;
2041 S.Kind = SK_ZeroInitialization;
2042 S.Type = T;
2043 Steps.push_back(S);
2044}
2045
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002046void InitializationSequence::AddCAssignmentStep(QualType T) {
2047 Step S;
2048 S.Kind = SK_CAssignment;
2049 S.Type = T;
2050 Steps.push_back(S);
2051}
2052
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002053void InitializationSequence::AddStringInitStep(QualType T) {
2054 Step S;
2055 S.Kind = SK_StringInit;
2056 S.Type = T;
2057 Steps.push_back(S);
2058}
2059
Douglas Gregor20093b42009-12-09 23:02:17 +00002060void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2061 OverloadingResult Result) {
2062 SequenceKind = FailedSequence;
2063 this->Failure = Failure;
2064 this->FailedOverloadResult = Result;
2065}
2066
2067//===----------------------------------------------------------------------===//
2068// Attempt initialization
2069//===----------------------------------------------------------------------===//
2070
2071/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002072static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002073 const InitializedEntity &Entity,
2074 const InitializationKind &Kind,
2075 InitListExpr *InitList,
2076 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002077 // FIXME: We only perform rudimentary checking of list
2078 // initializations at this point, then assume that any list
2079 // initialization of an array, aggregate, or scalar will be
2080 // well-formed. We we actually "perform" list initialization, we'll
2081 // do all of the necessary checking. C++0x initializer lists will
2082 // force us to perform more checking here.
2083 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2084
Douglas Gregord6542d82009-12-22 15:35:07 +00002085 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002086
2087 // C++ [dcl.init]p13:
2088 // If T is a scalar type, then a declaration of the form
2089 //
2090 // T x = { a };
2091 //
2092 // is equivalent to
2093 //
2094 // T x = a;
2095 if (DestType->isScalarType()) {
2096 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2097 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2098 return;
2099 }
2100
2101 // Assume scalar initialization from a single value works.
2102 } else if (DestType->isAggregateType()) {
2103 // Assume aggregate initialization works.
2104 } else if (DestType->isVectorType()) {
2105 // Assume vector initialization works.
2106 } else if (DestType->isReferenceType()) {
2107 // FIXME: C++0x defines behavior for this.
2108 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2109 return;
2110 } else if (DestType->isRecordType()) {
2111 // FIXME: C++0x defines behavior for this
2112 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2113 }
2114
2115 // Add a general "list initialization" step.
2116 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002117}
2118
2119/// \brief Try a reference initialization that involves calling a conversion
2120/// function.
2121///
2122/// FIXME: look intos DRs 656, 896
2123static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2124 const InitializedEntity &Entity,
2125 const InitializationKind &Kind,
2126 Expr *Initializer,
2127 bool AllowRValues,
2128 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002129 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002130 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2131 QualType T1 = cv1T1.getUnqualifiedType();
2132 QualType cv2T2 = Initializer->getType();
2133 QualType T2 = cv2T2.getUnqualifiedType();
2134
2135 bool DerivedToBase;
2136 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2137 T1, T2, DerivedToBase) &&
2138 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002139 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002140
2141 // Build the candidate set directly in the initialization sequence
2142 // structure, so that it will persist if we fail.
2143 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2144 CandidateSet.clear();
2145
2146 // Determine whether we are allowed to call explicit constructors or
2147 // explicit conversion operators.
2148 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2149
2150 const RecordType *T1RecordType = 0;
2151 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2152 // The type we're converting to is a class type. Enumerate its constructors
2153 // to see if there is a suitable conversion.
2154 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2155
2156 DeclarationName ConstructorName
2157 = S.Context.DeclarationNames.getCXXConstructorName(
2158 S.Context.getCanonicalType(T1).getUnqualifiedType());
2159 DeclContext::lookup_iterator Con, ConEnd;
2160 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2161 Con != ConEnd; ++Con) {
2162 // Find the constructor (which may be a template).
2163 CXXConstructorDecl *Constructor = 0;
2164 FunctionTemplateDecl *ConstructorTmpl
2165 = dyn_cast<FunctionTemplateDecl>(*Con);
2166 if (ConstructorTmpl)
2167 Constructor = cast<CXXConstructorDecl>(
2168 ConstructorTmpl->getTemplatedDecl());
2169 else
2170 Constructor = cast<CXXConstructorDecl>(*Con);
2171
2172 if (!Constructor->isInvalidDecl() &&
2173 Constructor->isConvertingConstructor(AllowExplicit)) {
2174 if (ConstructorTmpl)
2175 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2176 &Initializer, 1, CandidateSet);
2177 else
2178 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2179 }
2180 }
2181 }
2182
2183 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2184 // The type we're converting from is a class type, enumerate its conversion
2185 // functions.
2186 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2187
2188 // Determine the type we are converting to. If we are allowed to
2189 // convert to an rvalue, take the type that the destination type
2190 // refers to.
2191 QualType ToType = AllowRValues? cv1T1 : DestType;
2192
John McCalleec51cf2010-01-20 00:46:10 +00002193 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002194 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002195 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2196 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002197 NamedDecl *D = *I;
2198 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2199 if (isa<UsingShadowDecl>(D))
2200 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2201
2202 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2203 CXXConversionDecl *Conv;
2204 if (ConvTemplate)
2205 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2206 else
2207 Conv = cast<CXXConversionDecl>(*I);
2208
2209 // If the conversion function doesn't return a reference type,
2210 // it can't be considered for this conversion unless we're allowed to
2211 // consider rvalues.
2212 // FIXME: Do we need to make sure that we only consider conversion
2213 // candidates with reference-compatible results? That might be needed to
2214 // break recursion.
2215 if ((AllowExplicit || !Conv->isExplicit()) &&
2216 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2217 if (ConvTemplate)
2218 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2219 ToType, CandidateSet);
2220 else
2221 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2222 CandidateSet);
2223 }
2224 }
2225 }
2226
2227 SourceLocation DeclLoc = Initializer->getLocStart();
2228
2229 // Perform overload resolution. If it fails, return the failed result.
2230 OverloadCandidateSet::iterator Best;
2231 if (OverloadingResult Result
2232 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2233 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002234
Douglas Gregor20093b42009-12-09 23:02:17 +00002235 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002236
2237 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002238 if (isa<CXXConversionDecl>(Function))
2239 T2 = Function->getResultType();
2240 else
2241 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002242
2243 // Add the user-defined conversion step.
2244 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2245
2246 // Determine whether we need to perform derived-to-base or
2247 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002248 bool NewDerivedToBase = false;
2249 Sema::ReferenceCompareResult NewRefRelationship
2250 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2251 NewDerivedToBase);
2252 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2253 "Overload resolution picked a bad conversion function");
2254 (void)NewRefRelationship;
2255 if (NewDerivedToBase)
2256 Sequence.AddDerivedToBaseCastStep(
2257 S.Context.getQualifiedType(T1,
2258 T2.getNonReferenceType().getQualifiers()),
2259 /*isLValue=*/true);
2260
2261 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2262 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2263
2264 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2265 return OR_Success;
2266}
2267
2268/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2269static void TryReferenceInitialization(Sema &S,
2270 const InitializedEntity &Entity,
2271 const InitializationKind &Kind,
2272 Expr *Initializer,
2273 InitializationSequence &Sequence) {
2274 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2275
Douglas Gregord6542d82009-12-22 15:35:07 +00002276 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002277 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002278 Qualifiers T1Quals;
2279 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002280 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002281 Qualifiers T2Quals;
2282 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002283 SourceLocation DeclLoc = Initializer->getLocStart();
2284
2285 // If the initializer is the address of an overloaded function, try
2286 // to resolve the overloaded function. If all goes well, T2 is the
2287 // type of the resulting function.
2288 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2289 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2290 T1,
2291 false);
2292 if (!Fn) {
2293 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2294 return;
2295 }
2296
2297 Sequence.AddAddressOverloadResolutionStep(Fn);
2298 cv2T2 = Fn->getType();
2299 T2 = cv2T2.getUnqualifiedType();
2300 }
2301
2302 // FIXME: Rvalue references
2303 bool ForceRValue = false;
2304
2305 // Compute some basic properties of the types and the initializer.
2306 bool isLValueRef = DestType->isLValueReferenceType();
2307 bool isRValueRef = !isLValueRef;
2308 bool DerivedToBase = false;
2309 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2310 Initializer->isLvalue(S.Context);
2311 Sema::ReferenceCompareResult RefRelationship
2312 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2313
2314 // C++0x [dcl.init.ref]p5:
2315 // A reference to type "cv1 T1" is initialized by an expression of type
2316 // "cv2 T2" as follows:
2317 //
2318 // - If the reference is an lvalue reference and the initializer
2319 // expression
2320 OverloadingResult ConvOvlResult = OR_Success;
2321 if (isLValueRef) {
2322 if (InitLvalue == Expr::LV_Valid &&
2323 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2324 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2325 // reference-compatible with "cv2 T2," or
2326 //
2327 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2328 // bit-field when we're determining whether the reference initialization
2329 // can occur. This property will be checked by PerformInitialization.
2330 if (DerivedToBase)
2331 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002332 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002333 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002334 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002335 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2336 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2337 return;
2338 }
2339
2340 // - has a class type (i.e., T2 is a class type), where T1 is not
2341 // reference-related to T2, and can be implicitly converted to an
2342 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2343 // with "cv3 T3" (this conversion is selected by enumerating the
2344 // applicable conversion functions (13.3.1.6) and choosing the best
2345 // one through overload resolution (13.3)),
2346 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2347 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2348 Initializer,
2349 /*AllowRValues=*/false,
2350 Sequence);
2351 if (ConvOvlResult == OR_Success)
2352 return;
John McCall1d318332010-01-12 00:44:57 +00002353 if (ConvOvlResult != OR_No_Viable_Function) {
2354 Sequence.SetOverloadFailure(
2355 InitializationSequence::FK_ReferenceInitOverloadFailed,
2356 ConvOvlResult);
2357 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002358 }
2359 }
2360
2361 // - Otherwise, the reference shall be an lvalue reference to a
2362 // non-volatile const type (i.e., cv1 shall be const), or the reference
2363 // shall be an rvalue reference and the initializer expression shall
2364 // be an rvalue.
Chandler Carruth5535c382010-01-12 20:32:25 +00002365 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002366 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2367 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2368 Sequence.SetOverloadFailure(
2369 InitializationSequence::FK_ReferenceInitOverloadFailed,
2370 ConvOvlResult);
2371 else if (isLValueRef)
2372 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2373 ? (RefRelationship == Sema::Ref_Related
2374 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2375 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2376 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2377 else
2378 Sequence.SetFailed(
2379 InitializationSequence::FK_RValueReferenceBindingToLValue);
2380
2381 return;
2382 }
2383
2384 // - If T1 and T2 are class types and
2385 if (T1->isRecordType() && T2->isRecordType()) {
2386 // - the initializer expression is an rvalue and "cv1 T1" is
2387 // reference-compatible with "cv2 T2", or
2388 if (InitLvalue != Expr::LV_Valid &&
2389 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2390 if (DerivedToBase)
2391 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002392 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002393 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002394 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002395 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2396 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2397 return;
2398 }
2399
2400 // - T1 is not reference-related to T2 and the initializer expression
2401 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2402 // conversion is selected by enumerating the applicable conversion
2403 // functions (13.3.1.6) and choosing the best one through overload
2404 // resolution (13.3)),
2405 if (RefRelationship == Sema::Ref_Incompatible) {
2406 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2407 Kind, Initializer,
2408 /*AllowRValues=*/true,
2409 Sequence);
2410 if (ConvOvlResult)
2411 Sequence.SetOverloadFailure(
2412 InitializationSequence::FK_ReferenceInitOverloadFailed,
2413 ConvOvlResult);
2414
2415 return;
2416 }
2417
2418 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2419 return;
2420 }
2421
2422 // - If the initializer expression is an rvalue, with T2 an array type,
2423 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2424 // is bound to the object represented by the rvalue (see 3.10).
2425 // FIXME: How can an array type be reference-compatible with anything?
2426 // Don't we mean the element types of T1 and T2?
2427
2428 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2429 // from the initializer expression using the rules for a non-reference
2430 // copy initialization (8.5). The reference is then bound to the
2431 // temporary. [...]
2432 // Determine whether we are allowed to call explicit constructors or
2433 // explicit conversion operators.
2434 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2435 ImplicitConversionSequence ICS
2436 = S.TryImplicitConversion(Initializer, cv1T1,
2437 /*SuppressUserConversions=*/false, AllowExplicit,
2438 /*ForceRValue=*/false,
2439 /*FIXME:InOverloadResolution=*/false,
2440 /*UserCast=*/Kind.isExplicitCast());
2441
John McCall1d318332010-01-12 00:44:57 +00002442 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002443 // FIXME: Use the conversion function set stored in ICS to turn
2444 // this into an overloading ambiguity diagnostic. However, we need
2445 // to keep that set as an OverloadCandidateSet rather than as some
2446 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002447 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2448 Sequence.SetOverloadFailure(
2449 InitializationSequence::FK_ReferenceInitOverloadFailed,
2450 ConvOvlResult);
2451 else
2452 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002453 return;
2454 }
2455
2456 // [...] If T1 is reference-related to T2, cv1 must be the
2457 // same cv-qualification as, or greater cv-qualification
2458 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002459 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2460 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002461 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002462 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002463 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2464 return;
2465 }
2466
2467 // Perform the actual conversion.
2468 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2469 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2470 return;
2471}
2472
2473/// \brief Attempt character array initialization from a string literal
2474/// (C++ [dcl.init.string], C99 6.7.8).
2475static void TryStringLiteralInitialization(Sema &S,
2476 const InitializedEntity &Entity,
2477 const InitializationKind &Kind,
2478 Expr *Initializer,
2479 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002480 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002481 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002482}
2483
Douglas Gregor20093b42009-12-09 23:02:17 +00002484/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2485/// enumerates the constructors of the initialized entity and performs overload
2486/// resolution to select the best.
2487static void TryConstructorInitialization(Sema &S,
2488 const InitializedEntity &Entity,
2489 const InitializationKind &Kind,
2490 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002491 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002492 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002493 if (Kind.getKind() == InitializationKind::IK_Copy)
2494 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2495 else
2496 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002497
2498 // Build the candidate set directly in the initialization sequence
2499 // structure, so that it will persist if we fail.
2500 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2501 CandidateSet.clear();
2502
2503 // Determine whether we are allowed to call explicit constructors or
2504 // explicit conversion operators.
2505 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2506 Kind.getKind() == InitializationKind::IK_Value ||
2507 Kind.getKind() == InitializationKind::IK_Default);
2508
2509 // The type we're converting to is a class type. Enumerate its constructors
2510 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002511 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2512 assert(DestRecordType && "Constructor initialization requires record type");
2513 CXXRecordDecl *DestRecordDecl
2514 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2515
2516 DeclarationName ConstructorName
2517 = S.Context.DeclarationNames.getCXXConstructorName(
2518 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2519 DeclContext::lookup_iterator Con, ConEnd;
2520 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2521 Con != ConEnd; ++Con) {
2522 // Find the constructor (which may be a template).
2523 CXXConstructorDecl *Constructor = 0;
2524 FunctionTemplateDecl *ConstructorTmpl
2525 = dyn_cast<FunctionTemplateDecl>(*Con);
2526 if (ConstructorTmpl)
2527 Constructor = cast<CXXConstructorDecl>(
2528 ConstructorTmpl->getTemplatedDecl());
2529 else
2530 Constructor = cast<CXXConstructorDecl>(*Con);
2531
2532 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002533 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002534 if (ConstructorTmpl)
2535 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2536 Args, NumArgs, CandidateSet);
2537 else
2538 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2539 }
2540 }
2541
2542 SourceLocation DeclLoc = Kind.getLocation();
2543
2544 // Perform overload resolution. If it fails, return the failed result.
2545 OverloadCandidateSet::iterator Best;
2546 if (OverloadingResult Result
2547 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2548 Sequence.SetOverloadFailure(
2549 InitializationSequence::FK_ConstructorOverloadFailed,
2550 Result);
2551 return;
2552 }
2553
2554 // Add the constructor initialization step. Any cv-qualification conversion is
2555 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002556 if (Kind.getKind() == InitializationKind::IK_Copy) {
2557 Sequence.AddUserConversionStep(Best->Function, DestType);
2558 } else {
2559 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002560 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002561 DestType);
2562 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002563}
2564
Douglas Gregor71d17402009-12-15 00:01:57 +00002565/// \brief Attempt value initialization (C++ [dcl.init]p7).
2566static void TryValueInitialization(Sema &S,
2567 const InitializedEntity &Entity,
2568 const InitializationKind &Kind,
2569 InitializationSequence &Sequence) {
2570 // C++ [dcl.init]p5:
2571 //
2572 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002573 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002574
2575 // -- if T is an array type, then each element is value-initialized;
2576 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2577 T = AT->getElementType();
2578
2579 if (const RecordType *RT = T->getAs<RecordType>()) {
2580 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2581 // -- if T is a class type (clause 9) with a user-declared
2582 // constructor (12.1), then the default constructor for T is
2583 // called (and the initialization is ill-formed if T has no
2584 // accessible default constructor);
2585 //
2586 // FIXME: we really want to refer to a single subobject of the array,
2587 // but Entity doesn't have a way to capture that (yet).
2588 if (ClassDecl->hasUserDeclaredConstructor())
2589 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2590
Douglas Gregor16006c92009-12-16 18:50:27 +00002591 // -- if T is a (possibly cv-qualified) non-union class type
2592 // without a user-provided constructor, then the object is
2593 // zero-initialized and, if T’s implicitly-declared default
2594 // constructor is non-trivial, that constructor is called.
2595 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2596 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2597 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002598 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002599 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2600 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002601 }
2602 }
2603
Douglas Gregord6542d82009-12-22 15:35:07 +00002604 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002605 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2606}
2607
Douglas Gregor99a2e602009-12-16 01:38:02 +00002608/// \brief Attempt default initialization (C++ [dcl.init]p6).
2609static void TryDefaultInitialization(Sema &S,
2610 const InitializedEntity &Entity,
2611 const InitializationKind &Kind,
2612 InitializationSequence &Sequence) {
2613 assert(Kind.getKind() == InitializationKind::IK_Default);
2614
2615 // C++ [dcl.init]p6:
2616 // To default-initialize an object of type T means:
2617 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002618 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002619 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2620 DestType = Array->getElementType();
2621
2622 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2623 // constructor for T is called (and the initialization is ill-formed if
2624 // T has no accessible default constructor);
2625 if (DestType->isRecordType()) {
2626 // FIXME: If a program calls for the default initialization of an object of
2627 // a const-qualified type T, T shall be a class type with a user-provided
2628 // default constructor.
2629 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2630 Sequence);
2631 }
2632
2633 // - otherwise, no initialization is performed.
2634 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2635
2636 // If a program calls for the default initialization of an object of
2637 // a const-qualified type T, T shall be a class type with a user-provided
2638 // default constructor.
2639 if (DestType.isConstQualified())
2640 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2641}
2642
Douglas Gregor20093b42009-12-09 23:02:17 +00002643/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2644/// which enumerates all conversion functions and performs overload resolution
2645/// to select the best.
2646static void TryUserDefinedConversion(Sema &S,
2647 const InitializedEntity &Entity,
2648 const InitializationKind &Kind,
2649 Expr *Initializer,
2650 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002651 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2652
Douglas Gregord6542d82009-12-22 15:35:07 +00002653 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002654 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2655 QualType SourceType = Initializer->getType();
2656 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2657 "Must have a class type to perform a user-defined conversion");
2658
2659 // Build the candidate set directly in the initialization sequence
2660 // structure, so that it will persist if we fail.
2661 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2662 CandidateSet.clear();
2663
2664 // Determine whether we are allowed to call explicit constructors or
2665 // explicit conversion operators.
2666 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2667
2668 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2669 // The type we're converting to is a class type. Enumerate its constructors
2670 // to see if there is a suitable conversion.
2671 CXXRecordDecl *DestRecordDecl
2672 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2673
2674 DeclarationName ConstructorName
2675 = S.Context.DeclarationNames.getCXXConstructorName(
2676 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2677 DeclContext::lookup_iterator Con, ConEnd;
2678 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2679 Con != ConEnd; ++Con) {
2680 // Find the constructor (which may be a template).
2681 CXXConstructorDecl *Constructor = 0;
2682 FunctionTemplateDecl *ConstructorTmpl
2683 = dyn_cast<FunctionTemplateDecl>(*Con);
2684 if (ConstructorTmpl)
2685 Constructor = cast<CXXConstructorDecl>(
2686 ConstructorTmpl->getTemplatedDecl());
2687 else
2688 Constructor = cast<CXXConstructorDecl>(*Con);
2689
2690 if (!Constructor->isInvalidDecl() &&
2691 Constructor->isConvertingConstructor(AllowExplicit)) {
2692 if (ConstructorTmpl)
2693 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2694 &Initializer, 1, CandidateSet);
2695 else
2696 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2697 }
2698 }
2699 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002700
2701 SourceLocation DeclLoc = Initializer->getLocStart();
2702
Douglas Gregor4a520a22009-12-14 17:27:33 +00002703 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2704 // The type we're converting from is a class type, enumerate its conversion
2705 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002706
Eli Friedman33c2da92009-12-20 22:12:03 +00002707 // We can only enumerate the conversion functions for a complete type; if
2708 // the type isn't complete, simply skip this step.
2709 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2710 CXXRecordDecl *SourceRecordDecl
2711 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002712
John McCalleec51cf2010-01-20 00:46:10 +00002713 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002714 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002715 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002716 E = Conversions->end();
2717 I != E; ++I) {
2718 NamedDecl *D = *I;
2719 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2720 if (isa<UsingShadowDecl>(D))
2721 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2722
2723 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2724 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002725 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002726 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002727 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002728 Conv = cast<CXXConversionDecl>(*I);
2729
2730 if (AllowExplicit || !Conv->isExplicit()) {
2731 if (ConvTemplate)
2732 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2733 Initializer, DestType,
2734 CandidateSet);
2735 else
2736 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2737 CandidateSet);
2738 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002739 }
2740 }
2741 }
2742
Douglas Gregor4a520a22009-12-14 17:27:33 +00002743 // Perform overload resolution. If it fails, return the failed result.
2744 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002745 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002746 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2747 Sequence.SetOverloadFailure(
2748 InitializationSequence::FK_UserConversionOverloadFailed,
2749 Result);
2750 return;
2751 }
John McCall1d318332010-01-12 00:44:57 +00002752
Douglas Gregor4a520a22009-12-14 17:27:33 +00002753 FunctionDecl *Function = Best->Function;
2754
2755 if (isa<CXXConstructorDecl>(Function)) {
2756 // Add the user-defined conversion step. Any cv-qualification conversion is
2757 // subsumed by the initialization.
2758 Sequence.AddUserConversionStep(Function, DestType);
2759 return;
2760 }
2761
2762 // Add the user-defined conversion step that calls the conversion function.
2763 QualType ConvType = Function->getResultType().getNonReferenceType();
2764 Sequence.AddUserConversionStep(Function, ConvType);
2765
2766 // If the conversion following the call to the conversion function is
2767 // interesting, add it as a separate step.
2768 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2769 Best->FinalConversion.Third) {
2770 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002771 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002772 ICS.Standard = Best->FinalConversion;
2773 Sequence.AddConversionSequenceStep(ICS, DestType);
2774 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002775}
2776
2777/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2778/// non-class type to another.
2779static void TryImplicitConversion(Sema &S,
2780 const InitializedEntity &Entity,
2781 const InitializationKind &Kind,
2782 Expr *Initializer,
2783 InitializationSequence &Sequence) {
2784 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002785 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002786 /*SuppressUserConversions=*/true,
2787 /*AllowExplicit=*/false,
2788 /*ForceRValue=*/false,
2789 /*FIXME:InOverloadResolution=*/false,
2790 /*UserCast=*/Kind.isExplicitCast());
2791
John McCall1d318332010-01-12 00:44:57 +00002792 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002793 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2794 return;
2795 }
2796
Douglas Gregord6542d82009-12-22 15:35:07 +00002797 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002798}
2799
2800InitializationSequence::InitializationSequence(Sema &S,
2801 const InitializedEntity &Entity,
2802 const InitializationKind &Kind,
2803 Expr **Args,
2804 unsigned NumArgs) {
2805 ASTContext &Context = S.Context;
2806
2807 // C++0x [dcl.init]p16:
2808 // The semantics of initializers are as follows. The destination type is
2809 // the type of the object or reference being initialized and the source
2810 // type is the type of the initializer expression. The source type is not
2811 // defined when the initializer is a braced-init-list or when it is a
2812 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002813 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002814
2815 if (DestType->isDependentType() ||
2816 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2817 SequenceKind = DependentSequence;
2818 return;
2819 }
2820
2821 QualType SourceType;
2822 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002823 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002824 Initializer = Args[0];
2825 if (!isa<InitListExpr>(Initializer))
2826 SourceType = Initializer->getType();
2827 }
2828
2829 // - If the initializer is a braced-init-list, the object is
2830 // list-initialized (8.5.4).
2831 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2832 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002833 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002834 }
2835
2836 // - If the destination type is a reference type, see 8.5.3.
2837 if (DestType->isReferenceType()) {
2838 // C++0x [dcl.init.ref]p1:
2839 // A variable declared to be a T& or T&&, that is, "reference to type T"
2840 // (8.3.2), shall be initialized by an object, or function, of type T or
2841 // by an object that can be converted into a T.
2842 // (Therefore, multiple arguments are not permitted.)
2843 if (NumArgs != 1)
2844 SetFailed(FK_TooManyInitsForReference);
2845 else
2846 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2847 return;
2848 }
2849
2850 // - If the destination type is an array of characters, an array of
2851 // char16_t, an array of char32_t, or an array of wchar_t, and the
2852 // initializer is a string literal, see 8.5.2.
2853 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2854 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2855 return;
2856 }
2857
2858 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002859 if (Kind.getKind() == InitializationKind::IK_Value ||
2860 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002861 TryValueInitialization(S, Entity, Kind, *this);
2862 return;
2863 }
2864
Douglas Gregor99a2e602009-12-16 01:38:02 +00002865 // Handle default initialization.
2866 if (Kind.getKind() == InitializationKind::IK_Default){
2867 TryDefaultInitialization(S, Entity, Kind, *this);
2868 return;
2869 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002870
Douglas Gregor20093b42009-12-09 23:02:17 +00002871 // - Otherwise, if the destination type is an array, the program is
2872 // ill-formed.
2873 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2874 if (AT->getElementType()->isAnyCharacterType())
2875 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2876 else
2877 SetFailed(FK_ArrayNeedsInitList);
2878
2879 return;
2880 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002881
2882 // Handle initialization in C
2883 if (!S.getLangOptions().CPlusPlus) {
2884 setSequenceKind(CAssignment);
2885 AddCAssignmentStep(DestType);
2886 return;
2887 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002888
2889 // - If the destination type is a (possibly cv-qualified) class type:
2890 if (DestType->isRecordType()) {
2891 // - If the initialization is direct-initialization, or if it is
2892 // copy-initialization where the cv-unqualified version of the
2893 // source type is the same class as, or a derived class of, the
2894 // class of the destination, constructors are considered. [...]
2895 if (Kind.getKind() == InitializationKind::IK_Direct ||
2896 (Kind.getKind() == InitializationKind::IK_Copy &&
2897 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2898 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002899 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00002900 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002901 // - Otherwise (i.e., for the remaining copy-initialization cases),
2902 // user-defined conversion sequences that can convert from the source
2903 // type to the destination type or (when a conversion function is
2904 // used) to a derived class thereof are enumerated as described in
2905 // 13.3.1.4, and the best one is chosen through overload resolution
2906 // (13.3).
2907 else
2908 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2909 return;
2910 }
2911
Douglas Gregor99a2e602009-12-16 01:38:02 +00002912 if (NumArgs > 1) {
2913 SetFailed(FK_TooManyInitsForScalar);
2914 return;
2915 }
2916 assert(NumArgs == 1 && "Zero-argument case handled above");
2917
Douglas Gregor20093b42009-12-09 23:02:17 +00002918 // - Otherwise, if the source type is a (possibly cv-qualified) class
2919 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002920 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002921 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2922 return;
2923 }
2924
2925 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002926 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002927 // conversions (Clause 4) will be used, if necessary, to convert the
2928 // initializer expression to the cv-unqualified version of the
2929 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002930 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002931 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2932}
2933
2934InitializationSequence::~InitializationSequence() {
2935 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2936 StepEnd = Steps.end();
2937 Step != StepEnd; ++Step)
2938 Step->Destroy();
2939}
2940
2941//===----------------------------------------------------------------------===//
2942// Perform initialization
2943//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002944static Sema::AssignmentAction
2945getAssignmentAction(const InitializedEntity &Entity) {
2946 switch(Entity.getKind()) {
2947 case InitializedEntity::EK_Variable:
2948 case InitializedEntity::EK_New:
2949 return Sema::AA_Initializing;
2950
2951 case InitializedEntity::EK_Parameter:
2952 // FIXME: Can we tell when we're sending vs. passing?
2953 return Sema::AA_Passing;
2954
2955 case InitializedEntity::EK_Result:
2956 return Sema::AA_Returning;
2957
2958 case InitializedEntity::EK_Exception:
2959 case InitializedEntity::EK_Base:
2960 llvm_unreachable("No assignment action for C++-specific initialization");
2961 break;
2962
2963 case InitializedEntity::EK_Temporary:
2964 // FIXME: Can we tell apart casting vs. converting?
2965 return Sema::AA_Casting;
2966
2967 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002968 case InitializedEntity::EK_ArrayElement:
2969 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002970 return Sema::AA_Initializing;
2971 }
2972
2973 return Sema::AA_Converting;
2974}
2975
2976static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2977 bool IsCopy) {
2978 switch (Entity.getKind()) {
2979 case InitializedEntity::EK_Result:
2980 case InitializedEntity::EK_Exception:
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00002981 case InitializedEntity::EK_ArrayElement:
2982 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002983 return !IsCopy;
2984
2985 case InitializedEntity::EK_New:
2986 case InitializedEntity::EK_Variable:
2987 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002988 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002989 return false;
2990
2991 case InitializedEntity::EK_Parameter:
2992 case InitializedEntity::EK_Temporary:
2993 return true;
2994 }
2995
2996 llvm_unreachable("missed an InitializedEntity kind?");
2997}
2998
2999/// \brief If we need to perform an additional copy of the initialized object
3000/// for this kind of entity (e.g., the result of a function or an object being
3001/// thrown), make the copy.
3002static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3003 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003004 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003005 Sema::OwningExprResult CurInit) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003006 Expr *CurInitExpr = (Expr *)CurInit.get();
3007
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003008 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003009
3010 switch (Entity.getKind()) {
3011 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00003012 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003013 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003014 Loc = Entity.getReturnLoc();
3015 break;
3016
3017 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003018 Loc = Entity.getThrowLoc();
3019 break;
3020
3021 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00003022 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003023 Kind.getKind() != InitializationKind::IK_Copy)
3024 return move(CurInit);
3025 Loc = Entity.getDecl()->getLocation();
3026 break;
3027
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003028 case InitializedEntity::EK_ArrayElement:
3029 case InitializedEntity::EK_Member:
3030 if (Entity.getType()->isReferenceType() ||
3031 Kind.getKind() != InitializationKind::IK_Copy)
3032 return move(CurInit);
3033 Loc = CurInitExpr->getLocStart();
3034 break;
3035
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003036 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003037 // FIXME: Do we need this initialization for a parameter?
3038 return move(CurInit);
3039
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003040 case InitializedEntity::EK_New:
3041 case InitializedEntity::EK_Temporary:
3042 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003043 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003044 // We don't need to copy for any of these initialized entities.
3045 return move(CurInit);
3046 }
3047
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003048 CXXRecordDecl *Class = 0;
3049 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3050 Class = cast<CXXRecordDecl>(Record->getDecl());
3051 if (!Class)
3052 return move(CurInit);
3053
3054 // Perform overload resolution using the class's copy constructors.
3055 DeclarationName ConstructorName
3056 = S.Context.DeclarationNames.getCXXConstructorName(
3057 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3058 DeclContext::lookup_iterator Con, ConEnd;
3059 OverloadCandidateSet CandidateSet;
3060 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3061 Con != ConEnd; ++Con) {
3062 // Find the constructor (which may be a template).
3063 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3064 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003065 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003066 continue;
3067
3068 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3069 }
3070
3071 OverloadCandidateSet::iterator Best;
3072 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3073 case OR_Success:
3074 break;
3075
3076 case OR_No_Viable_Function:
3077 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003078 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003079 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003080 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3081 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003082 return S.ExprError();
3083
3084 case OR_Ambiguous:
3085 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003086 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003087 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003088 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3089 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003090 return S.ExprError();
3091
3092 case OR_Deleted:
3093 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003094 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003095 << CurInitExpr->getSourceRange();
3096 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3097 << Best->Function->isDeleted();
3098 return S.ExprError();
3099 }
3100
3101 CurInit.release();
3102 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3103 cast<CXXConstructorDecl>(Best->Function),
3104 /*Elidable=*/true,
3105 Sema::MultiExprArg(S,
3106 (void**)&CurInitExpr, 1));
3107}
Douglas Gregor20093b42009-12-09 23:02:17 +00003108
3109Action::OwningExprResult
3110InitializationSequence::Perform(Sema &S,
3111 const InitializedEntity &Entity,
3112 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003113 Action::MultiExprArg Args,
3114 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003115 if (SequenceKind == FailedSequence) {
3116 unsigned NumArgs = Args.size();
3117 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3118 return S.ExprError();
3119 }
3120
3121 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003122 // If the declaration is a non-dependent, incomplete array type
3123 // that has an initializer, then its type will be completed once
3124 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003125 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003126 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003127 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003128 if (const IncompleteArrayType *ArrayT
3129 = S.Context.getAsIncompleteArrayType(DeclType)) {
3130 // FIXME: We don't currently have the ability to accurately
3131 // compute the length of an initializer list without
3132 // performing full type-checking of the initializer list
3133 // (since we have to determine where braces are implicitly
3134 // introduced and such). So, we fall back to making the array
3135 // type a dependently-sized array type with no specified
3136 // bound.
3137 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3138 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003139
Douglas Gregord87b61f2009-12-10 17:56:55 +00003140 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003141 if (DeclaratorDecl *DD = Entity.getDecl()) {
3142 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3143 TypeLoc TL = TInfo->getTypeLoc();
3144 if (IncompleteArrayTypeLoc *ArrayLoc
3145 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3146 Brackets = ArrayLoc->getBracketsRange();
3147 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003148 }
3149
3150 *ResultType
3151 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3152 /*NumElts=*/0,
3153 ArrayT->getSizeModifier(),
3154 ArrayT->getIndexTypeCVRQualifiers(),
3155 Brackets);
3156 }
3157
3158 }
3159 }
3160
Eli Friedman08544622009-12-22 02:35:53 +00003161 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003162 return Sema::OwningExprResult(S, Args.release()[0]);
3163
3164 unsigned NumArgs = Args.size();
3165 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3166 SourceLocation(),
3167 (Expr **)Args.release(),
3168 NumArgs,
3169 SourceLocation()));
3170 }
3171
Douglas Gregor99a2e602009-12-16 01:38:02 +00003172 if (SequenceKind == NoInitialization)
3173 return S.Owned((Expr *)0);
3174
Douglas Gregord6542d82009-12-22 15:35:07 +00003175 QualType DestType = Entity.getType().getNonReferenceType();
3176 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003177 // the same as Entity.getDecl()->getType() in cases involving type merging,
3178 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003179 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003180 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003181 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003182
Douglas Gregor99a2e602009-12-16 01:38:02 +00003183 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3184
3185 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3186
3187 // For initialization steps that start with a single initializer,
3188 // grab the only argument out the Args and place it into the "current"
3189 // initializer.
3190 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003191 case SK_ResolveAddressOfOverloadedFunction:
3192 case SK_CastDerivedToBaseRValue:
3193 case SK_CastDerivedToBaseLValue:
3194 case SK_BindReference:
3195 case SK_BindReferenceToTemporary:
3196 case SK_UserConversion:
3197 case SK_QualificationConversionLValue:
3198 case SK_QualificationConversionRValue:
3199 case SK_ConversionSequence:
3200 case SK_ListInitialization:
3201 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003202 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003203 assert(Args.size() == 1);
3204 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3205 if (CurInit.isInvalid())
3206 return S.ExprError();
3207 break;
3208
3209 case SK_ConstructorInitialization:
3210 case SK_ZeroInitialization:
3211 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003212 }
3213
3214 // Walk through the computed steps for the initialization sequence,
3215 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003216 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003217 for (step_iterator Step = step_begin(), StepEnd = step_end();
3218 Step != StepEnd; ++Step) {
3219 if (CurInit.isInvalid())
3220 return S.ExprError();
3221
3222 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003223 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003224
3225 switch (Step->Kind) {
3226 case SK_ResolveAddressOfOverloadedFunction:
3227 // Overload resolution determined which function invoke; update the
3228 // initializer to reflect that choice.
3229 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3230 break;
3231
3232 case SK_CastDerivedToBaseRValue:
3233 case SK_CastDerivedToBaseLValue: {
3234 // We have a derived-to-base cast that produces either an rvalue or an
3235 // lvalue. Perform that cast.
3236
3237 // Casts to inaccessible base classes are allowed with C-style casts.
3238 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3239 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3240 CurInitExpr->getLocStart(),
3241 CurInitExpr->getSourceRange(),
3242 IgnoreBaseAccess))
3243 return S.ExprError();
3244
3245 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3246 CastExpr::CK_DerivedToBase,
3247 (Expr*)CurInit.release(),
3248 Step->Kind == SK_CastDerivedToBaseLValue));
3249 break;
3250 }
3251
3252 case SK_BindReference:
3253 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3254 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3255 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003256 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003257 << BitField->getDeclName()
3258 << CurInitExpr->getSourceRange();
3259 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3260 return S.ExprError();
3261 }
3262
3263 // Reference binding does not have any corresponding ASTs.
3264
3265 // Check exception specifications
3266 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3267 return S.ExprError();
3268 break;
3269
3270 case SK_BindReferenceToTemporary:
3271 // Check exception specifications
3272 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3273 return S.ExprError();
3274
3275 // FIXME: At present, we have no AST to describe when we need to make a
3276 // temporary to bind a reference to. We should.
3277 break;
3278
3279 case SK_UserConversion: {
3280 // We have a user-defined conversion that invokes either a constructor
3281 // or a conversion function.
3282 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003283 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003284 if (CXXConstructorDecl *Constructor
3285 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3286 // Build a call to the selected constructor.
3287 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3288 SourceLocation Loc = CurInitExpr->getLocStart();
3289 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3290
3291 // Determine the arguments required to actually perform the constructor
3292 // call.
3293 if (S.CompleteConstructorCall(Constructor,
3294 Sema::MultiExprArg(S,
3295 (void **)&CurInitExpr,
3296 1),
3297 Loc, ConstructorArgs))
3298 return S.ExprError();
3299
3300 // Build the an expression that constructs a temporary.
3301 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3302 move_arg(ConstructorArgs));
3303 if (CurInit.isInvalid())
3304 return S.ExprError();
3305
3306 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003307 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3308 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3309 S.IsDerivedFrom(SourceType, Class))
3310 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003311 } else {
3312 // Build a call to the conversion function.
3313 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003314
Douglas Gregor20093b42009-12-09 23:02:17 +00003315 // FIXME: Should we move this initialization into a separate
3316 // derived-to-base conversion? I believe the answer is "no", because
3317 // we don't want to turn off access control here for c-style casts.
3318 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3319 return S.ExprError();
3320
3321 // Do a little dance to make sure that CurInit has the proper
3322 // pointer.
3323 CurInit.release();
3324
3325 // Build the actual call to the conversion function.
3326 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3327 if (CurInit.isInvalid() || !CurInit.get())
3328 return S.ExprError();
3329
3330 CastKind = CastExpr::CK_UserDefinedConversion;
3331 }
3332
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003333 if (shouldBindAsTemporary(Entity, IsCopy))
3334 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3335
Douglas Gregor20093b42009-12-09 23:02:17 +00003336 CurInitExpr = CurInit.takeAs<Expr>();
3337 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3338 CastKind,
3339 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003340 false));
3341
3342 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003343 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003344 break;
3345 }
3346
3347 case SK_QualificationConversionLValue:
3348 case SK_QualificationConversionRValue:
3349 // Perform a qualification conversion; these can never go wrong.
3350 S.ImpCastExprToType(CurInitExpr, Step->Type,
3351 CastExpr::CK_NoOp,
3352 Step->Kind == SK_QualificationConversionLValue);
3353 CurInit.release();
3354 CurInit = S.Owned(CurInitExpr);
3355 break;
3356
3357 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003358 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003359 false, false, *Step->ICS))
3360 return S.ExprError();
3361
3362 CurInit.release();
3363 CurInit = S.Owned(CurInitExpr);
3364 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003365
3366 case SK_ListInitialization: {
3367 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3368 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003369 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003370 return S.ExprError();
3371
3372 CurInit.release();
3373 CurInit = S.Owned(InitList);
3374 break;
3375 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003376
3377 case SK_ConstructorInitialization: {
3378 CXXConstructorDecl *Constructor
3379 = cast<CXXConstructorDecl>(Step->Function);
3380
3381 // Build a call to the selected constructor.
3382 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3383 SourceLocation Loc = Kind.getLocation();
3384
3385 // Determine the arguments required to actually perform the constructor
3386 // call.
3387 if (S.CompleteConstructorCall(Constructor, move(Args),
3388 Loc, ConstructorArgs))
3389 return S.ExprError();
3390
3391 // Build the an expression that constructs a temporary.
Douglas Gregord6542d82009-12-22 15:35:07 +00003392 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor745880f2009-12-20 22:01:25 +00003393 Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003394 move_arg(ConstructorArgs),
3395 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003396 if (CurInit.isInvalid())
3397 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003398
3399 bool Elidable
3400 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3401 if (shouldBindAsTemporary(Entity, Elidable))
3402 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3403
3404 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003405 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003406 break;
3407 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003408
3409 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003410 step_iterator NextStep = Step;
3411 ++NextStep;
3412 if (NextStep != StepEnd &&
3413 NextStep->Kind == SK_ConstructorInitialization) {
3414 // The need for zero-initialization is recorded directly into
3415 // the call to the object's constructor within the next step.
3416 ConstructorInitRequiresZeroInit = true;
3417 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3418 S.getLangOptions().CPlusPlus &&
3419 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003420 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3421 Kind.getRange().getBegin(),
3422 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003423 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003424 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003425 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003426 break;
3427 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003428
3429 case SK_CAssignment: {
3430 QualType SourceType = CurInitExpr->getType();
3431 Sema::AssignConvertType ConvTy =
3432 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003433
3434 // If this is a call, allow conversion to a transparent union.
3435 if (ConvTy != Sema::Compatible &&
3436 Entity.getKind() == InitializedEntity::EK_Parameter &&
3437 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3438 == Sema::Compatible)
3439 ConvTy = Sema::Compatible;
3440
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003441 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3442 Step->Type, SourceType,
3443 CurInitExpr, getAssignmentAction(Entity)))
3444 return S.ExprError();
3445
3446 CurInit.release();
3447 CurInit = S.Owned(CurInitExpr);
3448 break;
3449 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003450
3451 case SK_StringInit: {
3452 QualType Ty = Step->Type;
3453 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3454 break;
3455 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003456 }
3457 }
3458
3459 return move(CurInit);
3460}
3461
3462//===----------------------------------------------------------------------===//
3463// Diagnose initialization failures
3464//===----------------------------------------------------------------------===//
3465bool InitializationSequence::Diagnose(Sema &S,
3466 const InitializedEntity &Entity,
3467 const InitializationKind &Kind,
3468 Expr **Args, unsigned NumArgs) {
3469 if (SequenceKind != FailedSequence)
3470 return false;
3471
Douglas Gregord6542d82009-12-22 15:35:07 +00003472 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003473 switch (Failure) {
3474 case FK_TooManyInitsForReference:
3475 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3476 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3477 break;
3478
3479 case FK_ArrayNeedsInitList:
3480 case FK_ArrayNeedsInitListOrStringLiteral:
3481 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3482 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3483 break;
3484
3485 case FK_AddressOfOverloadFailed:
3486 S.ResolveAddressOfOverloadedFunction(Args[0],
3487 DestType.getNonReferenceType(),
3488 true);
3489 break;
3490
3491 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003492 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003493 switch (FailedOverloadResult) {
3494 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003495 if (Failure == FK_UserConversionOverloadFailed)
3496 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3497 << Args[0]->getType() << DestType
3498 << Args[0]->getSourceRange();
3499 else
3500 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3501 << DestType << Args[0]->getType()
3502 << Args[0]->getSourceRange();
3503
John McCallcbce6062010-01-12 07:18:19 +00003504 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3505 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003506 break;
3507
3508 case OR_No_Viable_Function:
3509 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3510 << Args[0]->getType() << DestType.getNonReferenceType()
3511 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003512 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3513 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003514 break;
3515
3516 case OR_Deleted: {
3517 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3518 << Args[0]->getType() << DestType.getNonReferenceType()
3519 << Args[0]->getSourceRange();
3520 OverloadCandidateSet::iterator Best;
3521 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3522 Kind.getLocation(),
3523 Best);
3524 if (Ovl == OR_Deleted) {
3525 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3526 << Best->Function->isDeleted();
3527 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003528 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003529 }
3530 break;
3531 }
3532
3533 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003534 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003535 break;
3536 }
3537 break;
3538
3539 case FK_NonConstLValueReferenceBindingToTemporary:
3540 case FK_NonConstLValueReferenceBindingToUnrelated:
3541 S.Diag(Kind.getLocation(),
3542 Failure == FK_NonConstLValueReferenceBindingToTemporary
3543 ? diag::err_lvalue_reference_bind_to_temporary
3544 : diag::err_lvalue_reference_bind_to_unrelated)
3545 << DestType.getNonReferenceType()
3546 << Args[0]->getType()
3547 << Args[0]->getSourceRange();
3548 break;
3549
3550 case FK_RValueReferenceBindingToLValue:
3551 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3552 << Args[0]->getSourceRange();
3553 break;
3554
3555 case FK_ReferenceInitDropsQualifiers:
3556 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3557 << DestType.getNonReferenceType()
3558 << Args[0]->getType()
3559 << Args[0]->getSourceRange();
3560 break;
3561
3562 case FK_ReferenceInitFailed:
3563 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3564 << DestType.getNonReferenceType()
3565 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3566 << Args[0]->getType()
3567 << Args[0]->getSourceRange();
3568 break;
3569
3570 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003571 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3572 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003573 << DestType
3574 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3575 << Args[0]->getType()
3576 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003577 break;
3578
3579 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003580 SourceRange R;
3581
3582 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3583 R = SourceRange(InitList->getInit(1)->getLocStart(),
3584 InitList->getLocEnd());
3585 else
3586 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003587
3588 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003589 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003590 break;
3591 }
3592
3593 case FK_ReferenceBindingToInitList:
3594 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3595 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3596 break;
3597
3598 case FK_InitListBadDestinationType:
3599 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3600 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3601 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003602
3603 case FK_ConstructorOverloadFailed: {
3604 SourceRange ArgsRange;
3605 if (NumArgs)
3606 ArgsRange = SourceRange(Args[0]->getLocStart(),
3607 Args[NumArgs - 1]->getLocEnd());
3608
3609 // FIXME: Using "DestType" for the entity we're printing is probably
3610 // bad.
3611 switch (FailedOverloadResult) {
3612 case OR_Ambiguous:
3613 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3614 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003615 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003616 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003617 break;
3618
3619 case OR_No_Viable_Function:
3620 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3621 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003622 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3623 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003624 break;
3625
3626 case OR_Deleted: {
3627 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3628 << true << DestType << ArgsRange;
3629 OverloadCandidateSet::iterator Best;
3630 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3631 Kind.getLocation(),
3632 Best);
3633 if (Ovl == OR_Deleted) {
3634 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3635 << Best->Function->isDeleted();
3636 } else {
3637 llvm_unreachable("Inconsistent overload resolution?");
3638 }
3639 break;
3640 }
3641
3642 case OR_Success:
3643 llvm_unreachable("Conversion did not fail!");
3644 break;
3645 }
3646 break;
3647 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003648
3649 case FK_DefaultInitOfConst:
3650 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3651 << DestType;
3652 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003653 }
3654
3655 return true;
3656}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003657
3658//===----------------------------------------------------------------------===//
3659// Initialization helper functions
3660//===----------------------------------------------------------------------===//
3661Sema::OwningExprResult
3662Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3663 SourceLocation EqualLoc,
3664 OwningExprResult Init) {
3665 if (Init.isInvalid())
3666 return ExprError();
3667
3668 Expr *InitE = (Expr *)Init.get();
3669 assert(InitE && "No initialization expression?");
3670
3671 if (EqualLoc.isInvalid())
3672 EqualLoc = InitE->getLocStart();
3673
3674 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3675 EqualLoc);
3676 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3677 Init.release();
3678 return Seq.Perform(*this, Entity, Kind,
3679 MultiExprArg(*this, (void**)&InitE, 1));
3680}