blob: b0dee9c691774a9045a3b0c9d6a8347124cf156a [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.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000708 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
709 SemaRef.Owned(expr));
710 IList->setInit(Index, 0);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000711 hadError = true;
712 ++Index;
713 ++StructuredIndex;
714 }
715 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000716}
717
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000718void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000719 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000720 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000721 InitListExpr *StructuredList,
722 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000723 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000724 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000725 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000726 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000727 diag::err_many_braces_around_scalar_init)
728 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000729 hadError = true;
730 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000731 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000732 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000733 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000734 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000735 diag::err_designator_for_scalar_init)
736 << DeclType << expr->getSourceRange();
737 hadError = true;
738 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000739 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000740 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000741 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000742
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000743 Sema::OwningExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000744 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
745 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000746
747 Expr *ResultExpr;
748
749 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000750 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000751 else {
752 ResultExpr = Result.takeAs<Expr>();
753
754 if (ResultExpr != expr) {
755 // The type was promoted, update initializer list.
756 IList->setInit(Index, ResultExpr);
757 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000758 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000759 if (hadError)
760 ++StructuredIndex;
761 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000762 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000763 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000764 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000765 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000766 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000767 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000768 ++Index;
769 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000770 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000771 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000772}
773
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000774void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
775 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000776 unsigned &Index,
777 InitListExpr *StructuredList,
778 unsigned &StructuredIndex) {
779 if (Index < IList->getNumInits()) {
780 Expr *expr = IList->getInit(Index);
781 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000782 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000783 << DeclType << IList->getSourceRange();
784 hadError = true;
785 ++Index;
786 ++StructuredIndex;
787 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000788 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000789
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000790 Sema::OwningExprResult Result =
791 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
792 SemaRef.Owned(expr));
793
794 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000795 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000796
797 expr = Result.takeAs<Expr>();
798 IList->setInit(Index, expr);
799
Douglas Gregor930d8b52009-01-30 22:09:00 +0000800 if (hadError)
801 ++StructuredIndex;
802 else
803 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
804 ++Index;
805 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000806 // FIXME: It would be wonderful if we could point at the actual member. In
807 // general, it would be useful to pass location information down the stack,
808 // so that we know the location (or decl) of the "current object" being
809 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000810 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000811 diag::err_init_reference_member_uninitialized)
812 << DeclType
813 << IList->getSourceRange();
814 hadError = true;
815 ++Index;
816 ++StructuredIndex;
817 return;
818 }
819}
820
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000821void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000822 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000823 unsigned &Index,
824 InitListExpr *StructuredList,
825 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000826 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000827 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000828 unsigned maxElements = VT->getNumElements();
829 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000830 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Nate Begeman2ef13e52009-08-10 23:49:36 +0000832 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000833 InitializedEntity ElementEntity =
834 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000835
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000836 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
837 // Don't attempt to go past the end of the init list
838 if (Index >= IList->getNumInits())
839 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000840
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000841 ElementEntity.setElementIndex(Index);
842 CheckSubElementType(ElementEntity, IList, elementType, Index,
843 StructuredList, StructuredIndex);
844 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000845 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000846 InitializedEntity ElementEntity =
847 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
848
Nate Begeman2ef13e52009-08-10 23:49:36 +0000849 // OpenCL initializers allows vectors to be constructed from vectors.
850 for (unsigned i = 0; i < maxElements; ++i) {
851 // Don't attempt to go past the end of the init list
852 if (Index >= IList->getNumInits())
853 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000854
855 ElementEntity.setElementIndex(Index);
856
Nate Begeman2ef13e52009-08-10 23:49:36 +0000857 QualType IType = IList->getInit(Index)->getType();
858 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000859 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000860 StructuredList, StructuredIndex);
861 ++numEltsInit;
862 } else {
John McCall183700f2009-09-21 23:43:11 +0000863 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000864 unsigned numIElts = IVT->getNumElements();
865 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
866 numIElts);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000867 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000868 StructuredList, StructuredIndex);
869 numEltsInit += numIElts;
870 }
871 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000872 }
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Nate Begeman2ef13e52009-08-10 23:49:36 +0000874 // OpenCL & AltiVec require all elements to be initialized.
875 if (numEltsInit != maxElements)
876 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
877 SemaRef.Diag(IList->getSourceRange().getBegin(),
878 diag::err_vector_incorrect_num_initializers)
879 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000880 }
881}
882
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000883void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000884 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000885 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000886 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000887 unsigned &Index,
888 InitListExpr *StructuredList,
889 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000890 // Check for the special-case of initializing an array with a string.
891 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000892 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
893 SemaRef.Context)) {
894 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000895 // We place the string literal directly into the resulting
896 // initializer list. This is the only place where the structure
897 // of the structured initializer list doesn't match exactly,
898 // because doing so would involve allocating one character
899 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000900 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000901 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000902 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000903 return;
904 }
905 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000906 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000907 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000908 // Check for VLAs; in standard C it would be possible to check this
909 // earlier, but I don't know where clang accepts VLAs (gcc accepts
910 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000911 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000912 diag::err_variable_object_no_init)
913 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000914 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000915 ++Index;
916 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000917 return;
918 }
919
Douglas Gregor05c13a32009-01-22 00:58:24 +0000920 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000921 llvm::APSInt maxElements(elementIndex.getBitWidth(),
922 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000923 bool maxElementsKnown = false;
924 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000925 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000926 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000927 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000928 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000929 maxElementsKnown = true;
930 }
931
Chris Lattner08202542009-02-24 22:50:46 +0000932 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000933 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000934 while (Index < IList->getNumInits()) {
935 Expr *Init = IList->getInit(Index);
936 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000937 // If we're not the subobject that matches up with the '{' for
938 // the designator, we shouldn't be handling the
939 // designator. Return immediately.
940 if (!SubobjectIsDesignatorContext)
941 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000942
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000943 // Handle this designated initializer. elementIndex will be
944 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000945 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000946 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000947 StructuredList, StructuredIndex, true,
948 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000949 hadError = true;
950 continue;
951 }
952
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000953 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
954 maxElements.extend(elementIndex.getBitWidth());
955 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
956 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000957 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000958
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000959 // If the array is of incomplete type, keep track of the number of
960 // elements in the initializer.
961 if (!maxElementsKnown && elementIndex > maxElements)
962 maxElements = elementIndex;
963
Douglas Gregor05c13a32009-01-22 00:58:24 +0000964 continue;
965 }
966
967 // If we know the maximum number of elements, and we've already
968 // hit it, stop consuming elements in the initializer list.
969 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000970 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000971
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000972 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000973 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000974 Entity);
975 // Check this element.
976 CheckSubElementType(ElementEntity, IList, elementType, Index,
977 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000978 ++elementIndex;
979
980 // If the array is of incomplete type, keep track of the number of
981 // elements in the initializer.
982 if (!maxElementsKnown && elementIndex > maxElements)
983 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000984 }
Eli Friedman587cbdf2009-05-29 20:17:55 +0000985 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000986 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000987 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000988 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000989 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000990 // Sizing an array implicitly to zero is not allowed by ISO C,
991 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000992 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000993 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000994 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000995
Mike Stump1eb44332009-09-09 15:08:12 +0000996 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000997 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000998 }
999}
1000
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001001void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001002 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001003 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001004 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001005 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001006 unsigned &Index,
1007 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001008 unsigned &StructuredIndex,
1009 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001010 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Eli Friedmanb85f7072008-05-19 19:16:24 +00001012 // If the record is invalid, some of it's members are invalid. To avoid
1013 // confusion, we forgo checking the intializer for the entire record.
1014 if (structDecl->isInvalidDecl()) {
1015 hadError = true;
1016 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001017 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001018
1019 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1020 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001021 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001022 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001023 Field != FieldEnd; ++Field) {
1024 if (Field->getDeclName()) {
1025 StructuredList->setInitializedFieldInUnion(*Field);
1026 break;
1027 }
1028 }
1029 return;
1030 }
1031
Douglas Gregor05c13a32009-01-22 00:58:24 +00001032 // If structDecl is a forward declaration, this loop won't do
1033 // anything except look at designated initializers; That's okay,
1034 // because an error should get printed out elsewhere. It might be
1035 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001036 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001037 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001038 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001039 while (Index < IList->getNumInits()) {
1040 Expr *Init = IList->getInit(Index);
1041
1042 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001043 // If we're not the subobject that matches up with the '{' for
1044 // the designator, we shouldn't be handling the
1045 // designator. Return immediately.
1046 if (!SubobjectIsDesignatorContext)
1047 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001048
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001049 // Handle this designated initializer. Field will be updated to
1050 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001051 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001052 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001053 StructuredList, StructuredIndex,
1054 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001055 hadError = true;
1056
Douglas Gregordfb5e592009-02-12 19:00:39 +00001057 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001058 continue;
1059 }
1060
1061 if (Field == FieldEnd) {
1062 // We've run out of fields. We're done.
1063 break;
1064 }
1065
Douglas Gregordfb5e592009-02-12 19:00:39 +00001066 // We've already initialized a member of a union. We're done.
1067 if (InitializedSomething && DeclType->isUnionType())
1068 break;
1069
Douglas Gregor44b43212008-12-11 16:49:14 +00001070 // If we've hit the flexible array member at the end, we're done.
1071 if (Field->getType()->isIncompleteArrayType())
1072 break;
1073
Douglas Gregor0bb76892009-01-29 16:53:55 +00001074 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001075 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001076 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001077 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001078 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001079
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001080 InitializedEntity MemberEntity =
1081 InitializedEntity::InitializeMember(*Field, &Entity);
1082 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1083 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001084 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001085
1086 if (DeclType->isUnionType()) {
1087 // Initialize the first field within the union.
1088 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001089 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001090
1091 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001092 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001093
Mike Stump1eb44332009-09-09 15:08:12 +00001094 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001095 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001096 return;
1097
1098 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001099 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001100 (!isa<InitListExpr>(IList->getInit(Index)) ||
1101 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001102 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001103 diag::err_flexible_array_init_nonempty)
1104 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001105 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001106 << *Field;
1107 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001108 ++Index;
1109 return;
1110 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001111 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001112 diag::ext_flexible_array_init)
1113 << IList->getInit(Index)->getSourceRange().getBegin();
1114 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1115 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001116 }
1117
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001118 InitializedEntity MemberEntity =
1119 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001120
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001121 if (isa<InitListExpr>(IList->getInit(Index)))
1122 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1123 StructuredList, StructuredIndex);
1124 else
1125 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001126 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001127}
Steve Naroff0cca7492008-05-01 22:18:59 +00001128
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001129/// \brief Expand a field designator that refers to a member of an
1130/// anonymous struct or union into a series of field designators that
1131/// refers to the field within the appropriate subobject.
1132///
1133/// Field/FieldIndex will be updated to point to the (new)
1134/// currently-designated field.
1135static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001136 DesignatedInitExpr *DIE,
1137 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001138 FieldDecl *Field,
1139 RecordDecl::field_iterator &FieldIter,
1140 unsigned &FieldIndex) {
1141 typedef DesignatedInitExpr::Designator Designator;
1142
1143 // Build the path from the current object to the member of the
1144 // anonymous struct/union (backwards).
1145 llvm::SmallVector<FieldDecl *, 4> Path;
1146 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001148 // Build the replacement designators.
1149 llvm::SmallVector<Designator, 4> Replacements;
1150 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1151 FI = Path.rbegin(), FIEnd = Path.rend();
1152 FI != FIEnd; ++FI) {
1153 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001154 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001155 DIE->getDesignator(DesigIdx)->getDotLoc(),
1156 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1157 else
1158 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1159 SourceLocation()));
1160 Replacements.back().setField(*FI);
1161 }
1162
1163 // Expand the current designator into the set of replacement
1164 // designators, so we have a full subobject path down to where the
1165 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001166 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001167 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001169 // Update FieldIter/FieldIndex;
1170 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001171 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001172 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001173 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001174 FieldIter != FEnd; ++FieldIter) {
1175 if (FieldIter->isUnnamedBitfield())
1176 continue;
1177
1178 if (*FieldIter == Path.back())
1179 return;
1180
1181 ++FieldIndex;
1182 }
1183
1184 assert(false && "Unable to find anonymous struct/union field");
1185}
1186
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187/// @brief Check the well-formedness of a C99 designated initializer.
1188///
1189/// Determines whether the designated initializer @p DIE, which
1190/// resides at the given @p Index within the initializer list @p
1191/// IList, is well-formed for a current object of type @p DeclType
1192/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001193/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001194/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001195///
1196/// @param IList The initializer list in which this designated
1197/// initializer occurs.
1198///
Douglas Gregor71199712009-04-15 04:56:10 +00001199/// @param DIE The designated initializer expression.
1200///
1201/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001202///
1203/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1204/// into which the designation in @p DIE should refer.
1205///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001206/// @param NextField If non-NULL and the first designator in @p DIE is
1207/// a field, this will be set to the field declaration corresponding
1208/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001209///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001210/// @param NextElementIndex If non-NULL and the first designator in @p
1211/// DIE is an array designator or GNU array-range designator, this
1212/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001213///
1214/// @param Index Index into @p IList where the designated initializer
1215/// @p DIE occurs.
1216///
Douglas Gregor4c678342009-01-28 21:54:33 +00001217/// @param StructuredList The initializer list expression that
1218/// describes all of the subobject initializers in the order they'll
1219/// actually be initialized.
1220///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001221/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001222bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001223InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001224 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001225 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001226 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001227 QualType &CurrentObjectType,
1228 RecordDecl::field_iterator *NextField,
1229 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001230 unsigned &Index,
1231 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001232 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001233 bool FinishSubobjectInit,
1234 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001235 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001236 // Check the actual initialization for the designated object type.
1237 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001238
1239 // Temporarily remove the designator expression from the
1240 // initializer list that the child calls see, so that we don't try
1241 // to re-process the designator.
1242 unsigned OldIndex = Index;
1243 IList->setInit(OldIndex, DIE->getInit());
1244
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001245 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001246 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001247
1248 // Restore the designated initializer expression in the syntactic
1249 // form of the initializer list.
1250 if (IList->getInit(OldIndex) != DIE->getInit())
1251 DIE->setInit(IList->getInit(OldIndex));
1252 IList->setInit(OldIndex, DIE);
1253
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001254 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001255 }
1256
Douglas Gregor71199712009-04-15 04:56:10 +00001257 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001258 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001259 "Need a non-designated initializer list to start from");
1260
Douglas Gregor71199712009-04-15 04:56:10 +00001261 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001262 // Determine the structural initializer list that corresponds to the
1263 // current subobject.
1264 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001265 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001266 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001267 SourceRange(D->getStartLocation(),
1268 DIE->getSourceRange().getEnd()));
1269 assert(StructuredList && "Expected a structured initializer list");
1270
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001271 if (D->isFieldDesignator()) {
1272 // C99 6.7.8p7:
1273 //
1274 // If a designator has the form
1275 //
1276 // . identifier
1277 //
1278 // then the current object (defined below) shall have
1279 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001280 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001281 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001282 if (!RT) {
1283 SourceLocation Loc = D->getDotLoc();
1284 if (Loc.isInvalid())
1285 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001286 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1287 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001288 ++Index;
1289 return true;
1290 }
1291
Douglas Gregor4c678342009-01-28 21:54:33 +00001292 // Note: we perform a linear search of the fields here, despite
1293 // the fact that we have a faster lookup method, because we always
1294 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001295 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001296 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001297 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001298 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001299 Field = RT->getDecl()->field_begin(),
1300 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001301 for (; Field != FieldEnd; ++Field) {
1302 if (Field->isUnnamedBitfield())
1303 continue;
1304
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001305 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001306 break;
1307
1308 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001309 }
1310
Douglas Gregor4c678342009-01-28 21:54:33 +00001311 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001312 // There was no normal field in the struct with the designated
1313 // name. Perform another lookup for this name, which may find
1314 // something that we can't designate (e.g., a member function),
1315 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001316 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001317 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001318 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001319 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001320 // Name lookup didn't find anything. Determine whether this
1321 // was a typo for another field name.
1322 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1323 Sema::LookupMemberName);
1324 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1325 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1326 ReplacementField->getDeclContext()->getLookupContext()
1327 ->Equals(RT->getDecl())) {
1328 SemaRef.Diag(D->getFieldLoc(),
1329 diag::err_field_designator_unknown_suggest)
1330 << FieldName << CurrentObjectType << R.getLookupName()
1331 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1332 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001333 SemaRef.Diag(ReplacementField->getLocation(),
1334 diag::note_previous_decl)
1335 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001336 } else {
1337 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1338 << FieldName << CurrentObjectType;
1339 ++Index;
1340 return true;
1341 }
1342 } else if (!KnownField) {
1343 // Determine whether we found a field at all.
1344 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1345 }
1346
1347 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001348 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001349 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001350 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001351 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001352 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001353 ++Index;
1354 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001355 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001356
1357 if (!KnownField &&
1358 cast<RecordDecl>((ReplacementField)->getDeclContext())
1359 ->isAnonymousStructOrUnion()) {
1360 // Handle an field designator that refers to a member of an
1361 // anonymous struct or union.
1362 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1363 ReplacementField,
1364 Field, FieldIndex);
1365 D = DIE->getDesignator(DesigIdx);
1366 } else if (!KnownField) {
1367 // The replacement field comes from typo correction; find it
1368 // in the list of fields.
1369 FieldIndex = 0;
1370 Field = RT->getDecl()->field_begin();
1371 for (; Field != FieldEnd; ++Field) {
1372 if (Field->isUnnamedBitfield())
1373 continue;
1374
1375 if (ReplacementField == *Field ||
1376 Field->getIdentifier() == ReplacementField->getIdentifier())
1377 break;
1378
1379 ++FieldIndex;
1380 }
1381 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001382 } else if (!KnownField &&
1383 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001384 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001385 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1386 Field, FieldIndex);
1387 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001388 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001389
1390 // All of the fields of a union are located at the same place in
1391 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001392 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001394 StructuredList->setInitializedFieldInUnion(*Field);
1395 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001396
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001397 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001398 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Douglas Gregor4c678342009-01-28 21:54:33 +00001400 // Make sure that our non-designated initializer list has space
1401 // for a subobject corresponding to this field.
1402 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001403 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001404
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001405 // This designator names a flexible array member.
1406 if (Field->getType()->isIncompleteArrayType()) {
1407 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001408 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001409 // We can't designate an object within the flexible array
1410 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001411 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001412 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001413 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001414 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001415 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001416 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001417 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001418 << *Field;
1419 Invalid = true;
1420 }
1421
1422 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1423 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001424 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001425 diag::err_flexible_array_init_needs_braces)
1426 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001427 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001428 << *Field;
1429 Invalid = true;
1430 }
1431
1432 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001433 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001434 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001435 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001436 diag::err_flexible_array_init_nonempty)
1437 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001438 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001439 << *Field;
1440 Invalid = true;
1441 }
1442
1443 if (Invalid) {
1444 ++Index;
1445 return true;
1446 }
1447
1448 // Initialize the array.
1449 bool prevHadError = hadError;
1450 unsigned newStructuredIndex = FieldIndex;
1451 unsigned OldIndex = Index;
1452 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001453
1454 InitializedEntity MemberEntity =
1455 InitializedEntity::InitializeMember(*Field, &Entity);
1456 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001457 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001458
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001459 IList->setInit(OldIndex, DIE);
1460 if (hadError && !prevHadError) {
1461 ++Field;
1462 ++FieldIndex;
1463 if (NextField)
1464 *NextField = Field;
1465 StructuredIndex = FieldIndex;
1466 return true;
1467 }
1468 } else {
1469 // Recurse to check later designated subobjects.
1470 QualType FieldType = (*Field)->getType();
1471 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001472
1473 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001474 InitializedEntity::InitializeMember(*Field, &Entity);
1475 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001476 FieldType, 0, 0, Index,
1477 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001478 true, false))
1479 return true;
1480 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001481
1482 // Find the position of the next field to be initialized in this
1483 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001484 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001485 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001486
1487 // If this the first designator, our caller will continue checking
1488 // the rest of this struct/class/union subobject.
1489 if (IsFirstDesignator) {
1490 if (NextField)
1491 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001492 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001493 return false;
1494 }
1495
Douglas Gregor34e79462009-01-28 23:36:17 +00001496 if (!FinishSubobjectInit)
1497 return false;
1498
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001499 // We've already initialized something in the union; we're done.
1500 if (RT->getDecl()->isUnion())
1501 return hadError;
1502
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001503 // Check the remaining fields within this class/struct/union subobject.
1504 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001505
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001506 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001507 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001508 return hadError && !prevHadError;
1509 }
1510
1511 // C99 6.7.8p6:
1512 //
1513 // If a designator has the form
1514 //
1515 // [ constant-expression ]
1516 //
1517 // then the current object (defined below) shall have array
1518 // type and the expression shall be an integer constant
1519 // expression. If the array is of unknown size, any
1520 // nonnegative value is valid.
1521 //
1522 // Additionally, cope with the GNU extension that permits
1523 // designators of the form
1524 //
1525 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001526 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001528 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001529 << CurrentObjectType;
1530 ++Index;
1531 return true;
1532 }
1533
1534 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001535 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1536 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001537 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001538 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001539 DesignatedEndIndex = DesignatedStartIndex;
1540 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001541 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001542
Mike Stump1eb44332009-09-09 15:08:12 +00001543
1544 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001545 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001546 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001547 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001548 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001549
Chris Lattner3bf68932009-04-25 21:59:05 +00001550 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001551 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001552 }
1553
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001554 if (isa<ConstantArrayType>(AT)) {
1555 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001556 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1557 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1558 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1559 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1560 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001561 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001562 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001563 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001564 << IndexExpr->getSourceRange();
1565 ++Index;
1566 return true;
1567 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001568 } else {
1569 // Make sure the bit-widths and signedness match.
1570 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1571 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001572 else if (DesignatedStartIndex.getBitWidth() <
1573 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001574 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1575 DesignatedStartIndex.setIsUnsigned(true);
1576 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001577 }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Douglas Gregor4c678342009-01-28 21:54:33 +00001579 // Make sure that our non-designated initializer list has space
1580 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001581 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001582 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001583 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001584
Douglas Gregor34e79462009-01-28 23:36:17 +00001585 // Repeatedly perform subobject initializations in the range
1586 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001587
Douglas Gregor34e79462009-01-28 23:36:17 +00001588 // Move to the next designator
1589 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1590 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001591
1592 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001593 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001594
Douglas Gregor34e79462009-01-28 23:36:17 +00001595 while (DesignatedStartIndex <= DesignatedEndIndex) {
1596 // Recurse to check later designated subobjects.
1597 QualType ElementType = AT->getElementType();
1598 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001599
1600 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001601 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001602 ElementType, 0, 0, Index,
1603 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001604 (DesignatedStartIndex == DesignatedEndIndex),
1605 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001606 return true;
1607
1608 // Move to the next index in the array that we'll be initializing.
1609 ++DesignatedStartIndex;
1610 ElementIndex = DesignatedStartIndex.getZExtValue();
1611 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001612
1613 // If this the first designator, our caller will continue checking
1614 // the rest of this array subobject.
1615 if (IsFirstDesignator) {
1616 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001617 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001618 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001619 return false;
1620 }
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Douglas Gregor34e79462009-01-28 23:36:17 +00001622 if (!FinishSubobjectInit)
1623 return false;
1624
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001625 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001626 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001627 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001628 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001629 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001630 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001631}
1632
Douglas Gregor4c678342009-01-28 21:54:33 +00001633// Get the structured initializer list for a subobject of type
1634// @p CurrentObjectType.
1635InitListExpr *
1636InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1637 QualType CurrentObjectType,
1638 InitListExpr *StructuredList,
1639 unsigned StructuredIndex,
1640 SourceRange InitRange) {
1641 Expr *ExistingInit = 0;
1642 if (!StructuredList)
1643 ExistingInit = SyntacticToSemantic[IList];
1644 else if (StructuredIndex < StructuredList->getNumInits())
1645 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Douglas Gregor4c678342009-01-28 21:54:33 +00001647 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1648 return Result;
1649
1650 if (ExistingInit) {
1651 // We are creating an initializer list that initializes the
1652 // subobjects of the current object, but there was already an
1653 // initialization that completely initialized the current
1654 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001655 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001656 // struct X { int a, b; };
1657 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001658 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001659 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1660 // designated initializer re-initializes the whole
1661 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001662 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001663 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001664 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001665 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001666 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001667 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001668 << ExistingInit->getSourceRange();
1669 }
1670
Mike Stump1eb44332009-09-09 15:08:12 +00001671 InitListExpr *Result
1672 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001673 InitRange.getEnd());
1674
Douglas Gregor4c678342009-01-28 21:54:33 +00001675 Result->setType(CurrentObjectType);
1676
Douglas Gregorfa219202009-03-20 23:58:33 +00001677 // Pre-allocate storage for the structured initializer list.
1678 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001679 unsigned NumInits = 0;
1680 if (!StructuredList)
1681 NumInits = IList->getNumInits();
1682 else if (Index < IList->getNumInits()) {
1683 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1684 NumInits = SubList->getNumInits();
1685 }
1686
Mike Stump1eb44332009-09-09 15:08:12 +00001687 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001688 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1689 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1690 NumElements = CAType->getSize().getZExtValue();
1691 // Simple heuristic so that we don't allocate a very large
1692 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001693 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001694 NumElements = 0;
1695 }
John McCall183700f2009-09-21 23:43:11 +00001696 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001697 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001698 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001699 RecordDecl *RDecl = RType->getDecl();
1700 if (RDecl->isUnion())
1701 NumElements = 1;
1702 else
Mike Stump1eb44332009-09-09 15:08:12 +00001703 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001704 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001705 }
1706
Douglas Gregor08457732009-03-21 18:13:52 +00001707 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001708 NumElements = IList->getNumInits();
1709
1710 Result->reserveInits(NumElements);
1711
Douglas Gregor4c678342009-01-28 21:54:33 +00001712 // Link this new initializer list into the structured initializer
1713 // lists.
1714 if (StructuredList)
1715 StructuredList->updateInit(StructuredIndex, Result);
1716 else {
1717 Result->setSyntacticForm(IList);
1718 SyntacticToSemantic[IList] = Result;
1719 }
1720
1721 return Result;
1722}
1723
1724/// Update the initializer at index @p StructuredIndex within the
1725/// structured initializer list to the value @p expr.
1726void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1727 unsigned &StructuredIndex,
1728 Expr *expr) {
1729 // No structured initializer list to update
1730 if (!StructuredList)
1731 return;
1732
1733 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1734 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001735 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001736 diag::warn_initializer_overrides)
1737 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001738 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001739 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001740 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001741 << PrevInit->getSourceRange();
1742 }
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Douglas Gregor4c678342009-01-28 21:54:33 +00001744 ++StructuredIndex;
1745}
1746
Douglas Gregor05c13a32009-01-22 00:58:24 +00001747/// Check that the given Index expression is a valid array designator
1748/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001749/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001750/// and produces a reasonable diagnostic if there is a
1751/// failure. Returns true if there was an error, false otherwise. If
1752/// everything went okay, Value will receive the value of the constant
1753/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001754static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001755CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001756 SourceLocation Loc = Index->getSourceRange().getBegin();
1757
1758 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001759 if (S.VerifyIntegerConstantExpression(Index, &Value))
1760 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001761
Chris Lattner3bf68932009-04-25 21:59:05 +00001762 if (Value.isSigned() && Value.isNegative())
1763 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001764 << Value.toString(10) << Index->getSourceRange();
1765
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001766 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001767 return false;
1768}
1769
1770Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1771 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001772 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001773 OwningExprResult Init) {
1774 typedef DesignatedInitExpr::Designator ASTDesignator;
1775
1776 bool Invalid = false;
1777 llvm::SmallVector<ASTDesignator, 32> Designators;
1778 llvm::SmallVector<Expr *, 32> InitExpressions;
1779
1780 // Build designators and check array designator expressions.
1781 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1782 const Designator &D = Desig.getDesignator(Idx);
1783 switch (D.getKind()) {
1784 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001785 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001786 D.getFieldLoc()));
1787 break;
1788
1789 case Designator::ArrayDesignator: {
1790 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1791 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001792 if (!Index->isTypeDependent() &&
1793 !Index->isValueDependent() &&
1794 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001795 Invalid = true;
1796 else {
1797 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001798 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001799 D.getRBracketLoc()));
1800 InitExpressions.push_back(Index);
1801 }
1802 break;
1803 }
1804
1805 case Designator::ArrayRangeDesignator: {
1806 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1807 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1808 llvm::APSInt StartValue;
1809 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001810 bool StartDependent = StartIndex->isTypeDependent() ||
1811 StartIndex->isValueDependent();
1812 bool EndDependent = EndIndex->isTypeDependent() ||
1813 EndIndex->isValueDependent();
1814 if ((!StartDependent &&
1815 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1816 (!EndDependent &&
1817 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001818 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001819 else {
1820 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001821 if (StartDependent || EndDependent) {
1822 // Nothing to compute.
1823 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001824 EndValue.extend(StartValue.getBitWidth());
1825 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1826 StartValue.extend(EndValue.getBitWidth());
1827
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001828 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001829 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001830 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001831 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1832 Invalid = true;
1833 } else {
1834 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001835 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001836 D.getEllipsisLoc(),
1837 D.getRBracketLoc()));
1838 InitExpressions.push_back(StartIndex);
1839 InitExpressions.push_back(EndIndex);
1840 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001841 }
1842 break;
1843 }
1844 }
1845 }
1846
1847 if (Invalid || Init.isInvalid())
1848 return ExprError();
1849
1850 // Clear out the expressions within the designation.
1851 Desig.ClearExprs(*this);
1852
1853 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001854 = DesignatedInitExpr::Create(Context,
1855 Designators.data(), Designators.size(),
1856 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001857 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001858 return Owned(DIE);
1859}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001860
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001861bool Sema::CheckInitList(const InitializedEntity &Entity,
1862 InitListExpr *&InitList, QualType &DeclType) {
1863 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001864 if (!CheckInitList.HadError())
1865 InitList = CheckInitList.getFullyStructuredList();
1866
1867 return CheckInitList.HadError();
1868}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001869
Douglas Gregor20093b42009-12-09 23:02:17 +00001870//===----------------------------------------------------------------------===//
1871// Initialization entity
1872//===----------------------------------------------------------------------===//
1873
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001874InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1875 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001876 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001877{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001878 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1879 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001880 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001881 } else {
1882 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001883 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001884 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001885}
1886
1887InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1888 CXXBaseSpecifier *Base)
1889{
1890 InitializedEntity Result;
1891 Result.Kind = EK_Base;
1892 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001893 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001894 return Result;
1895}
1896
Douglas Gregor99a2e602009-12-16 01:38:02 +00001897DeclarationName InitializedEntity::getName() const {
1898 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001899 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001900 if (!VariableOrMember)
1901 return DeclarationName();
1902 // Fall through
1903
1904 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001905 case EK_Member:
1906 return VariableOrMember->getDeclName();
1907
1908 case EK_Result:
1909 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001910 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001911 case EK_Temporary:
1912 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001913 case EK_ArrayElement:
1914 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001915 return DeclarationName();
1916 }
1917
1918 // Silence GCC warning
1919 return DeclarationName();
1920}
1921
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001922DeclaratorDecl *InitializedEntity::getDecl() const {
1923 switch (getKind()) {
1924 case EK_Variable:
1925 case EK_Parameter:
1926 case EK_Member:
1927 return VariableOrMember;
1928
1929 case EK_Result:
1930 case EK_Exception:
1931 case EK_New:
1932 case EK_Temporary:
1933 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001934 case EK_ArrayElement:
1935 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001936 return 0;
1937 }
1938
1939 // Silence GCC warning
1940 return 0;
1941}
1942
Douglas Gregor20093b42009-12-09 23:02:17 +00001943//===----------------------------------------------------------------------===//
1944// Initialization sequence
1945//===----------------------------------------------------------------------===//
1946
1947void InitializationSequence::Step::Destroy() {
1948 switch (Kind) {
1949 case SK_ResolveAddressOfOverloadedFunction:
1950 case SK_CastDerivedToBaseRValue:
1951 case SK_CastDerivedToBaseLValue:
1952 case SK_BindReference:
1953 case SK_BindReferenceToTemporary:
1954 case SK_UserConversion:
1955 case SK_QualificationConversionRValue:
1956 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001957 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001958 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001959 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001960 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001961 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001962 break;
1963
1964 case SK_ConversionSequence:
1965 delete ICS;
1966 }
1967}
1968
1969void InitializationSequence::AddAddressOverloadResolutionStep(
1970 FunctionDecl *Function) {
1971 Step S;
1972 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1973 S.Type = Function->getType();
1974 S.Function = Function;
1975 Steps.push_back(S);
1976}
1977
1978void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1979 bool IsLValue) {
1980 Step S;
1981 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1982 S.Type = BaseType;
1983 Steps.push_back(S);
1984}
1985
1986void InitializationSequence::AddReferenceBindingStep(QualType T,
1987 bool BindingTemporary) {
1988 Step S;
1989 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1990 S.Type = T;
1991 Steps.push_back(S);
1992}
1993
Eli Friedman03981012009-12-11 02:42:07 +00001994void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1995 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001996 Step S;
1997 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00001998 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00001999 S.Function = Function;
2000 Steps.push_back(S);
2001}
2002
2003void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2004 bool IsLValue) {
2005 Step S;
2006 S.Kind = IsLValue? SK_QualificationConversionLValue
2007 : SK_QualificationConversionRValue;
2008 S.Type = Ty;
2009 Steps.push_back(S);
2010}
2011
2012void InitializationSequence::AddConversionSequenceStep(
2013 const ImplicitConversionSequence &ICS,
2014 QualType T) {
2015 Step S;
2016 S.Kind = SK_ConversionSequence;
2017 S.Type = T;
2018 S.ICS = new ImplicitConversionSequence(ICS);
2019 Steps.push_back(S);
2020}
2021
Douglas Gregord87b61f2009-12-10 17:56:55 +00002022void InitializationSequence::AddListInitializationStep(QualType T) {
2023 Step S;
2024 S.Kind = SK_ListInitialization;
2025 S.Type = T;
2026 Steps.push_back(S);
2027}
2028
Douglas Gregor51c56d62009-12-14 20:49:26 +00002029void
2030InitializationSequence::AddConstructorInitializationStep(
2031 CXXConstructorDecl *Constructor,
2032 QualType T) {
2033 Step S;
2034 S.Kind = SK_ConstructorInitialization;
2035 S.Type = T;
2036 S.Function = Constructor;
2037 Steps.push_back(S);
2038}
2039
Douglas Gregor71d17402009-12-15 00:01:57 +00002040void InitializationSequence::AddZeroInitializationStep(QualType T) {
2041 Step S;
2042 S.Kind = SK_ZeroInitialization;
2043 S.Type = T;
2044 Steps.push_back(S);
2045}
2046
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002047void InitializationSequence::AddCAssignmentStep(QualType T) {
2048 Step S;
2049 S.Kind = SK_CAssignment;
2050 S.Type = T;
2051 Steps.push_back(S);
2052}
2053
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002054void InitializationSequence::AddStringInitStep(QualType T) {
2055 Step S;
2056 S.Kind = SK_StringInit;
2057 S.Type = T;
2058 Steps.push_back(S);
2059}
2060
Douglas Gregor20093b42009-12-09 23:02:17 +00002061void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2062 OverloadingResult Result) {
2063 SequenceKind = FailedSequence;
2064 this->Failure = Failure;
2065 this->FailedOverloadResult = Result;
2066}
2067
2068//===----------------------------------------------------------------------===//
2069// Attempt initialization
2070//===----------------------------------------------------------------------===//
2071
2072/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002073static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002074 const InitializedEntity &Entity,
2075 const InitializationKind &Kind,
2076 InitListExpr *InitList,
2077 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002078 // FIXME: We only perform rudimentary checking of list
2079 // initializations at this point, then assume that any list
2080 // initialization of an array, aggregate, or scalar will be
2081 // well-formed. We we actually "perform" list initialization, we'll
2082 // do all of the necessary checking. C++0x initializer lists will
2083 // force us to perform more checking here.
2084 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2085
Douglas Gregord6542d82009-12-22 15:35:07 +00002086 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002087
2088 // C++ [dcl.init]p13:
2089 // If T is a scalar type, then a declaration of the form
2090 //
2091 // T x = { a };
2092 //
2093 // is equivalent to
2094 //
2095 // T x = a;
2096 if (DestType->isScalarType()) {
2097 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2098 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2099 return;
2100 }
2101
2102 // Assume scalar initialization from a single value works.
2103 } else if (DestType->isAggregateType()) {
2104 // Assume aggregate initialization works.
2105 } else if (DestType->isVectorType()) {
2106 // Assume vector initialization works.
2107 } else if (DestType->isReferenceType()) {
2108 // FIXME: C++0x defines behavior for this.
2109 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2110 return;
2111 } else if (DestType->isRecordType()) {
2112 // FIXME: C++0x defines behavior for this
2113 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2114 }
2115
2116 // Add a general "list initialization" step.
2117 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002118}
2119
2120/// \brief Try a reference initialization that involves calling a conversion
2121/// function.
2122///
2123/// FIXME: look intos DRs 656, 896
2124static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2125 const InitializedEntity &Entity,
2126 const InitializationKind &Kind,
2127 Expr *Initializer,
2128 bool AllowRValues,
2129 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002130 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002131 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2132 QualType T1 = cv1T1.getUnqualifiedType();
2133 QualType cv2T2 = Initializer->getType();
2134 QualType T2 = cv2T2.getUnqualifiedType();
2135
2136 bool DerivedToBase;
2137 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2138 T1, T2, DerivedToBase) &&
2139 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002140 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002141
2142 // Build the candidate set directly in the initialization sequence
2143 // structure, so that it will persist if we fail.
2144 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2145 CandidateSet.clear();
2146
2147 // Determine whether we are allowed to call explicit constructors or
2148 // explicit conversion operators.
2149 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2150
2151 const RecordType *T1RecordType = 0;
2152 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2153 // The type we're converting to is a class type. Enumerate its constructors
2154 // to see if there is a suitable conversion.
2155 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2156
2157 DeclarationName ConstructorName
2158 = S.Context.DeclarationNames.getCXXConstructorName(
2159 S.Context.getCanonicalType(T1).getUnqualifiedType());
2160 DeclContext::lookup_iterator Con, ConEnd;
2161 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2162 Con != ConEnd; ++Con) {
2163 // Find the constructor (which may be a template).
2164 CXXConstructorDecl *Constructor = 0;
2165 FunctionTemplateDecl *ConstructorTmpl
2166 = dyn_cast<FunctionTemplateDecl>(*Con);
2167 if (ConstructorTmpl)
2168 Constructor = cast<CXXConstructorDecl>(
2169 ConstructorTmpl->getTemplatedDecl());
2170 else
2171 Constructor = cast<CXXConstructorDecl>(*Con);
2172
2173 if (!Constructor->isInvalidDecl() &&
2174 Constructor->isConvertingConstructor(AllowExplicit)) {
2175 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002176 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2177 ConstructorTmpl->getAccess(),
2178 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002179 &Initializer, 1, CandidateSet);
2180 else
John McCall86820f52010-01-26 01:37:31 +00002181 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2182 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002183 }
2184 }
2185 }
2186
2187 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2188 // The type we're converting from is a class type, enumerate its conversion
2189 // functions.
2190 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2191
2192 // Determine the type we are converting to. If we are allowed to
2193 // convert to an rvalue, take the type that the destination type
2194 // refers to.
2195 QualType ToType = AllowRValues? cv1T1 : DestType;
2196
John McCalleec51cf2010-01-20 00:46:10 +00002197 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002198 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002199 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2200 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002201 NamedDecl *D = *I;
2202 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2203 if (isa<UsingShadowDecl>(D))
2204 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2205
2206 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2207 CXXConversionDecl *Conv;
2208 if (ConvTemplate)
2209 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2210 else
2211 Conv = cast<CXXConversionDecl>(*I);
2212
2213 // If the conversion function doesn't return a reference type,
2214 // it can't be considered for this conversion unless we're allowed to
2215 // consider rvalues.
2216 // FIXME: Do we need to make sure that we only consider conversion
2217 // candidates with reference-compatible results? That might be needed to
2218 // break recursion.
2219 if ((AllowExplicit || !Conv->isExplicit()) &&
2220 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2221 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00002222 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2223 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002224 ToType, CandidateSet);
2225 else
John McCall86820f52010-01-26 01:37:31 +00002226 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2227 Initializer, cv1T1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002228 }
2229 }
2230 }
2231
2232 SourceLocation DeclLoc = Initializer->getLocStart();
2233
2234 // Perform overload resolution. If it fails, return the failed result.
2235 OverloadCandidateSet::iterator Best;
2236 if (OverloadingResult Result
2237 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2238 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002239
Douglas Gregor20093b42009-12-09 23:02:17 +00002240 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002241
2242 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002243 if (isa<CXXConversionDecl>(Function))
2244 T2 = Function->getResultType();
2245 else
2246 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002247
2248 // Add the user-defined conversion step.
2249 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2250
2251 // Determine whether we need to perform derived-to-base or
2252 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002253 bool NewDerivedToBase = false;
2254 Sema::ReferenceCompareResult NewRefRelationship
2255 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2256 NewDerivedToBase);
2257 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2258 "Overload resolution picked a bad conversion function");
2259 (void)NewRefRelationship;
2260 if (NewDerivedToBase)
2261 Sequence.AddDerivedToBaseCastStep(
2262 S.Context.getQualifiedType(T1,
2263 T2.getNonReferenceType().getQualifiers()),
2264 /*isLValue=*/true);
2265
2266 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2267 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2268
2269 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2270 return OR_Success;
2271}
2272
2273/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2274static void TryReferenceInitialization(Sema &S,
2275 const InitializedEntity &Entity,
2276 const InitializationKind &Kind,
2277 Expr *Initializer,
2278 InitializationSequence &Sequence) {
2279 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2280
Douglas Gregord6542d82009-12-22 15:35:07 +00002281 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002282 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002283 Qualifiers T1Quals;
2284 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002285 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002286 Qualifiers T2Quals;
2287 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002288 SourceLocation DeclLoc = Initializer->getLocStart();
2289
2290 // If the initializer is the address of an overloaded function, try
2291 // to resolve the overloaded function. If all goes well, T2 is the
2292 // type of the resulting function.
2293 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2294 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2295 T1,
2296 false);
2297 if (!Fn) {
2298 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2299 return;
2300 }
2301
2302 Sequence.AddAddressOverloadResolutionStep(Fn);
2303 cv2T2 = Fn->getType();
2304 T2 = cv2T2.getUnqualifiedType();
2305 }
2306
2307 // FIXME: Rvalue references
2308 bool ForceRValue = false;
2309
2310 // Compute some basic properties of the types and the initializer.
2311 bool isLValueRef = DestType->isLValueReferenceType();
2312 bool isRValueRef = !isLValueRef;
2313 bool DerivedToBase = false;
2314 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2315 Initializer->isLvalue(S.Context);
2316 Sema::ReferenceCompareResult RefRelationship
2317 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2318
2319 // C++0x [dcl.init.ref]p5:
2320 // A reference to type "cv1 T1" is initialized by an expression of type
2321 // "cv2 T2" as follows:
2322 //
2323 // - If the reference is an lvalue reference and the initializer
2324 // expression
2325 OverloadingResult ConvOvlResult = OR_Success;
2326 if (isLValueRef) {
2327 if (InitLvalue == Expr::LV_Valid &&
2328 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2329 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2330 // reference-compatible with "cv2 T2," or
2331 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002332 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002333 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002334 // can occur. However, we do pay attention to whether it is a bit-field
2335 // to decide whether we're actually binding to a temporary created from
2336 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002337 if (DerivedToBase)
2338 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002339 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002340 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002341 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002342 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002343 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
2344 Initializer->getBitField();
2345 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002346 return;
2347 }
2348
2349 // - has a class type (i.e., T2 is a class type), where T1 is not
2350 // reference-related to T2, and can be implicitly converted to an
2351 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2352 // with "cv3 T3" (this conversion is selected by enumerating the
2353 // applicable conversion functions (13.3.1.6) and choosing the best
2354 // one through overload resolution (13.3)),
2355 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2356 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2357 Initializer,
2358 /*AllowRValues=*/false,
2359 Sequence);
2360 if (ConvOvlResult == OR_Success)
2361 return;
John McCall1d318332010-01-12 00:44:57 +00002362 if (ConvOvlResult != OR_No_Viable_Function) {
2363 Sequence.SetOverloadFailure(
2364 InitializationSequence::FK_ReferenceInitOverloadFailed,
2365 ConvOvlResult);
2366 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002367 }
2368 }
2369
2370 // - Otherwise, the reference shall be an lvalue reference to a
2371 // non-volatile const type (i.e., cv1 shall be const), or the reference
2372 // shall be an rvalue reference and the initializer expression shall
2373 // be an rvalue.
Douglas Gregoref06e242010-01-29 19:39:15 +00002374 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002375 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2376 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2377 Sequence.SetOverloadFailure(
2378 InitializationSequence::FK_ReferenceInitOverloadFailed,
2379 ConvOvlResult);
2380 else if (isLValueRef)
2381 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2382 ? (RefRelationship == Sema::Ref_Related
2383 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2384 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2385 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2386 else
2387 Sequence.SetFailed(
2388 InitializationSequence::FK_RValueReferenceBindingToLValue);
2389
2390 return;
2391 }
2392
2393 // - If T1 and T2 are class types and
2394 if (T1->isRecordType() && T2->isRecordType()) {
2395 // - the initializer expression is an rvalue and "cv1 T1" is
2396 // reference-compatible with "cv2 T2", or
2397 if (InitLvalue != Expr::LV_Valid &&
2398 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2399 if (DerivedToBase)
2400 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002401 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002402 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002403 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002404 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2405 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2406 return;
2407 }
2408
2409 // - T1 is not reference-related to T2 and the initializer expression
2410 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2411 // conversion is selected by enumerating the applicable conversion
2412 // functions (13.3.1.6) and choosing the best one through overload
2413 // resolution (13.3)),
2414 if (RefRelationship == Sema::Ref_Incompatible) {
2415 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2416 Kind, Initializer,
2417 /*AllowRValues=*/true,
2418 Sequence);
2419 if (ConvOvlResult)
2420 Sequence.SetOverloadFailure(
2421 InitializationSequence::FK_ReferenceInitOverloadFailed,
2422 ConvOvlResult);
2423
2424 return;
2425 }
2426
2427 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2428 return;
2429 }
2430
2431 // - If the initializer expression is an rvalue, with T2 an array type,
2432 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2433 // is bound to the object represented by the rvalue (see 3.10).
2434 // FIXME: How can an array type be reference-compatible with anything?
2435 // Don't we mean the element types of T1 and T2?
2436
2437 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2438 // from the initializer expression using the rules for a non-reference
2439 // copy initialization (8.5). The reference is then bound to the
2440 // temporary. [...]
2441 // Determine whether we are allowed to call explicit constructors or
2442 // explicit conversion operators.
2443 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2444 ImplicitConversionSequence ICS
2445 = S.TryImplicitConversion(Initializer, cv1T1,
2446 /*SuppressUserConversions=*/false, AllowExplicit,
2447 /*ForceRValue=*/false,
2448 /*FIXME:InOverloadResolution=*/false,
2449 /*UserCast=*/Kind.isExplicitCast());
2450
John McCall1d318332010-01-12 00:44:57 +00002451 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002452 // FIXME: Use the conversion function set stored in ICS to turn
2453 // this into an overloading ambiguity diagnostic. However, we need
2454 // to keep that set as an OverloadCandidateSet rather than as some
2455 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002456 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2457 Sequence.SetOverloadFailure(
2458 InitializationSequence::FK_ReferenceInitOverloadFailed,
2459 ConvOvlResult);
2460 else
2461 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002462 return;
2463 }
2464
2465 // [...] If T1 is reference-related to T2, cv1 must be the
2466 // same cv-qualification as, or greater cv-qualification
2467 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002468 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2469 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002470 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002471 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2473 return;
2474 }
2475
2476 // Perform the actual conversion.
2477 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2478 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2479 return;
2480}
2481
2482/// \brief Attempt character array initialization from a string literal
2483/// (C++ [dcl.init.string], C99 6.7.8).
2484static void TryStringLiteralInitialization(Sema &S,
2485 const InitializedEntity &Entity,
2486 const InitializationKind &Kind,
2487 Expr *Initializer,
2488 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002489 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002490 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002491}
2492
Douglas Gregor20093b42009-12-09 23:02:17 +00002493/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2494/// enumerates the constructors of the initialized entity and performs overload
2495/// resolution to select the best.
2496static void TryConstructorInitialization(Sema &S,
2497 const InitializedEntity &Entity,
2498 const InitializationKind &Kind,
2499 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002500 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002501 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002502 if (Kind.getKind() == InitializationKind::IK_Copy)
2503 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2504 else
2505 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002506
2507 // Build the candidate set directly in the initialization sequence
2508 // structure, so that it will persist if we fail.
2509 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2510 CandidateSet.clear();
2511
2512 // Determine whether we are allowed to call explicit constructors or
2513 // explicit conversion operators.
2514 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2515 Kind.getKind() == InitializationKind::IK_Value ||
2516 Kind.getKind() == InitializationKind::IK_Default);
2517
2518 // The type we're converting to is a class type. Enumerate its constructors
2519 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002520 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2521 assert(DestRecordType && "Constructor initialization requires record type");
2522 CXXRecordDecl *DestRecordDecl
2523 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2524
2525 DeclarationName ConstructorName
2526 = S.Context.DeclarationNames.getCXXConstructorName(
2527 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2528 DeclContext::lookup_iterator Con, ConEnd;
2529 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2530 Con != ConEnd; ++Con) {
2531 // Find the constructor (which may be a template).
2532 CXXConstructorDecl *Constructor = 0;
2533 FunctionTemplateDecl *ConstructorTmpl
2534 = dyn_cast<FunctionTemplateDecl>(*Con);
2535 if (ConstructorTmpl)
2536 Constructor = cast<CXXConstructorDecl>(
2537 ConstructorTmpl->getTemplatedDecl());
2538 else
2539 Constructor = cast<CXXConstructorDecl>(*Con);
2540
2541 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002542 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002543 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002544 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2545 ConstructorTmpl->getAccess(),
2546 /*ExplicitArgs*/ 0,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002547 Args, NumArgs, CandidateSet);
2548 else
John McCall86820f52010-01-26 01:37:31 +00002549 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2550 Args, NumArgs, CandidateSet);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002551 }
2552 }
2553
2554 SourceLocation DeclLoc = Kind.getLocation();
2555
2556 // Perform overload resolution. If it fails, return the failed result.
2557 OverloadCandidateSet::iterator Best;
2558 if (OverloadingResult Result
2559 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2560 Sequence.SetOverloadFailure(
2561 InitializationSequence::FK_ConstructorOverloadFailed,
2562 Result);
2563 return;
2564 }
2565
2566 // Add the constructor initialization step. Any cv-qualification conversion is
2567 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002568 if (Kind.getKind() == InitializationKind::IK_Copy) {
2569 Sequence.AddUserConversionStep(Best->Function, DestType);
2570 } else {
2571 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002572 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002573 DestType);
2574 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002575}
2576
Douglas Gregor71d17402009-12-15 00:01:57 +00002577/// \brief Attempt value initialization (C++ [dcl.init]p7).
2578static void TryValueInitialization(Sema &S,
2579 const InitializedEntity &Entity,
2580 const InitializationKind &Kind,
2581 InitializationSequence &Sequence) {
2582 // C++ [dcl.init]p5:
2583 //
2584 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002585 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002586
2587 // -- if T is an array type, then each element is value-initialized;
2588 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2589 T = AT->getElementType();
2590
2591 if (const RecordType *RT = T->getAs<RecordType>()) {
2592 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2593 // -- if T is a class type (clause 9) with a user-declared
2594 // constructor (12.1), then the default constructor for T is
2595 // called (and the initialization is ill-formed if T has no
2596 // accessible default constructor);
2597 //
2598 // FIXME: we really want to refer to a single subobject of the array,
2599 // but Entity doesn't have a way to capture that (yet).
2600 if (ClassDecl->hasUserDeclaredConstructor())
2601 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2602
Douglas Gregor16006c92009-12-16 18:50:27 +00002603 // -- if T is a (possibly cv-qualified) non-union class type
2604 // without a user-provided constructor, then the object is
2605 // zero-initialized and, if T’s implicitly-declared default
2606 // constructor is non-trivial, that constructor is called.
2607 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2608 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2609 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002610 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002611 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2612 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002613 }
2614 }
2615
Douglas Gregord6542d82009-12-22 15:35:07 +00002616 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002617 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2618}
2619
Douglas Gregor99a2e602009-12-16 01:38:02 +00002620/// \brief Attempt default initialization (C++ [dcl.init]p6).
2621static void TryDefaultInitialization(Sema &S,
2622 const InitializedEntity &Entity,
2623 const InitializationKind &Kind,
2624 InitializationSequence &Sequence) {
2625 assert(Kind.getKind() == InitializationKind::IK_Default);
2626
2627 // C++ [dcl.init]p6:
2628 // To default-initialize an object of type T means:
2629 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002630 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002631 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2632 DestType = Array->getElementType();
2633
2634 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2635 // constructor for T is called (and the initialization is ill-formed if
2636 // T has no accessible default constructor);
2637 if (DestType->isRecordType()) {
2638 // FIXME: If a program calls for the default initialization of an object of
2639 // a const-qualified type T, T shall be a class type with a user-provided
2640 // default constructor.
2641 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2642 Sequence);
2643 }
2644
2645 // - otherwise, no initialization is performed.
2646 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2647
2648 // If a program calls for the default initialization of an object of
2649 // a const-qualified type T, T shall be a class type with a user-provided
2650 // default constructor.
2651 if (DestType.isConstQualified())
2652 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2653}
2654
Douglas Gregor20093b42009-12-09 23:02:17 +00002655/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2656/// which enumerates all conversion functions and performs overload resolution
2657/// to select the best.
2658static void TryUserDefinedConversion(Sema &S,
2659 const InitializedEntity &Entity,
2660 const InitializationKind &Kind,
2661 Expr *Initializer,
2662 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002663 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2664
Douglas Gregord6542d82009-12-22 15:35:07 +00002665 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002666 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2667 QualType SourceType = Initializer->getType();
2668 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2669 "Must have a class type to perform a user-defined conversion");
2670
2671 // Build the candidate set directly in the initialization sequence
2672 // structure, so that it will persist if we fail.
2673 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2674 CandidateSet.clear();
2675
2676 // Determine whether we are allowed to call explicit constructors or
2677 // explicit conversion operators.
2678 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2679
2680 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2681 // The type we're converting to is a class type. Enumerate its constructors
2682 // to see if there is a suitable conversion.
2683 CXXRecordDecl *DestRecordDecl
2684 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2685
2686 DeclarationName ConstructorName
2687 = S.Context.DeclarationNames.getCXXConstructorName(
2688 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2689 DeclContext::lookup_iterator Con, ConEnd;
2690 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2691 Con != ConEnd; ++Con) {
2692 // Find the constructor (which may be a template).
2693 CXXConstructorDecl *Constructor = 0;
2694 FunctionTemplateDecl *ConstructorTmpl
2695 = dyn_cast<FunctionTemplateDecl>(*Con);
2696 if (ConstructorTmpl)
2697 Constructor = cast<CXXConstructorDecl>(
2698 ConstructorTmpl->getTemplatedDecl());
2699 else
2700 Constructor = cast<CXXConstructorDecl>(*Con);
2701
2702 if (!Constructor->isInvalidDecl() &&
2703 Constructor->isConvertingConstructor(AllowExplicit)) {
2704 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00002705 S.AddTemplateOverloadCandidate(ConstructorTmpl,
2706 ConstructorTmpl->getAccess(),
2707 /*ExplicitArgs*/ 0,
Douglas Gregor4a520a22009-12-14 17:27:33 +00002708 &Initializer, 1, CandidateSet);
2709 else
John McCall86820f52010-01-26 01:37:31 +00002710 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
2711 &Initializer, 1, CandidateSet);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002712 }
2713 }
2714 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002715
2716 SourceLocation DeclLoc = Initializer->getLocStart();
2717
Douglas Gregor4a520a22009-12-14 17:27:33 +00002718 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2719 // The type we're converting from is a class type, enumerate its conversion
2720 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002721
Eli Friedman33c2da92009-12-20 22:12:03 +00002722 // We can only enumerate the conversion functions for a complete type; if
2723 // the type isn't complete, simply skip this step.
2724 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2725 CXXRecordDecl *SourceRecordDecl
2726 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002727
John McCalleec51cf2010-01-20 00:46:10 +00002728 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002729 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002730 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002731 E = Conversions->end();
2732 I != E; ++I) {
2733 NamedDecl *D = *I;
2734 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2735 if (isa<UsingShadowDecl>(D))
2736 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2737
2738 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2739 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002740 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002741 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002742 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002743 Conv = cast<CXXConversionDecl>(*I);
2744
2745 if (AllowExplicit || !Conv->isExplicit()) {
2746 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00002747 S.AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
2748 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002749 CandidateSet);
2750 else
John McCall86820f52010-01-26 01:37:31 +00002751 S.AddConversionCandidate(Conv, I.getAccess(), ActingDC,
2752 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002753 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002754 }
2755 }
2756 }
2757
Douglas Gregor4a520a22009-12-14 17:27:33 +00002758 // Perform overload resolution. If it fails, return the failed result.
2759 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002760 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002761 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2762 Sequence.SetOverloadFailure(
2763 InitializationSequence::FK_UserConversionOverloadFailed,
2764 Result);
2765 return;
2766 }
John McCall1d318332010-01-12 00:44:57 +00002767
Douglas Gregor4a520a22009-12-14 17:27:33 +00002768 FunctionDecl *Function = Best->Function;
2769
2770 if (isa<CXXConstructorDecl>(Function)) {
2771 // Add the user-defined conversion step. Any cv-qualification conversion is
2772 // subsumed by the initialization.
2773 Sequence.AddUserConversionStep(Function, DestType);
2774 return;
2775 }
2776
2777 // Add the user-defined conversion step that calls the conversion function.
2778 QualType ConvType = Function->getResultType().getNonReferenceType();
2779 Sequence.AddUserConversionStep(Function, ConvType);
2780
2781 // If the conversion following the call to the conversion function is
2782 // interesting, add it as a separate step.
2783 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2784 Best->FinalConversion.Third) {
2785 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002786 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002787 ICS.Standard = Best->FinalConversion;
2788 Sequence.AddConversionSequenceStep(ICS, DestType);
2789 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002790}
2791
2792/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2793/// non-class type to another.
2794static void TryImplicitConversion(Sema &S,
2795 const InitializedEntity &Entity,
2796 const InitializationKind &Kind,
2797 Expr *Initializer,
2798 InitializationSequence &Sequence) {
2799 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002800 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002801 /*SuppressUserConversions=*/true,
2802 /*AllowExplicit=*/false,
2803 /*ForceRValue=*/false,
2804 /*FIXME:InOverloadResolution=*/false,
2805 /*UserCast=*/Kind.isExplicitCast());
2806
John McCall1d318332010-01-12 00:44:57 +00002807 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002808 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2809 return;
2810 }
2811
Douglas Gregord6542d82009-12-22 15:35:07 +00002812 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002813}
2814
2815InitializationSequence::InitializationSequence(Sema &S,
2816 const InitializedEntity &Entity,
2817 const InitializationKind &Kind,
2818 Expr **Args,
2819 unsigned NumArgs) {
2820 ASTContext &Context = S.Context;
2821
2822 // C++0x [dcl.init]p16:
2823 // The semantics of initializers are as follows. The destination type is
2824 // the type of the object or reference being initialized and the source
2825 // type is the type of the initializer expression. The source type is not
2826 // defined when the initializer is a braced-init-list or when it is a
2827 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002828 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002829
2830 if (DestType->isDependentType() ||
2831 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2832 SequenceKind = DependentSequence;
2833 return;
2834 }
2835
2836 QualType SourceType;
2837 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002838 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002839 Initializer = Args[0];
2840 if (!isa<InitListExpr>(Initializer))
2841 SourceType = Initializer->getType();
2842 }
2843
2844 // - If the initializer is a braced-init-list, the object is
2845 // list-initialized (8.5.4).
2846 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2847 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002848 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002849 }
2850
2851 // - If the destination type is a reference type, see 8.5.3.
2852 if (DestType->isReferenceType()) {
2853 // C++0x [dcl.init.ref]p1:
2854 // A variable declared to be a T& or T&&, that is, "reference to type T"
2855 // (8.3.2), shall be initialized by an object, or function, of type T or
2856 // by an object that can be converted into a T.
2857 // (Therefore, multiple arguments are not permitted.)
2858 if (NumArgs != 1)
2859 SetFailed(FK_TooManyInitsForReference);
2860 else
2861 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2862 return;
2863 }
2864
2865 // - If the destination type is an array of characters, an array of
2866 // char16_t, an array of char32_t, or an array of wchar_t, and the
2867 // initializer is a string literal, see 8.5.2.
2868 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2869 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2870 return;
2871 }
2872
2873 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002874 if (Kind.getKind() == InitializationKind::IK_Value ||
2875 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002876 TryValueInitialization(S, Entity, Kind, *this);
2877 return;
2878 }
2879
Douglas Gregor99a2e602009-12-16 01:38:02 +00002880 // Handle default initialization.
2881 if (Kind.getKind() == InitializationKind::IK_Default){
2882 TryDefaultInitialization(S, Entity, Kind, *this);
2883 return;
2884 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002885
Douglas Gregor20093b42009-12-09 23:02:17 +00002886 // - Otherwise, if the destination type is an array, the program is
2887 // ill-formed.
2888 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2889 if (AT->getElementType()->isAnyCharacterType())
2890 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2891 else
2892 SetFailed(FK_ArrayNeedsInitList);
2893
2894 return;
2895 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002896
2897 // Handle initialization in C
2898 if (!S.getLangOptions().CPlusPlus) {
2899 setSequenceKind(CAssignment);
2900 AddCAssignmentStep(DestType);
2901 return;
2902 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002903
2904 // - If the destination type is a (possibly cv-qualified) class type:
2905 if (DestType->isRecordType()) {
2906 // - If the initialization is direct-initialization, or if it is
2907 // copy-initialization where the cv-unqualified version of the
2908 // source type is the same class as, or a derived class of, the
2909 // class of the destination, constructors are considered. [...]
2910 if (Kind.getKind() == InitializationKind::IK_Direct ||
2911 (Kind.getKind() == InitializationKind::IK_Copy &&
2912 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2913 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002914 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00002915 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002916 // - Otherwise (i.e., for the remaining copy-initialization cases),
2917 // user-defined conversion sequences that can convert from the source
2918 // type to the destination type or (when a conversion function is
2919 // used) to a derived class thereof are enumerated as described in
2920 // 13.3.1.4, and the best one is chosen through overload resolution
2921 // (13.3).
2922 else
2923 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2924 return;
2925 }
2926
Douglas Gregor99a2e602009-12-16 01:38:02 +00002927 if (NumArgs > 1) {
2928 SetFailed(FK_TooManyInitsForScalar);
2929 return;
2930 }
2931 assert(NumArgs == 1 && "Zero-argument case handled above");
2932
Douglas Gregor20093b42009-12-09 23:02:17 +00002933 // - Otherwise, if the source type is a (possibly cv-qualified) class
2934 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002935 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002936 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2937 return;
2938 }
2939
2940 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002941 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002942 // conversions (Clause 4) will be used, if necessary, to convert the
2943 // initializer expression to the cv-unqualified version of the
2944 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002945 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002946 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2947}
2948
2949InitializationSequence::~InitializationSequence() {
2950 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2951 StepEnd = Steps.end();
2952 Step != StepEnd; ++Step)
2953 Step->Destroy();
2954}
2955
2956//===----------------------------------------------------------------------===//
2957// Perform initialization
2958//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002959static Sema::AssignmentAction
2960getAssignmentAction(const InitializedEntity &Entity) {
2961 switch(Entity.getKind()) {
2962 case InitializedEntity::EK_Variable:
2963 case InitializedEntity::EK_New:
2964 return Sema::AA_Initializing;
2965
2966 case InitializedEntity::EK_Parameter:
2967 // FIXME: Can we tell when we're sending vs. passing?
2968 return Sema::AA_Passing;
2969
2970 case InitializedEntity::EK_Result:
2971 return Sema::AA_Returning;
2972
2973 case InitializedEntity::EK_Exception:
2974 case InitializedEntity::EK_Base:
2975 llvm_unreachable("No assignment action for C++-specific initialization");
2976 break;
2977
2978 case InitializedEntity::EK_Temporary:
2979 // FIXME: Can we tell apart casting vs. converting?
2980 return Sema::AA_Casting;
2981
2982 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002983 case InitializedEntity::EK_ArrayElement:
2984 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002985 return Sema::AA_Initializing;
2986 }
2987
2988 return Sema::AA_Converting;
2989}
2990
2991static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2992 bool IsCopy) {
2993 switch (Entity.getKind()) {
2994 case InitializedEntity::EK_Result:
2995 case InitializedEntity::EK_Exception:
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00002996 case InitializedEntity::EK_ArrayElement:
2997 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002998 return !IsCopy;
2999
3000 case InitializedEntity::EK_New:
3001 case InitializedEntity::EK_Variable:
3002 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003003 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003004 return false;
3005
3006 case InitializedEntity::EK_Parameter:
3007 case InitializedEntity::EK_Temporary:
3008 return true;
3009 }
3010
3011 llvm_unreachable("missed an InitializedEntity kind?");
3012}
3013
3014/// \brief If we need to perform an additional copy of the initialized object
3015/// for this kind of entity (e.g., the result of a function or an object being
3016/// thrown), make the copy.
3017static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3018 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003019 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003020 Sema::OwningExprResult CurInit) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003021 Expr *CurInitExpr = (Expr *)CurInit.get();
3022
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003023 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003024
3025 switch (Entity.getKind()) {
3026 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00003027 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003028 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003029 Loc = Entity.getReturnLoc();
3030 break;
3031
3032 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003033 Loc = Entity.getThrowLoc();
3034 break;
3035
3036 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00003037 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003038 Kind.getKind() != InitializationKind::IK_Copy)
3039 return move(CurInit);
3040 Loc = Entity.getDecl()->getLocation();
3041 break;
3042
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003043 case InitializedEntity::EK_ArrayElement:
3044 case InitializedEntity::EK_Member:
3045 if (Entity.getType()->isReferenceType() ||
3046 Kind.getKind() != InitializationKind::IK_Copy)
3047 return move(CurInit);
3048 Loc = CurInitExpr->getLocStart();
3049 break;
3050
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003051 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003052 // FIXME: Do we need this initialization for a parameter?
3053 return move(CurInit);
3054
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003055 case InitializedEntity::EK_New:
3056 case InitializedEntity::EK_Temporary:
3057 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003058 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003059 // We don't need to copy for any of these initialized entities.
3060 return move(CurInit);
3061 }
3062
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003063 CXXRecordDecl *Class = 0;
3064 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3065 Class = cast<CXXRecordDecl>(Record->getDecl());
3066 if (!Class)
3067 return move(CurInit);
3068
3069 // Perform overload resolution using the class's copy constructors.
3070 DeclarationName ConstructorName
3071 = S.Context.DeclarationNames.getCXXConstructorName(
3072 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3073 DeclContext::lookup_iterator Con, ConEnd;
3074 OverloadCandidateSet CandidateSet;
3075 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3076 Con != ConEnd; ++Con) {
3077 // Find the constructor (which may be a template).
3078 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3079 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003080 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003081 continue;
3082
John McCall86820f52010-01-26 01:37:31 +00003083 S.AddOverloadCandidate(Constructor, Constructor->getAccess(),
3084 &CurInitExpr, 1, CandidateSet);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003085 }
3086
3087 OverloadCandidateSet::iterator Best;
3088 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3089 case OR_Success:
3090 break;
3091
3092 case OR_No_Viable_Function:
3093 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003094 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003095 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003096 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3097 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003098 return S.ExprError();
3099
3100 case OR_Ambiguous:
3101 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003102 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003103 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003104 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3105 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003106 return S.ExprError();
3107
3108 case OR_Deleted:
3109 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003110 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003111 << CurInitExpr->getSourceRange();
3112 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3113 << Best->Function->isDeleted();
3114 return S.ExprError();
3115 }
3116
3117 CurInit.release();
3118 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3119 cast<CXXConstructorDecl>(Best->Function),
3120 /*Elidable=*/true,
3121 Sema::MultiExprArg(S,
3122 (void**)&CurInitExpr, 1));
3123}
Douglas Gregor20093b42009-12-09 23:02:17 +00003124
3125Action::OwningExprResult
3126InitializationSequence::Perform(Sema &S,
3127 const InitializedEntity &Entity,
3128 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003129 Action::MultiExprArg Args,
3130 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003131 if (SequenceKind == FailedSequence) {
3132 unsigned NumArgs = Args.size();
3133 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3134 return S.ExprError();
3135 }
3136
3137 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003138 // If the declaration is a non-dependent, incomplete array type
3139 // that has an initializer, then its type will be completed once
3140 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003141 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003142 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003143 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003144 if (const IncompleteArrayType *ArrayT
3145 = S.Context.getAsIncompleteArrayType(DeclType)) {
3146 // FIXME: We don't currently have the ability to accurately
3147 // compute the length of an initializer list without
3148 // performing full type-checking of the initializer list
3149 // (since we have to determine where braces are implicitly
3150 // introduced and such). So, we fall back to making the array
3151 // type a dependently-sized array type with no specified
3152 // bound.
3153 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3154 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003155
Douglas Gregord87b61f2009-12-10 17:56:55 +00003156 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003157 if (DeclaratorDecl *DD = Entity.getDecl()) {
3158 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3159 TypeLoc TL = TInfo->getTypeLoc();
3160 if (IncompleteArrayTypeLoc *ArrayLoc
3161 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3162 Brackets = ArrayLoc->getBracketsRange();
3163 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003164 }
3165
3166 *ResultType
3167 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3168 /*NumElts=*/0,
3169 ArrayT->getSizeModifier(),
3170 ArrayT->getIndexTypeCVRQualifiers(),
3171 Brackets);
3172 }
3173
3174 }
3175 }
3176
Eli Friedman08544622009-12-22 02:35:53 +00003177 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003178 return Sema::OwningExprResult(S, Args.release()[0]);
3179
3180 unsigned NumArgs = Args.size();
3181 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3182 SourceLocation(),
3183 (Expr **)Args.release(),
3184 NumArgs,
3185 SourceLocation()));
3186 }
3187
Douglas Gregor99a2e602009-12-16 01:38:02 +00003188 if (SequenceKind == NoInitialization)
3189 return S.Owned((Expr *)0);
3190
Douglas Gregord6542d82009-12-22 15:35:07 +00003191 QualType DestType = Entity.getType().getNonReferenceType();
3192 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003193 // the same as Entity.getDecl()->getType() in cases involving type merging,
3194 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003195 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003196 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003197 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003198
Douglas Gregor99a2e602009-12-16 01:38:02 +00003199 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3200
3201 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3202
3203 // For initialization steps that start with a single initializer,
3204 // grab the only argument out the Args and place it into the "current"
3205 // initializer.
3206 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003207 case SK_ResolveAddressOfOverloadedFunction:
3208 case SK_CastDerivedToBaseRValue:
3209 case SK_CastDerivedToBaseLValue:
3210 case SK_BindReference:
3211 case SK_BindReferenceToTemporary:
3212 case SK_UserConversion:
3213 case SK_QualificationConversionLValue:
3214 case SK_QualificationConversionRValue:
3215 case SK_ConversionSequence:
3216 case SK_ListInitialization:
3217 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003218 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003219 assert(Args.size() == 1);
3220 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3221 if (CurInit.isInvalid())
3222 return S.ExprError();
3223 break;
3224
3225 case SK_ConstructorInitialization:
3226 case SK_ZeroInitialization:
3227 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003228 }
3229
3230 // Walk through the computed steps for the initialization sequence,
3231 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003232 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003233 for (step_iterator Step = step_begin(), StepEnd = step_end();
3234 Step != StepEnd; ++Step) {
3235 if (CurInit.isInvalid())
3236 return S.ExprError();
3237
3238 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003239 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003240
3241 switch (Step->Kind) {
3242 case SK_ResolveAddressOfOverloadedFunction:
3243 // Overload resolution determined which function invoke; update the
3244 // initializer to reflect that choice.
3245 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3246 break;
3247
3248 case SK_CastDerivedToBaseRValue:
3249 case SK_CastDerivedToBaseLValue: {
3250 // We have a derived-to-base cast that produces either an rvalue or an
3251 // lvalue. Perform that cast.
3252
3253 // Casts to inaccessible base classes are allowed with C-style casts.
3254 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3255 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3256 CurInitExpr->getLocStart(),
3257 CurInitExpr->getSourceRange(),
3258 IgnoreBaseAccess))
3259 return S.ExprError();
3260
3261 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3262 CastExpr::CK_DerivedToBase,
3263 (Expr*)CurInit.release(),
3264 Step->Kind == SK_CastDerivedToBaseLValue));
3265 break;
3266 }
3267
3268 case SK_BindReference:
3269 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3270 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3271 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003272 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003273 << BitField->getDeclName()
3274 << CurInitExpr->getSourceRange();
3275 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3276 return S.ExprError();
3277 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003278
Douglas Gregor20093b42009-12-09 23:02:17 +00003279 // Reference binding does not have any corresponding ASTs.
3280
3281 // Check exception specifications
3282 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3283 return S.ExprError();
3284 break;
3285
3286 case SK_BindReferenceToTemporary:
3287 // Check exception specifications
3288 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3289 return S.ExprError();
3290
3291 // FIXME: At present, we have no AST to describe when we need to make a
3292 // temporary to bind a reference to. We should.
3293 break;
3294
3295 case SK_UserConversion: {
3296 // We have a user-defined conversion that invokes either a constructor
3297 // or a conversion function.
3298 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003299 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003300 if (CXXConstructorDecl *Constructor
3301 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3302 // Build a call to the selected constructor.
3303 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3304 SourceLocation Loc = CurInitExpr->getLocStart();
3305 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3306
3307 // Determine the arguments required to actually perform the constructor
3308 // call.
3309 if (S.CompleteConstructorCall(Constructor,
3310 Sema::MultiExprArg(S,
3311 (void **)&CurInitExpr,
3312 1),
3313 Loc, ConstructorArgs))
3314 return S.ExprError();
3315
3316 // Build the an expression that constructs a temporary.
3317 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3318 move_arg(ConstructorArgs));
3319 if (CurInit.isInvalid())
3320 return S.ExprError();
3321
3322 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003323 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3324 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3325 S.IsDerivedFrom(SourceType, Class))
3326 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003327 } else {
3328 // Build a call to the conversion function.
3329 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003330
Douglas Gregor20093b42009-12-09 23:02:17 +00003331 // FIXME: Should we move this initialization into a separate
3332 // derived-to-base conversion? I believe the answer is "no", because
3333 // we don't want to turn off access control here for c-style casts.
3334 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3335 return S.ExprError();
3336
3337 // Do a little dance to make sure that CurInit has the proper
3338 // pointer.
3339 CurInit.release();
3340
3341 // Build the actual call to the conversion function.
3342 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3343 if (CurInit.isInvalid() || !CurInit.get())
3344 return S.ExprError();
3345
3346 CastKind = CastExpr::CK_UserDefinedConversion;
3347 }
3348
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003349 if (shouldBindAsTemporary(Entity, IsCopy))
3350 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3351
Douglas Gregor20093b42009-12-09 23:02:17 +00003352 CurInitExpr = CurInit.takeAs<Expr>();
3353 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3354 CastKind,
3355 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003356 false));
3357
3358 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003359 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003360 break;
3361 }
3362
3363 case SK_QualificationConversionLValue:
3364 case SK_QualificationConversionRValue:
3365 // Perform a qualification conversion; these can never go wrong.
3366 S.ImpCastExprToType(CurInitExpr, Step->Type,
3367 CastExpr::CK_NoOp,
3368 Step->Kind == SK_QualificationConversionLValue);
3369 CurInit.release();
3370 CurInit = S.Owned(CurInitExpr);
3371 break;
3372
3373 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003374 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003375 false, false, *Step->ICS))
3376 return S.ExprError();
3377
3378 CurInit.release();
3379 CurInit = S.Owned(CurInitExpr);
3380 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003381
3382 case SK_ListInitialization: {
3383 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3384 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003385 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003386 return S.ExprError();
3387
3388 CurInit.release();
3389 CurInit = S.Owned(InitList);
3390 break;
3391 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003392
3393 case SK_ConstructorInitialization: {
3394 CXXConstructorDecl *Constructor
3395 = cast<CXXConstructorDecl>(Step->Function);
3396
3397 // Build a call to the selected constructor.
3398 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3399 SourceLocation Loc = Kind.getLocation();
3400
3401 // Determine the arguments required to actually perform the constructor
3402 // call.
3403 if (S.CompleteConstructorCall(Constructor, move(Args),
3404 Loc, ConstructorArgs))
3405 return S.ExprError();
3406
3407 // Build the an expression that constructs a temporary.
Douglas Gregord6542d82009-12-22 15:35:07 +00003408 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor745880f2009-12-20 22:01:25 +00003409 Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003410 move_arg(ConstructorArgs),
3411 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003412 if (CurInit.isInvalid())
3413 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003414
3415 bool Elidable
3416 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3417 if (shouldBindAsTemporary(Entity, Elidable))
3418 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3419
3420 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003421 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003422 break;
3423 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003424
3425 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003426 step_iterator NextStep = Step;
3427 ++NextStep;
3428 if (NextStep != StepEnd &&
3429 NextStep->Kind == SK_ConstructorInitialization) {
3430 // The need for zero-initialization is recorded directly into
3431 // the call to the object's constructor within the next step.
3432 ConstructorInitRequiresZeroInit = true;
3433 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3434 S.getLangOptions().CPlusPlus &&
3435 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003436 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3437 Kind.getRange().getBegin(),
3438 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003439 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003440 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003441 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003442 break;
3443 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003444
3445 case SK_CAssignment: {
3446 QualType SourceType = CurInitExpr->getType();
3447 Sema::AssignConvertType ConvTy =
3448 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003449
3450 // If this is a call, allow conversion to a transparent union.
3451 if (ConvTy != Sema::Compatible &&
3452 Entity.getKind() == InitializedEntity::EK_Parameter &&
3453 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3454 == Sema::Compatible)
3455 ConvTy = Sema::Compatible;
3456
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003457 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3458 Step->Type, SourceType,
3459 CurInitExpr, getAssignmentAction(Entity)))
3460 return S.ExprError();
3461
3462 CurInit.release();
3463 CurInit = S.Owned(CurInitExpr);
3464 break;
3465 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003466
3467 case SK_StringInit: {
3468 QualType Ty = Step->Type;
3469 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3470 break;
3471 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003472 }
3473 }
3474
3475 return move(CurInit);
3476}
3477
3478//===----------------------------------------------------------------------===//
3479// Diagnose initialization failures
3480//===----------------------------------------------------------------------===//
3481bool InitializationSequence::Diagnose(Sema &S,
3482 const InitializedEntity &Entity,
3483 const InitializationKind &Kind,
3484 Expr **Args, unsigned NumArgs) {
3485 if (SequenceKind != FailedSequence)
3486 return false;
3487
Douglas Gregord6542d82009-12-22 15:35:07 +00003488 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003489 switch (Failure) {
3490 case FK_TooManyInitsForReference:
3491 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3492 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3493 break;
3494
3495 case FK_ArrayNeedsInitList:
3496 case FK_ArrayNeedsInitListOrStringLiteral:
3497 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3498 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3499 break;
3500
3501 case FK_AddressOfOverloadFailed:
3502 S.ResolveAddressOfOverloadedFunction(Args[0],
3503 DestType.getNonReferenceType(),
3504 true);
3505 break;
3506
3507 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003508 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003509 switch (FailedOverloadResult) {
3510 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003511 if (Failure == FK_UserConversionOverloadFailed)
3512 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3513 << Args[0]->getType() << DestType
3514 << Args[0]->getSourceRange();
3515 else
3516 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3517 << DestType << Args[0]->getType()
3518 << Args[0]->getSourceRange();
3519
John McCallcbce6062010-01-12 07:18:19 +00003520 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3521 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003522 break;
3523
3524 case OR_No_Viable_Function:
3525 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3526 << Args[0]->getType() << DestType.getNonReferenceType()
3527 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003528 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3529 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003530 break;
3531
3532 case OR_Deleted: {
3533 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3534 << Args[0]->getType() << DestType.getNonReferenceType()
3535 << Args[0]->getSourceRange();
3536 OverloadCandidateSet::iterator Best;
3537 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3538 Kind.getLocation(),
3539 Best);
3540 if (Ovl == OR_Deleted) {
3541 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3542 << Best->Function->isDeleted();
3543 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003544 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003545 }
3546 break;
3547 }
3548
3549 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003550 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003551 break;
3552 }
3553 break;
3554
3555 case FK_NonConstLValueReferenceBindingToTemporary:
3556 case FK_NonConstLValueReferenceBindingToUnrelated:
3557 S.Diag(Kind.getLocation(),
3558 Failure == FK_NonConstLValueReferenceBindingToTemporary
3559 ? diag::err_lvalue_reference_bind_to_temporary
3560 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00003561 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003562 << DestType.getNonReferenceType()
3563 << Args[0]->getType()
3564 << Args[0]->getSourceRange();
3565 break;
3566
3567 case FK_RValueReferenceBindingToLValue:
3568 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3569 << Args[0]->getSourceRange();
3570 break;
3571
3572 case FK_ReferenceInitDropsQualifiers:
3573 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3574 << DestType.getNonReferenceType()
3575 << Args[0]->getType()
3576 << Args[0]->getSourceRange();
3577 break;
3578
3579 case FK_ReferenceInitFailed:
3580 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3581 << DestType.getNonReferenceType()
3582 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3583 << Args[0]->getType()
3584 << Args[0]->getSourceRange();
3585 break;
3586
3587 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003588 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3589 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003590 << DestType
3591 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3592 << Args[0]->getType()
3593 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003594 break;
3595
3596 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003597 SourceRange R;
3598
3599 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3600 R = SourceRange(InitList->getInit(1)->getLocStart(),
3601 InitList->getLocEnd());
3602 else
3603 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003604
3605 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003606 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003607 break;
3608 }
3609
3610 case FK_ReferenceBindingToInitList:
3611 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3612 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3613 break;
3614
3615 case FK_InitListBadDestinationType:
3616 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3617 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3618 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003619
3620 case FK_ConstructorOverloadFailed: {
3621 SourceRange ArgsRange;
3622 if (NumArgs)
3623 ArgsRange = SourceRange(Args[0]->getLocStart(),
3624 Args[NumArgs - 1]->getLocEnd());
3625
3626 // FIXME: Using "DestType" for the entity we're printing is probably
3627 // bad.
3628 switch (FailedOverloadResult) {
3629 case OR_Ambiguous:
3630 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3631 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003632 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003633 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003634 break;
3635
3636 case OR_No_Viable_Function:
3637 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3638 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003639 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3640 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003641 break;
3642
3643 case OR_Deleted: {
3644 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3645 << true << DestType << ArgsRange;
3646 OverloadCandidateSet::iterator Best;
3647 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3648 Kind.getLocation(),
3649 Best);
3650 if (Ovl == OR_Deleted) {
3651 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3652 << Best->Function->isDeleted();
3653 } else {
3654 llvm_unreachable("Inconsistent overload resolution?");
3655 }
3656 break;
3657 }
3658
3659 case OR_Success:
3660 llvm_unreachable("Conversion did not fail!");
3661 break;
3662 }
3663 break;
3664 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003665
3666 case FK_DefaultInitOfConst:
3667 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3668 << DestType;
3669 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003670 }
3671
3672 return true;
3673}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003674
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003675void InitializationSequence::dump(llvm::raw_ostream &OS) const {
3676 switch (SequenceKind) {
3677 case FailedSequence: {
3678 OS << "Failed sequence: ";
3679 switch (Failure) {
3680 case FK_TooManyInitsForReference:
3681 OS << "too many initializers for reference";
3682 break;
3683
3684 case FK_ArrayNeedsInitList:
3685 OS << "array requires initializer list";
3686 break;
3687
3688 case FK_ArrayNeedsInitListOrStringLiteral:
3689 OS << "array requires initializer list or string literal";
3690 break;
3691
3692 case FK_AddressOfOverloadFailed:
3693 OS << "address of overloaded function failed";
3694 break;
3695
3696 case FK_ReferenceInitOverloadFailed:
3697 OS << "overload resolution for reference initialization failed";
3698 break;
3699
3700 case FK_NonConstLValueReferenceBindingToTemporary:
3701 OS << "non-const lvalue reference bound to temporary";
3702 break;
3703
3704 case FK_NonConstLValueReferenceBindingToUnrelated:
3705 OS << "non-const lvalue reference bound to unrelated type";
3706 break;
3707
3708 case FK_RValueReferenceBindingToLValue:
3709 OS << "rvalue reference bound to an lvalue";
3710 break;
3711
3712 case FK_ReferenceInitDropsQualifiers:
3713 OS << "reference initialization drops qualifiers";
3714 break;
3715
3716 case FK_ReferenceInitFailed:
3717 OS << "reference initialization failed";
3718 break;
3719
3720 case FK_ConversionFailed:
3721 OS << "conversion failed";
3722 break;
3723
3724 case FK_TooManyInitsForScalar:
3725 OS << "too many initializers for scalar";
3726 break;
3727
3728 case FK_ReferenceBindingToInitList:
3729 OS << "referencing binding to initializer list";
3730 break;
3731
3732 case FK_InitListBadDestinationType:
3733 OS << "initializer list for non-aggregate, non-scalar type";
3734 break;
3735
3736 case FK_UserConversionOverloadFailed:
3737 OS << "overloading failed for user-defined conversion";
3738 break;
3739
3740 case FK_ConstructorOverloadFailed:
3741 OS << "constructor overloading failed";
3742 break;
3743
3744 case FK_DefaultInitOfConst:
3745 OS << "default initialization of a const variable";
3746 break;
3747 }
3748 OS << '\n';
3749 return;
3750 }
3751
3752 case DependentSequence:
3753 OS << "Dependent sequence: ";
3754 return;
3755
3756 case UserDefinedConversion:
3757 OS << "User-defined conversion sequence: ";
3758 break;
3759
3760 case ConstructorInitialization:
3761 OS << "Constructor initialization sequence: ";
3762 break;
3763
3764 case ReferenceBinding:
3765 OS << "Reference binding: ";
3766 break;
3767
3768 case ListInitialization:
3769 OS << "List initialization: ";
3770 break;
3771
3772 case ZeroInitialization:
3773 OS << "Zero initialization\n";
3774 return;
3775
3776 case NoInitialization:
3777 OS << "No initialization\n";
3778 return;
3779
3780 case StandardConversion:
3781 OS << "Standard conversion: ";
3782 break;
3783
3784 case CAssignment:
3785 OS << "C assignment: ";
3786 break;
3787
3788 case StringInit:
3789 OS << "String initialization: ";
3790 break;
3791 }
3792
3793 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
3794 if (S != step_begin()) {
3795 OS << " -> ";
3796 }
3797
3798 switch (S->Kind) {
3799 case SK_ResolveAddressOfOverloadedFunction:
3800 OS << "resolve address of overloaded function";
3801 break;
3802
3803 case SK_CastDerivedToBaseRValue:
3804 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
3805 break;
3806
3807 case SK_CastDerivedToBaseLValue:
3808 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
3809 break;
3810
3811 case SK_BindReference:
3812 OS << "bind reference to lvalue";
3813 break;
3814
3815 case SK_BindReferenceToTemporary:
3816 OS << "bind reference to a temporary";
3817 break;
3818
3819 case SK_UserConversion:
3820 OS << "user-defined conversion via " << S->Function->getNameAsString();
3821 break;
3822
3823 case SK_QualificationConversionRValue:
3824 OS << "qualification conversion (rvalue)";
3825
3826 case SK_QualificationConversionLValue:
3827 OS << "qualification conversion (lvalue)";
3828 break;
3829
3830 case SK_ConversionSequence:
3831 OS << "implicit conversion sequence (";
3832 S->ICS->DebugPrint(); // FIXME: use OS
3833 OS << ")";
3834 break;
3835
3836 case SK_ListInitialization:
3837 OS << "list initialization";
3838 break;
3839
3840 case SK_ConstructorInitialization:
3841 OS << "constructor initialization";
3842 break;
3843
3844 case SK_ZeroInitialization:
3845 OS << "zero initialization";
3846 break;
3847
3848 case SK_CAssignment:
3849 OS << "C assignment";
3850 break;
3851
3852 case SK_StringInit:
3853 OS << "string initialization";
3854 break;
3855 }
3856 }
3857}
3858
3859void InitializationSequence::dump() const {
3860 dump(llvm::errs());
3861}
3862
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003863//===----------------------------------------------------------------------===//
3864// Initialization helper functions
3865//===----------------------------------------------------------------------===//
3866Sema::OwningExprResult
3867Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3868 SourceLocation EqualLoc,
3869 OwningExprResult Init) {
3870 if (Init.isInvalid())
3871 return ExprError();
3872
3873 Expr *InitE = (Expr *)Init.get();
3874 assert(InitE && "No initialization expression?");
3875
3876 if (EqualLoc.isInvalid())
3877 EqualLoc = InitE->getLocStart();
3878
3879 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3880 EqualLoc);
3881 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3882 Init.release();
3883 return Seq.Perform(*this, Entity, Kind,
3884 MultiExprArg(*this, (void**)&InitE, 1));
3885}