blob: 05dd56275c365c9f4b6b25f43a40a56162bde261 [file] [log] [blame]
Steve Narofff8ecff22008-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 Lattner0cb78032009-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 Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Sema.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000022#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000025#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000028#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000029#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000030using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000031
Chris Lattner0cb78032009-02-24 22:27:37 +000032//===----------------------------------------------------------------------===//
33// Sema Initialization Checking
34//===----------------------------------------------------------------------===//
35
Chris Lattnerd8b741c82009-02-24 23:10:27 +000036static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000037 const ArrayType *AT = Context.getAsArrayType(DeclType);
38 if (!AT) return 0;
39
Eli Friedman893abe42009-05-29 18:22:49 +000040 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
41 return 0;
42
Chris Lattnera9196812009-02-26 23:26:43 +000043 // See if this is a string literal or @encode.
44 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000045
Chris Lattnera9196812009-02-26 23:26:43 +000046 // Handle @encode, which is a narrow string.
47 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
48 return Init;
49
50 // Otherwise we can only handle string literals.
51 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000052 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000053
54 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000055 // char array can be initialized with a narrow string.
56 // Only allow char x[] = "foo"; not char x[] = L"foo";
57 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000059
Eli Friedman42a84652009-05-31 10:54:53 +000060 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
61 // correction from DR343): "An array with element type compatible with a
62 // qualified or unqualified version of wchar_t may be initialized by a wide
63 // string literal, optionally enclosed in braces."
64 if (Context.typesAreCompatible(Context.getWCharType(),
65 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000066 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner0cb78032009-02-24 22:27:37 +000068 return 0;
69}
70
Chris Lattnerd8b741c82009-02-24 23:10:27 +000071static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
72 // Get the length of the string as parsed.
73 uint64_t StrLength =
74 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
75
Mike Stump11289f42009-09-09 15:08:12 +000076
Chris Lattnerd8b741c82009-02-24 23:10:27 +000077 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000078 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000079 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000080 // being initialized to a string literal.
81 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000082 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000083 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000084 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
85 ConstVal,
86 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000087 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000088 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Eli Friedman893abe42009-05-29 18:22:49 +000090 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000091
Eli Friedman893abe42009-05-29 18:22:49 +000092 // C99 6.7.8p14. We have an array of character type with known size. However,
93 // the size may be smaller or larger than the string we are initializing.
94 // FIXME: Avoid truncation for 64-bit length strings.
95 if (StrLength-1 > CAT->getSize().getZExtValue())
96 S.Diag(Str->getSourceRange().getBegin(),
97 diag::warn_initializer_string_for_char_array_too_long)
98 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000099
Eli Friedman893abe42009-05-29 18:22:49 +0000100 // Set the type to the actual size that we are initializing. If we have
101 // something like:
102 // char x[1] = "foo";
103 // then this will set the string literal's type to char[1].
104 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000105}
106
Chris Lattner0cb78032009-02-24 22:27:37 +0000107//===----------------------------------------------------------------------===//
108// Semantic checking for initializer lists.
109//===----------------------------------------------------------------------===//
110
Douglas Gregorcde232f2009-01-29 01:05:33 +0000111/// @brief Semantic checking for initializer lists.
112///
113/// The InitListChecker class contains a set of routines that each
114/// handle the initialization of a certain kind of entity, e.g.,
115/// arrays, vectors, struct/union types, scalars, etc. The
116/// InitListChecker itself performs a recursive walk of the subobject
117/// structure of the type to be initialized, while stepping through
118/// the initializer list one element at a time. The IList and Index
119/// parameters to each of the Check* routines contain the active
120/// (syntactic) initializer list and the index into that initializer
121/// list that represents the current initializer. Each routine is
122/// responsible for moving that Index forward as it consumes elements.
123///
124/// Each Check* routine also has a StructuredList/StructuredIndex
125/// arguments, which contains the current the "structured" (semantic)
126/// initializer list and the index into that initializer list where we
127/// are copying initializers as we map them over to the semantic
128/// list. Once we have completed our recursive walk of the subobject
129/// structure, we will have constructed a full semantic initializer
130/// list.
131///
132/// C99 designators cause changes in the initializer list traversal,
133/// because they make the initialization "jump" into a specific
134/// subobject and then continue the initialization from that
135/// point. CheckDesignatedInitializer() recursively steps into the
136/// designated subobject and manages backing out the recursion to
137/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000138namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000139class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000140 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000141 bool hadError;
142 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
143 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000144
Anders Carlsson6cabf312010-01-23 23:23:01 +0000145 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000146 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000147 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000148 unsigned &StructuredIndex,
149 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000150 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000151 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000152 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000153 unsigned &StructuredIndex,
154 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000155 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000156 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000157 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000158 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000159 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000160 unsigned &StructuredIndex,
161 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000162 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000163 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000164 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000165 InitListExpr *StructuredList,
166 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000167 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000168 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000169 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000170 InitListExpr *StructuredList,
171 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000172 void CheckReferenceType(const InitializedEntity &Entity,
173 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000174 unsigned &Index,
175 InitListExpr *StructuredList,
176 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000178 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000179 InitListExpr *StructuredList,
180 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000182 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000183 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000184 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000185 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000190 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
193 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000194 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000195 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000196 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000197 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000198 RecordDecl::field_iterator *NextField,
199 llvm::APSInt *NextElementIndex,
200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000203 bool FinishSubobjectInit,
204 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
206 QualType CurrentObjectType,
207 InitListExpr *StructuredList,
208 unsigned StructuredIndex,
209 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000210 void UpdateStructuredListElement(InitListExpr *StructuredList,
211 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000212 Expr *expr);
213 int numArrayElements(QualType DeclType);
214 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000215
Douglas Gregor2bb07652009-12-22 00:05:34 +0000216 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
217 const InitializedEntity &ParentEntity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000219 void FillInValueInitializations(const InitializedEntity &Entity,
220 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000221public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000222 InitListChecker(Sema &S, const InitializedEntity &Entity,
223 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000224 bool HadError() { return hadError; }
225
226 // @brief Retrieves the fully-structured initializer list used for
227 // semantic analysis and code generation.
228 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
229};
Chris Lattner9ececce2009-02-24 22:48:58 +0000230} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000231
Douglas Gregor2bb07652009-12-22 00:05:34 +0000232void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
233 const InitializedEntity &ParentEntity,
234 InitListExpr *ILE,
235 bool &RequiresSecondPass) {
236 SourceLocation Loc = ILE->getSourceRange().getBegin();
237 unsigned NumInits = ILE->getNumInits();
238 InitializedEntity MemberEntity
239 = InitializedEntity::InitializeMember(Field, &ParentEntity);
240 if (Init >= NumInits || !ILE->getInit(Init)) {
241 // FIXME: We probably don't need to handle references
242 // specially here, since value-initialization of references is
243 // handled in InitializationSequence.
244 if (Field->getType()->isReferenceType()) {
245 // C++ [dcl.init.aggr]p9:
246 // If an incomplete or empty initializer-list leaves a
247 // member of reference type uninitialized, the program is
248 // ill-formed.
249 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
250 << Field->getType()
251 << ILE->getSyntacticForm()->getSourceRange();
252 SemaRef.Diag(Field->getLocation(),
253 diag::note_uninit_reference_member);
254 hadError = true;
255 return;
256 }
257
258 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
259 true);
260 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
261 if (!InitSeq) {
262 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
263 hadError = true;
264 return;
265 }
266
John McCalldadc5752010-08-24 06:29:42 +0000267 ExprResult MemberInit
Douglas Gregor2bb07652009-12-22 00:05:34 +0000268 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
269 Sema::MultiExprArg(SemaRef, 0, 0));
270 if (MemberInit.isInvalid()) {
271 hadError = true;
272 return;
273 }
274
275 if (hadError) {
276 // Do nothing
277 } else if (Init < NumInits) {
278 ILE->setInit(Init, MemberInit.takeAs<Expr>());
279 } else if (InitSeq.getKind()
280 == InitializationSequence::ConstructorInitialization) {
281 // Value-initialization requires a constructor call, so
282 // extend the initializer list to include the constructor
283 // call and make a note that we'll need to take another pass
284 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000285 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000286 RequiresSecondPass = true;
287 }
288 } else if (InitListExpr *InnerILE
289 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
290 FillInValueInitializations(MemberEntity, InnerILE,
291 RequiresSecondPass);
292}
293
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000294/// Recursively replaces NULL values within the given initializer list
295/// with expressions that perform value-initialization of the
296/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000297void
298InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
299 InitListExpr *ILE,
300 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000301 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000302 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000303 SourceLocation Loc = ILE->getSourceRange().getBegin();
304 if (ILE->getSyntacticForm())
305 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000306
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000307 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000308 if (RType->getDecl()->isUnion() &&
309 ILE->getInitializedFieldInUnion())
310 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
311 Entity, ILE, RequiresSecondPass);
312 else {
313 unsigned Init = 0;
314 for (RecordDecl::field_iterator
315 Field = RType->getDecl()->field_begin(),
316 FieldEnd = RType->getDecl()->field_end();
317 Field != FieldEnd; ++Field) {
318 if (Field->isUnnamedBitfield())
319 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000320
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000322 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000323
324 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
325 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000326 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000327
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000329
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 // Only look at the first initialization of a union.
331 if (RType->getDecl()->isUnion())
332 break;
333 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000334 }
335
336 return;
Mike Stump11289f42009-09-09 15:08:12 +0000337 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000338
339 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000340
Douglas Gregor723796a2009-12-16 06:35:08 +0000341 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000342 unsigned NumInits = ILE->getNumInits();
343 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000344 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000345 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000346 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
347 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000348 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
349 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000350 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000351 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000352 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000353 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
354 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000355 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000356 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000357
Douglas Gregor723796a2009-12-16 06:35:08 +0000358
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000359 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000360 if (hadError)
361 return;
362
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000363 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
364 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000365 ElementEntity.setElementIndex(Init);
366
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000367 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000368 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
369 true);
370 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
371 if (!InitSeq) {
372 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000373 hadError = true;
374 return;
375 }
376
John McCalldadc5752010-08-24 06:29:42 +0000377 ExprResult ElementInit
Douglas Gregor723796a2009-12-16 06:35:08 +0000378 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
379 Sema::MultiExprArg(SemaRef, 0, 0));
380 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000381 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000382 return;
383 }
384
385 if (hadError) {
386 // Do nothing
387 } else if (Init < NumInits) {
388 ILE->setInit(Init, ElementInit.takeAs<Expr>());
389 } else if (InitSeq.getKind()
390 == InitializationSequence::ConstructorInitialization) {
391 // Value-initialization requires a constructor call, so
392 // extend the initializer list to include the constructor
393 // call and make a note that we'll need to take another pass
394 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000395 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000396 RequiresSecondPass = true;
397 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000398 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000399 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
400 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000401 }
402}
403
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000404
Douglas Gregor723796a2009-12-16 06:35:08 +0000405InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
406 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000407 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000408 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000409
Eli Friedman23a9e312008-05-19 19:16:24 +0000410 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000411 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000412 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000413 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000414 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000415 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000416 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000417
Douglas Gregor723796a2009-12-16 06:35:08 +0000418 if (!hadError) {
419 bool RequiresSecondPass = false;
420 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000421 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000422 FillInValueInitializations(Entity, FullyStructuredList,
423 RequiresSecondPass);
424 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000425}
426
427int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000428 // FIXME: use a proper constant
429 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000430 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000431 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000432 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
433 }
434 return maxElements;
435}
436
437int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000438 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000439 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000440 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000441 Field = structDecl->field_begin(),
442 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000443 Field != FieldEnd; ++Field) {
444 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
445 ++InitializableMembers;
446 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000447 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000448 return std::min(InitializableMembers, 1);
449 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000450}
451
Anders Carlsson6cabf312010-01-23 23:23:01 +0000452void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000453 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000454 QualType T, unsigned &Index,
455 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000456 unsigned &StructuredIndex,
457 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000458 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000459
Steve Narofff8ecff22008-05-01 22:18:59 +0000460 if (T->isArrayType())
461 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000462 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000463 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000464 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000465 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000466 else
467 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000468
Eli Friedmane0f832b2008-05-25 13:49:22 +0000469 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000470 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000471 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000472 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000473 hadError = true;
474 return;
475 }
476
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000477 // Build a structured initializer list corresponding to this subobject.
478 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000479 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
480 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000481 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
482 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000483 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000484
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000485 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000486 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000487 CheckListElementTypes(Entity, ParentIList, T,
488 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000489 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000490 StructuredSubobjectInitIndex,
491 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000492 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000493 StructuredSubobjectInitList->setType(T);
494
Douglas Gregor5741efb2009-03-01 17:12:46 +0000495 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000496 // range corresponds with the end of the last initializer it used.
497 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000498 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000499 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
500 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
501 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000502
503 // Warn about missing braces.
504 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000505 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
506 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000507 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000508 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
509 "{")
510 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner5cb196e2010-03-07 04:47:12 +0000511 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000512 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000513 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000514}
515
Anders Carlsson6cabf312010-01-23 23:23:01 +0000516void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000517 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000518 unsigned &Index,
519 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000520 unsigned &StructuredIndex,
521 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000522 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000523 SyntacticToSemantic[IList] = StructuredList;
524 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000525 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
526 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000527 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
528 IList->setType(ExprTy);
529 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000530 if (hadError)
531 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000532
Eli Friedman85f54972008-05-25 13:22:35 +0000533 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000534 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000535 if (StructuredIndex == 1 &&
536 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000537 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000538 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000539 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000540 hadError = true;
541 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000542 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000543 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000544 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000545 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000546 // Don't complain for incomplete types, since we'll get an error
547 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000548 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000549 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000550 CurrentObjectType->isArrayType()? 0 :
551 CurrentObjectType->isVectorType()? 1 :
552 CurrentObjectType->isScalarType()? 2 :
553 CurrentObjectType->isUnionType()? 3 :
554 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000555
556 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000557 if (SemaRef.getLangOptions().CPlusPlus) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Nate Begeman425038c2009-07-07 21:53:06 +0000561 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
562 DK = diag::err_excess_initializers;
563 hadError = true;
564 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000565
Chris Lattnerb0912a52009-02-24 22:50:46 +0000566 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000567 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000568 }
569 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000570
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000571 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000572 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000573 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000574 << FixItHint::CreateRemoval(IList->getLocStart())
575 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000576}
577
Anders Carlsson6cabf312010-01-23 23:23:01 +0000578void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000579 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000580 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000581 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000582 unsigned &Index,
583 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000584 unsigned &StructuredIndex,
585 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000586 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000587 CheckScalarType(Entity, IList, DeclType, Index,
588 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000589 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000590 CheckVectorType(Entity, IList, DeclType, Index,
591 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000592 } else if (DeclType->isAggregateType()) {
593 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000594 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000595 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000596 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 StructuredList, StructuredIndex,
598 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000599 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000600 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000601 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000602 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000603 CheckArrayType(Entity, IList, DeclType, Zero,
604 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000605 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000607 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000608 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
609 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000610 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000613 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000614 } else if (DeclType->isRecordType()) {
615 // C++ [dcl.init]p14:
616 // [...] If the class is an aggregate (8.5.1), and the initializer
617 // is a brace-enclosed list, see 8.5.1.
618 //
619 // Note: 8.5.1 is handled below; here, we diagnose the case where
620 // we have an initializer list and a destination type that is not
621 // an aggregate.
622 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000623 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000624 << DeclType << IList->getSourceRange();
625 hadError = true;
626 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000627 CheckReferenceType(Entity, IList, DeclType, Index,
628 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000629 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000630 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
631 << DeclType;
632 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000633 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000634 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
635 << DeclType;
636 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000637 }
638}
639
Anders Carlsson6cabf312010-01-23 23:23:01 +0000640void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000641 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000642 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000643 unsigned &Index,
644 InitListExpr *StructuredList,
645 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000646 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000647 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
648 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000650 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000651 = getStructuredSubobjectInit(IList, Index, ElemType,
652 StructuredList, StructuredIndex,
653 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000654 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000655 newStructuredList, newStructuredIndex);
656 ++StructuredIndex;
657 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000658 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
659 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000660 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000661 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000662 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000663 CheckScalarType(Entity, IList, ElemType, Index,
664 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000665 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000666 CheckReferenceType(Entity, IList, ElemType, Index,
667 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000668 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000669 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000670 // C++ [dcl.init.aggr]p12:
671 // All implicit type conversions (clause 4) are considered when
672 // initializing the aggregate member with an ini- tializer from
673 // an initializer-list. If the initializer can initialize a
674 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000675
Anders Carlsson0bd52402010-01-24 00:19:41 +0000676 // FIXME: Better EqualLoc?
677 InitializationKind Kind =
678 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
679 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
680
681 if (Seq) {
John McCalldadc5752010-08-24 06:29:42 +0000682 ExprResult Result =
Anders Carlsson0bd52402010-01-24 00:19:41 +0000683 Seq.Perform(SemaRef, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +0000684 Sema::MultiExprArg(SemaRef, &expr, 1));
Anders Carlsson0bd52402010-01-24 00:19:41 +0000685 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000686 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000687
688 UpdateStructuredListElement(StructuredList, StructuredIndex,
689 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000690 ++Index;
691 return;
692 }
693
694 // Fall through for subaggregate initialization
695 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000696 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000697 //
698 // The initializer for a structure or union object that has
699 // automatic storage duration shall be either an initializer
700 // list as described below, or a single expression that has
701 // compatible structure or union type. In the latter case, the
702 // initial value of the object, including unnamed members, is
703 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000704 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000705 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000706 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
707 ++Index;
708 return;
709 }
710
711 // Fall through for subaggregate initialization
712 }
713
714 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000715 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000716 // [...] Otherwise, if the member is itself a non-empty
717 // subaggregate, brace elision is assumed and the initializer is
718 // considered for the initialization of the first member of
719 // the subaggregate.
720 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000721 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000722 StructuredIndex);
723 ++StructuredIndex;
724 } else {
725 // We cannot initialize this element, so let
726 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssona18f0fb2010-01-30 01:56:32 +0000727 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
728 SemaRef.Owned(expr));
729 IList->setInit(Index, 0);
Douglas Gregord14247a2009-01-30 22:09:00 +0000730 hadError = true;
731 ++Index;
732 ++StructuredIndex;
733 }
734 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000735}
736
Anders Carlsson6cabf312010-01-23 23:23:01 +0000737void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000738 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000739 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000740 InitListExpr *StructuredList,
741 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000742 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000743 Expr *expr = IList->getInit(Index);
Eli Friedmandf239252010-08-14 03:14:53 +0000744 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
745 SemaRef.Diag(SubIList->getLocStart(),
746 diag::warn_many_braces_around_scalar_init)
747 << SubIList->getSourceRange();
748
749 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
750 StructuredIndex);
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000751 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000752 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000753 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000754 diag::err_designator_for_scalar_init)
755 << DeclType << expr->getSourceRange();
756 hadError = true;
757 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000758 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000759 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000760 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000761
John McCalldadc5752010-08-24 06:29:42 +0000762 ExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000763 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
764 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000765
Chandler Carruthdfe198b2010-02-13 07:23:01 +0000766 Expr *ResultExpr = 0;
Anders Carlsson26d05642010-01-23 18:35:41 +0000767
768 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000769 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000770 else {
771 ResultExpr = Result.takeAs<Expr>();
772
773 if (ResultExpr != expr) {
774 // The type was promoted, update initializer list.
775 IList->setInit(Index, ResultExpr);
776 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000777 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000778 if (hadError)
779 ++StructuredIndex;
780 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000781 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000782 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000783 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000784 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000785 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000786 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000787 ++Index;
788 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000789 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000790 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000791}
792
Anders Carlsson6cabf312010-01-23 23:23:01 +0000793void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
794 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000795 unsigned &Index,
796 InitListExpr *StructuredList,
797 unsigned &StructuredIndex) {
798 if (Index < IList->getNumInits()) {
799 Expr *expr = IList->getInit(Index);
800 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000801 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000802 << DeclType << IList->getSourceRange();
803 hadError = true;
804 ++Index;
805 ++StructuredIndex;
806 return;
Mike Stump11289f42009-09-09 15:08:12 +0000807 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000808
John McCalldadc5752010-08-24 06:29:42 +0000809 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000810 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
811 SemaRef.Owned(expr));
812
813 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000814 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000815
816 expr = Result.takeAs<Expr>();
817 IList->setInit(Index, expr);
818
Douglas Gregord14247a2009-01-30 22:09:00 +0000819 if (hadError)
820 ++StructuredIndex;
821 else
822 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
823 ++Index;
824 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000825 // FIXME: It would be wonderful if we could point at the actual member. In
826 // general, it would be useful to pass location information down the stack,
827 // so that we know the location (or decl) of the "current object" being
828 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000829 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000830 diag::err_init_reference_member_uninitialized)
831 << DeclType
832 << IList->getSourceRange();
833 hadError = true;
834 ++Index;
835 ++StructuredIndex;
836 return;
837 }
838}
839
Anders Carlsson6cabf312010-01-23 23:23:01 +0000840void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000841 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000842 unsigned &Index,
843 InitListExpr *StructuredList,
844 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000845 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000846 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000847 unsigned maxElements = VT->getNumElements();
848 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000849 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000850
Nate Begeman5ec4b312009-08-10 23:49:36 +0000851 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000852 InitializedEntity ElementEntity =
853 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000854
Anders Carlsson6cabf312010-01-23 23:23:01 +0000855 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
856 // Don't attempt to go past the end of the init list
857 if (Index >= IList->getNumInits())
858 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000859
Anders Carlsson6cabf312010-01-23 23:23:01 +0000860 ElementEntity.setElementIndex(Index);
861 CheckSubElementType(ElementEntity, IList, elementType, Index,
862 StructuredList, StructuredIndex);
863 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000864 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000865 InitializedEntity ElementEntity =
866 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
867
Nate Begeman5ec4b312009-08-10 23:49:36 +0000868 // OpenCL initializers allows vectors to be constructed from vectors.
869 for (unsigned i = 0; i < maxElements; ++i) {
870 // Don't attempt to go past the end of the init list
871 if (Index >= IList->getNumInits())
872 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000873
874 ElementEntity.setElementIndex(Index);
875
Nate Begeman5ec4b312009-08-10 23:49:36 +0000876 QualType IType = IList->getInit(Index)->getType();
877 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000878 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000879 StructuredList, StructuredIndex);
880 ++numEltsInit;
881 } else {
Nate Begeman5da51d32010-07-07 22:26:56 +0000882 QualType VecType;
John McCall9dd450b2009-09-21 23:43:11 +0000883 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000884 unsigned numIElts = IVT->getNumElements();
Nate Begeman5da51d32010-07-07 22:26:56 +0000885
886 if (IType->isExtVectorType())
887 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
888 else
889 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
890 IVT->getAltiVecSpecific());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000891 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000892 StructuredList, StructuredIndex);
893 numEltsInit += numIElts;
894 }
895 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000896 }
Mike Stump11289f42009-09-09 15:08:12 +0000897
John Thompson7bc797b2010-04-20 23:21:17 +0000898 // OpenCL requires all elements to be initialized.
Nate Begeman5ec4b312009-08-10 23:49:36 +0000899 if (numEltsInit != maxElements)
Chris Lattnerb596ac72010-04-20 05:19:10 +0000900 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman5ec4b312009-08-10 23:49:36 +0000901 SemaRef.Diag(IList->getSourceRange().getBegin(),
902 diag::err_vector_incorrect_num_initializers)
903 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000904 }
905}
906
Anders Carlsson6cabf312010-01-23 23:23:01 +0000907void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000908 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000909 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000910 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000911 unsigned &Index,
912 InitListExpr *StructuredList,
913 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000914 // Check for the special-case of initializing an array with a string.
915 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000916 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
917 SemaRef.Context)) {
918 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000919 // We place the string literal directly into the resulting
920 // initializer list. This is the only place where the structure
921 // of the structured initializer list doesn't match exactly,
922 // because doing so would involve allocating one character
923 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000924 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000925 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000926 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000927 return;
928 }
929 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000930 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000931 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000932 // Check for VLAs; in standard C it would be possible to check this
933 // earlier, but I don't know where clang accepts VLAs (gcc accepts
934 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000935 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000936 diag::err_variable_object_no_init)
937 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000938 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000939 ++Index;
940 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000941 return;
942 }
943
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000944 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000945 llvm::APSInt maxElements(elementIndex.getBitWidth(),
946 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000947 bool maxElementsKnown = false;
948 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000949 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000950 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000951 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000952 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000953 maxElementsKnown = true;
954 }
955
Chris Lattnerb0912a52009-02-24 22:50:46 +0000956 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000957 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000958 while (Index < IList->getNumInits()) {
959 Expr *Init = IList->getInit(Index);
960 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000961 // If we're not the subobject that matches up with the '{' for
962 // the designator, we shouldn't be handling the
963 // designator. Return immediately.
964 if (!SubobjectIsDesignatorContext)
965 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000966
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000967 // Handle this designated initializer. elementIndex will be
968 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000969 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000970 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000971 StructuredList, StructuredIndex, true,
972 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000973 hadError = true;
974 continue;
975 }
976
Douglas Gregor033d1252009-01-23 16:54:12 +0000977 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
978 maxElements.extend(elementIndex.getBitWidth());
979 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
980 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000981 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000982
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000983 // If the array is of incomplete type, keep track of the number of
984 // elements in the initializer.
985 if (!maxElementsKnown && elementIndex > maxElements)
986 maxElements = elementIndex;
987
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000988 continue;
989 }
990
991 // If we know the maximum number of elements, and we've already
992 // hit it, stop consuming elements in the initializer list.
993 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000994 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000995
Anders Carlsson6cabf312010-01-23 23:23:01 +0000996 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000997 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000998 Entity);
999 // Check this element.
1000 CheckSubElementType(ElementEntity, IList, elementType, Index,
1001 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001002 ++elementIndex;
1003
1004 // If the array is of incomplete type, keep track of the number of
1005 // elements in the initializer.
1006 if (!maxElementsKnown && elementIndex > maxElements)
1007 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001008 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001009 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001010 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001011 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001012 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001013 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001014 // Sizing an array implicitly to zero is not allowed by ISO C,
1015 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001016 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001017 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001018 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001019
Mike Stump11289f42009-09-09 15:08:12 +00001020 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001021 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001022 }
1023}
1024
Anders Carlsson6cabf312010-01-23 23:23:01 +00001025void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001026 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001027 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001028 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001029 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001030 unsigned &Index,
1031 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001032 unsigned &StructuredIndex,
1033 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001034 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001035
Eli Friedman23a9e312008-05-19 19:16:24 +00001036 // If the record is invalid, some of it's members are invalid. To avoid
1037 // confusion, we forgo checking the intializer for the entire record.
1038 if (structDecl->isInvalidDecl()) {
1039 hadError = true;
1040 return;
Mike Stump11289f42009-09-09 15:08:12 +00001041 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001042
1043 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1044 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001045 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001046 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001047 Field != FieldEnd; ++Field) {
1048 if (Field->getDeclName()) {
1049 StructuredList->setInitializedFieldInUnion(*Field);
1050 break;
1051 }
1052 }
1053 return;
1054 }
1055
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001056 // If structDecl is a forward declaration, this loop won't do
1057 // anything except look at designated initializers; That's okay,
1058 // because an error should get printed out elsewhere. It might be
1059 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001061 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001062 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001063 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001064 while (Index < IList->getNumInits()) {
1065 Expr *Init = IList->getInit(Index);
1066
1067 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001068 // If we're not the subobject that matches up with the '{' for
1069 // the designator, we shouldn't be handling the
1070 // designator. Return immediately.
1071 if (!SubobjectIsDesignatorContext)
1072 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001073
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001074 // Handle this designated initializer. Field will be updated to
1075 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001076 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001077 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001078 StructuredList, StructuredIndex,
1079 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001080 hadError = true;
1081
Douglas Gregora9add4e2009-02-12 19:00:39 +00001082 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001083
1084 // Disable check for missing fields when designators are used.
1085 // This matches gcc behaviour.
1086 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001087 continue;
1088 }
1089
1090 if (Field == FieldEnd) {
1091 // We've run out of fields. We're done.
1092 break;
1093 }
1094
Douglas Gregora9add4e2009-02-12 19:00:39 +00001095 // We've already initialized a member of a union. We're done.
1096 if (InitializedSomething && DeclType->isUnionType())
1097 break;
1098
Douglas Gregor91f84212008-12-11 16:49:14 +00001099 // If we've hit the flexible array member at the end, we're done.
1100 if (Field->getType()->isIncompleteArrayType())
1101 break;
1102
Douglas Gregor51695702009-01-29 16:53:55 +00001103 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001104 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001105 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001106 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001107 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001108
Anders Carlsson6cabf312010-01-23 23:23:01 +00001109 InitializedEntity MemberEntity =
1110 InitializedEntity::InitializeMember(*Field, &Entity);
1111 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1112 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001113 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001114
1115 if (DeclType->isUnionType()) {
1116 // Initialize the first field within the union.
1117 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001118 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001119
1120 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001121 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001122
John McCalle40b58e2010-03-11 19:32:38 +00001123 // Emit warnings for missing struct field initializers.
Douglas Gregor8fba4f22010-06-18 21:43:10 +00001124 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001125 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1126 // It is possible we have one or more unnamed bitfields remaining.
1127 // Find first (if any) named field and emit warning.
1128 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1129 it != end; ++it) {
1130 if (!it->isUnnamedBitfield()) {
1131 SemaRef.Diag(IList->getSourceRange().getEnd(),
1132 diag::warn_missing_field_initializers) << it->getName();
1133 break;
1134 }
1135 }
1136 }
1137
Mike Stump11289f42009-09-09 15:08:12 +00001138 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001139 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001140 return;
1141
1142 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001143 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001144 (!isa<InitListExpr>(IList->getInit(Index)) ||
1145 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001146 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001147 diag::err_flexible_array_init_nonempty)
1148 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001149 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001150 << *Field;
1151 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001152 ++Index;
1153 return;
1154 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001155 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001156 diag::ext_flexible_array_init)
1157 << IList->getInit(Index)->getSourceRange().getBegin();
1158 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1159 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001160 }
1161
Anders Carlsson6cabf312010-01-23 23:23:01 +00001162 InitializedEntity MemberEntity =
1163 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001164
Anders Carlsson6cabf312010-01-23 23:23:01 +00001165 if (isa<InitListExpr>(IList->getInit(Index)))
1166 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1167 StructuredList, StructuredIndex);
1168 else
1169 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001170 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001171}
Steve Narofff8ecff22008-05-01 22:18:59 +00001172
Douglas Gregord5846a12009-04-15 06:41:24 +00001173/// \brief Expand a field designator that refers to a member of an
1174/// anonymous struct or union into a series of field designators that
1175/// refers to the field within the appropriate subobject.
1176///
1177/// Field/FieldIndex will be updated to point to the (new)
1178/// currently-designated field.
1179static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001180 DesignatedInitExpr *DIE,
1181 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001182 FieldDecl *Field,
1183 RecordDecl::field_iterator &FieldIter,
1184 unsigned &FieldIndex) {
1185 typedef DesignatedInitExpr::Designator Designator;
1186
1187 // Build the path from the current object to the member of the
1188 // anonymous struct/union (backwards).
1189 llvm::SmallVector<FieldDecl *, 4> Path;
1190 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001191
Douglas Gregord5846a12009-04-15 06:41:24 +00001192 // Build the replacement designators.
1193 llvm::SmallVector<Designator, 4> Replacements;
1194 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1195 FI = Path.rbegin(), FIEnd = Path.rend();
1196 FI != FIEnd; ++FI) {
1197 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001198 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001199 DIE->getDesignator(DesigIdx)->getDotLoc(),
1200 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1201 else
1202 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1203 SourceLocation()));
1204 Replacements.back().setField(*FI);
1205 }
1206
1207 // Expand the current designator into the set of replacement
1208 // designators, so we have a full subobject path down to where the
1209 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001210 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001211 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001212
Douglas Gregord5846a12009-04-15 06:41:24 +00001213 // Update FieldIter/FieldIndex;
1214 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001215 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001216 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001217 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001218 FieldIter != FEnd; ++FieldIter) {
1219 if (FieldIter->isUnnamedBitfield())
1220 continue;
1221
1222 if (*FieldIter == Path.back())
1223 return;
1224
1225 ++FieldIndex;
1226 }
1227
1228 assert(false && "Unable to find anonymous struct/union field");
1229}
1230
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001231/// @brief Check the well-formedness of a C99 designated initializer.
1232///
1233/// Determines whether the designated initializer @p DIE, which
1234/// resides at the given @p Index within the initializer list @p
1235/// IList, is well-formed for a current object of type @p DeclType
1236/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001237/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001238/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001239///
1240/// @param IList The initializer list in which this designated
1241/// initializer occurs.
1242///
Douglas Gregora5324162009-04-15 04:56:10 +00001243/// @param DIE The designated initializer expression.
1244///
1245/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001246///
1247/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1248/// into which the designation in @p DIE should refer.
1249///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001250/// @param NextField If non-NULL and the first designator in @p DIE is
1251/// a field, this will be set to the field declaration corresponding
1252/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001253///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001254/// @param NextElementIndex If non-NULL and the first designator in @p
1255/// DIE is an array designator or GNU array-range designator, this
1256/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001257///
1258/// @param Index Index into @p IList where the designated initializer
1259/// @p DIE occurs.
1260///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001261/// @param StructuredList The initializer list expression that
1262/// describes all of the subobject initializers in the order they'll
1263/// actually be initialized.
1264///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001265/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001266bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001267InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001268 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001269 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001270 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001271 QualType &CurrentObjectType,
1272 RecordDecl::field_iterator *NextField,
1273 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001274 unsigned &Index,
1275 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001276 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001277 bool FinishSubobjectInit,
1278 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001279 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001280 // Check the actual initialization for the designated object type.
1281 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001282
1283 // Temporarily remove the designator expression from the
1284 // initializer list that the child calls see, so that we don't try
1285 // to re-process the designator.
1286 unsigned OldIndex = Index;
1287 IList->setInit(OldIndex, DIE->getInit());
1288
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001289 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001290 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001291
1292 // Restore the designated initializer expression in the syntactic
1293 // form of the initializer list.
1294 if (IList->getInit(OldIndex) != DIE->getInit())
1295 DIE->setInit(IList->getInit(OldIndex));
1296 IList->setInit(OldIndex, DIE);
1297
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001298 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001299 }
1300
Douglas Gregora5324162009-04-15 04:56:10 +00001301 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001302 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001303 "Need a non-designated initializer list to start from");
1304
Douglas Gregora5324162009-04-15 04:56:10 +00001305 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001306 // Determine the structural initializer list that corresponds to the
1307 // current subobject.
1308 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001309 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001310 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001311 SourceRange(D->getStartLocation(),
1312 DIE->getSourceRange().getEnd()));
1313 assert(StructuredList && "Expected a structured initializer list");
1314
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001315 if (D->isFieldDesignator()) {
1316 // C99 6.7.8p7:
1317 //
1318 // If a designator has the form
1319 //
1320 // . identifier
1321 //
1322 // then the current object (defined below) shall have
1323 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001324 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001325 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001326 if (!RT) {
1327 SourceLocation Loc = D->getDotLoc();
1328 if (Loc.isInvalid())
1329 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001330 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1331 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001332 ++Index;
1333 return true;
1334 }
1335
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001336 // Note: we perform a linear search of the fields here, despite
1337 // the fact that we have a faster lookup method, because we always
1338 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001339 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001340 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001341 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001342 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001343 Field = RT->getDecl()->field_begin(),
1344 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001345 for (; Field != FieldEnd; ++Field) {
1346 if (Field->isUnnamedBitfield())
1347 continue;
1348
Douglas Gregord5846a12009-04-15 06:41:24 +00001349 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001350 break;
1351
1352 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001353 }
1354
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001355 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001356 // There was no normal field in the struct with the designated
1357 // name. Perform another lookup for this name, which may find
1358 // something that we can't designate (e.g., a member function),
1359 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001360 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001361 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001362 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001363 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001364 // Name lookup didn't find anything. Determine whether this
1365 // was a typo for another field name.
1366 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1367 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001368 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1369 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001370 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1371 ReplacementField->getDeclContext()->getLookupContext()
1372 ->Equals(RT->getDecl())) {
1373 SemaRef.Diag(D->getFieldLoc(),
1374 diag::err_field_designator_unknown_suggest)
1375 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001376 << FixItHint::CreateReplacement(D->getFieldLoc(),
1377 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001378 SemaRef.Diag(ReplacementField->getLocation(),
1379 diag::note_previous_decl)
1380 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001381 } else {
1382 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1383 << FieldName << CurrentObjectType;
1384 ++Index;
1385 return true;
1386 }
1387 } else if (!KnownField) {
1388 // Determine whether we found a field at all.
1389 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1390 }
1391
1392 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001393 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001394 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001395 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001396 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001397 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001398 ++Index;
1399 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001400 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001401
1402 if (!KnownField &&
1403 cast<RecordDecl>((ReplacementField)->getDeclContext())
1404 ->isAnonymousStructOrUnion()) {
1405 // Handle an field designator that refers to a member of an
1406 // anonymous struct or union.
1407 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1408 ReplacementField,
1409 Field, FieldIndex);
1410 D = DIE->getDesignator(DesigIdx);
1411 } else if (!KnownField) {
1412 // The replacement field comes from typo correction; find it
1413 // in the list of fields.
1414 FieldIndex = 0;
1415 Field = RT->getDecl()->field_begin();
1416 for (; Field != FieldEnd; ++Field) {
1417 if (Field->isUnnamedBitfield())
1418 continue;
1419
1420 if (ReplacementField == *Field ||
1421 Field->getIdentifier() == ReplacementField->getIdentifier())
1422 break;
1423
1424 ++FieldIndex;
1425 }
1426 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001427 } else if (!KnownField &&
1428 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001429 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001430 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1431 Field, FieldIndex);
1432 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001433 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001434
1435 // All of the fields of a union are located at the same place in
1436 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001437 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001438 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001439 StructuredList->setInitializedFieldInUnion(*Field);
1440 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001441
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001442 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001443 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001444
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001445 // Make sure that our non-designated initializer list has space
1446 // for a subobject corresponding to this field.
1447 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001448 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001449
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001450 // This designator names a flexible array member.
1451 if (Field->getType()->isIncompleteArrayType()) {
1452 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001453 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001454 // We can't designate an object within the flexible array
1455 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001456 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001457 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001458 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001459 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001460 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001461 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001462 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001463 << *Field;
1464 Invalid = true;
1465 }
1466
1467 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1468 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001469 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001470 diag::err_flexible_array_init_needs_braces)
1471 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001472 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001473 << *Field;
1474 Invalid = true;
1475 }
1476
1477 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001478 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001479 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001480 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001481 diag::err_flexible_array_init_nonempty)
1482 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001483 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001484 << *Field;
1485 Invalid = true;
1486 }
1487
1488 if (Invalid) {
1489 ++Index;
1490 return true;
1491 }
1492
1493 // Initialize the array.
1494 bool prevHadError = hadError;
1495 unsigned newStructuredIndex = FieldIndex;
1496 unsigned OldIndex = Index;
1497 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001498
1499 InitializedEntity MemberEntity =
1500 InitializedEntity::InitializeMember(*Field, &Entity);
1501 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001502 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001503
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001504 IList->setInit(OldIndex, DIE);
1505 if (hadError && !prevHadError) {
1506 ++Field;
1507 ++FieldIndex;
1508 if (NextField)
1509 *NextField = Field;
1510 StructuredIndex = FieldIndex;
1511 return true;
1512 }
1513 } else {
1514 // Recurse to check later designated subobjects.
1515 QualType FieldType = (*Field)->getType();
1516 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001517
1518 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001519 InitializedEntity::InitializeMember(*Field, &Entity);
1520 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001521 FieldType, 0, 0, Index,
1522 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001523 true, false))
1524 return true;
1525 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001526
1527 // Find the position of the next field to be initialized in this
1528 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001529 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001530 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001531
1532 // If this the first designator, our caller will continue checking
1533 // the rest of this struct/class/union subobject.
1534 if (IsFirstDesignator) {
1535 if (NextField)
1536 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001537 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001538 return false;
1539 }
1540
Douglas Gregor17bd0942009-01-28 23:36:17 +00001541 if (!FinishSubobjectInit)
1542 return false;
1543
Douglas Gregord5846a12009-04-15 06:41:24 +00001544 // We've already initialized something in the union; we're done.
1545 if (RT->getDecl()->isUnion())
1546 return hadError;
1547
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001548 // Check the remaining fields within this class/struct/union subobject.
1549 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001550
Anders Carlsson6cabf312010-01-23 23:23:01 +00001551 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001552 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001553 return hadError && !prevHadError;
1554 }
1555
1556 // C99 6.7.8p6:
1557 //
1558 // If a designator has the form
1559 //
1560 // [ constant-expression ]
1561 //
1562 // then the current object (defined below) shall have array
1563 // type and the expression shall be an integer constant
1564 // expression. If the array is of unknown size, any
1565 // nonnegative value is valid.
1566 //
1567 // Additionally, cope with the GNU extension that permits
1568 // designators of the form
1569 //
1570 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001571 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001572 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001573 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001574 << CurrentObjectType;
1575 ++Index;
1576 return true;
1577 }
1578
1579 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001580 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1581 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001582 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001583 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001584 DesignatedEndIndex = DesignatedStartIndex;
1585 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001586 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001587
Mike Stump11289f42009-09-09 15:08:12 +00001588
1589 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001590 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001591 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001592 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001593 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001594
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001595 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001596 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001597 }
1598
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001599 if (isa<ConstantArrayType>(AT)) {
1600 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001601 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1602 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1603 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1604 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1605 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001606 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001607 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001608 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001609 << IndexExpr->getSourceRange();
1610 ++Index;
1611 return true;
1612 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001613 } else {
1614 // Make sure the bit-widths and signedness match.
1615 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1616 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001617 else if (DesignatedStartIndex.getBitWidth() <
1618 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001619 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1620 DesignatedStartIndex.setIsUnsigned(true);
1621 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 }
Mike Stump11289f42009-09-09 15:08:12 +00001623
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001624 // Make sure that our non-designated initializer list has space
1625 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001626 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001627 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001628 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001629
Douglas Gregor17bd0942009-01-28 23:36:17 +00001630 // Repeatedly perform subobject initializations in the range
1631 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001632
Douglas Gregor17bd0942009-01-28 23:36:17 +00001633 // Move to the next designator
1634 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1635 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001636
1637 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001638 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001639
Douglas Gregor17bd0942009-01-28 23:36:17 +00001640 while (DesignatedStartIndex <= DesignatedEndIndex) {
1641 // Recurse to check later designated subobjects.
1642 QualType ElementType = AT->getElementType();
1643 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001644
1645 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001646 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001647 ElementType, 0, 0, Index,
1648 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001649 (DesignatedStartIndex == DesignatedEndIndex),
1650 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001651 return true;
1652
1653 // Move to the next index in the array that we'll be initializing.
1654 ++DesignatedStartIndex;
1655 ElementIndex = DesignatedStartIndex.getZExtValue();
1656 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001657
1658 // If this the first designator, our caller will continue checking
1659 // the rest of this array subobject.
1660 if (IsFirstDesignator) {
1661 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001662 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001664 return false;
1665 }
Mike Stump11289f42009-09-09 15:08:12 +00001666
Douglas Gregor17bd0942009-01-28 23:36:17 +00001667 if (!FinishSubobjectInit)
1668 return false;
1669
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001670 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001671 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001672 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001673 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001674 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001675 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001676}
1677
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001678// Get the structured initializer list for a subobject of type
1679// @p CurrentObjectType.
1680InitListExpr *
1681InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1682 QualType CurrentObjectType,
1683 InitListExpr *StructuredList,
1684 unsigned StructuredIndex,
1685 SourceRange InitRange) {
1686 Expr *ExistingInit = 0;
1687 if (!StructuredList)
1688 ExistingInit = SyntacticToSemantic[IList];
1689 else if (StructuredIndex < StructuredList->getNumInits())
1690 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001692 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1693 return Result;
1694
1695 if (ExistingInit) {
1696 // We are creating an initializer list that initializes the
1697 // subobjects of the current object, but there was already an
1698 // initialization that completely initialized the current
1699 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001700 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001701 // struct X { int a, b; };
1702 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001703 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001704 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1705 // designated initializer re-initializes the whole
1706 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001707 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001708 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001709 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001710 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001712 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001713 << ExistingInit->getSourceRange();
1714 }
1715
Mike Stump11289f42009-09-09 15:08:12 +00001716 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001717 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1718 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001719 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001720
Douglas Gregora8a089b2010-07-13 18:40:04 +00001721 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001722
Douglas Gregor6d00c992009-03-20 23:58:33 +00001723 // Pre-allocate storage for the structured initializer list.
1724 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001725 unsigned NumInits = 0;
1726 if (!StructuredList)
1727 NumInits = IList->getNumInits();
1728 else if (Index < IList->getNumInits()) {
1729 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1730 NumInits = SubList->getNumInits();
1731 }
1732
Mike Stump11289f42009-09-09 15:08:12 +00001733 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001734 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1735 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1736 NumElements = CAType->getSize().getZExtValue();
1737 // Simple heuristic so that we don't allocate a very large
1738 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001739 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001740 NumElements = 0;
1741 }
John McCall9dd450b2009-09-21 23:43:11 +00001742 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001743 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001744 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001745 RecordDecl *RDecl = RType->getDecl();
1746 if (RDecl->isUnion())
1747 NumElements = 1;
1748 else
Mike Stump11289f42009-09-09 15:08:12 +00001749 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001750 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001751 }
1752
Douglas Gregor221c9a52009-03-21 18:13:52 +00001753 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001754 NumElements = IList->getNumInits();
1755
Ted Kremenekac034612010-04-13 23:39:13 +00001756 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001757
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001758 // Link this new initializer list into the structured initializer
1759 // lists.
1760 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001761 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001762 else {
1763 Result->setSyntacticForm(IList);
1764 SyntacticToSemantic[IList] = Result;
1765 }
1766
1767 return Result;
1768}
1769
1770/// Update the initializer at index @p StructuredIndex within the
1771/// structured initializer list to the value @p expr.
1772void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1773 unsigned &StructuredIndex,
1774 Expr *expr) {
1775 // No structured initializer list to update
1776 if (!StructuredList)
1777 return;
1778
Ted Kremenekac034612010-04-13 23:39:13 +00001779 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1780 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001781 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001782 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001783 diag::warn_initializer_overrides)
1784 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001785 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001786 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001787 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001788 << PrevInit->getSourceRange();
1789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001791 ++StructuredIndex;
1792}
1793
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001794/// Check that the given Index expression is a valid array designator
1795/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001796/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001797/// and produces a reasonable diagnostic if there is a
1798/// failure. Returns true if there was an error, false otherwise. If
1799/// everything went okay, Value will receive the value of the constant
1800/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001801static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001802CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001803 SourceLocation Loc = Index->getSourceRange().getBegin();
1804
1805 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001806 if (S.VerifyIntegerConstantExpression(Index, &Value))
1807 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001808
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001809 if (Value.isSigned() && Value.isNegative())
1810 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001811 << Value.toString(10) << Index->getSourceRange();
1812
Douglas Gregor51650d32009-01-23 21:04:18 +00001813 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001814 return false;
1815}
1816
John McCalldadc5752010-08-24 06:29:42 +00001817ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001818 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001819 bool GNUSyntax,
John McCalldadc5752010-08-24 06:29:42 +00001820 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001821 typedef DesignatedInitExpr::Designator ASTDesignator;
1822
1823 bool Invalid = false;
1824 llvm::SmallVector<ASTDesignator, 32> Designators;
1825 llvm::SmallVector<Expr *, 32> InitExpressions;
1826
1827 // Build designators and check array designator expressions.
1828 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1829 const Designator &D = Desig.getDesignator(Idx);
1830 switch (D.getKind()) {
1831 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001832 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001833 D.getFieldLoc()));
1834 break;
1835
1836 case Designator::ArrayDesignator: {
1837 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1838 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001839 if (!Index->isTypeDependent() &&
1840 !Index->isValueDependent() &&
1841 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001842 Invalid = true;
1843 else {
1844 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001845 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001846 D.getRBracketLoc()));
1847 InitExpressions.push_back(Index);
1848 }
1849 break;
1850 }
1851
1852 case Designator::ArrayRangeDesignator: {
1853 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1854 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1855 llvm::APSInt StartValue;
1856 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001857 bool StartDependent = StartIndex->isTypeDependent() ||
1858 StartIndex->isValueDependent();
1859 bool EndDependent = EndIndex->isTypeDependent() ||
1860 EndIndex->isValueDependent();
1861 if ((!StartDependent &&
1862 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1863 (!EndDependent &&
1864 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001865 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001866 else {
1867 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001868 if (StartDependent || EndDependent) {
1869 // Nothing to compute.
1870 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001871 EndValue.extend(StartValue.getBitWidth());
1872 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1873 StartValue.extend(EndValue.getBitWidth());
1874
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001875 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001876 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001877 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001878 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1879 Invalid = true;
1880 } else {
1881 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001882 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001883 D.getEllipsisLoc(),
1884 D.getRBracketLoc()));
1885 InitExpressions.push_back(StartIndex);
1886 InitExpressions.push_back(EndIndex);
1887 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001888 }
1889 break;
1890 }
1891 }
1892 }
1893
1894 if (Invalid || Init.isInvalid())
1895 return ExprError();
1896
1897 // Clear out the expressions within the designation.
1898 Desig.ClearExprs(*this);
1899
1900 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001901 = DesignatedInitExpr::Create(Context,
1902 Designators.data(), Designators.size(),
1903 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001904 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905 return Owned(DIE);
1906}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001907
Douglas Gregor723796a2009-12-16 06:35:08 +00001908bool Sema::CheckInitList(const InitializedEntity &Entity,
1909 InitListExpr *&InitList, QualType &DeclType) {
1910 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001911 if (!CheckInitList.HadError())
1912 InitList = CheckInitList.getFullyStructuredList();
1913
1914 return CheckInitList.HadError();
1915}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001916
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001917//===----------------------------------------------------------------------===//
1918// Initialization entity
1919//===----------------------------------------------------------------------===//
1920
Douglas Gregor723796a2009-12-16 06:35:08 +00001921InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1922 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001923 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001924{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001925 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1926 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001927 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001928 } else {
1929 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001930 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001931 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001932}
1933
1934InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001935 CXXBaseSpecifier *Base,
1936 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001937{
1938 InitializedEntity Result;
1939 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001940 Result.Base = reinterpret_cast<uintptr_t>(Base);
1941 if (IsInheritedVirtualBase)
1942 Result.Base |= 0x01;
1943
Douglas Gregor1b303932009-12-22 15:35:07 +00001944 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001945 return Result;
1946}
1947
Douglas Gregor85dabae2009-12-16 01:38:02 +00001948DeclarationName InitializedEntity::getName() const {
1949 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001950 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001951 if (!VariableOrMember)
1952 return DeclarationName();
1953 // Fall through
1954
1955 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001956 case EK_Member:
1957 return VariableOrMember->getDeclName();
1958
1959 case EK_Result:
1960 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001961 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001962 case EK_Temporary:
1963 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001964 case EK_ArrayElement:
1965 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001966 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001967 return DeclarationName();
1968 }
1969
1970 // Silence GCC warning
1971 return DeclarationName();
1972}
1973
Douglas Gregora4b592a2009-12-19 03:01:41 +00001974DeclaratorDecl *InitializedEntity::getDecl() const {
1975 switch (getKind()) {
1976 case EK_Variable:
1977 case EK_Parameter:
1978 case EK_Member:
1979 return VariableOrMember;
1980
1981 case EK_Result:
1982 case EK_Exception:
1983 case EK_New:
1984 case EK_Temporary:
1985 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001986 case EK_ArrayElement:
1987 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001988 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001989 return 0;
1990 }
1991
1992 // Silence GCC warning
1993 return 0;
1994}
1995
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001996bool InitializedEntity::allowsNRVO() const {
1997 switch (getKind()) {
1998 case EK_Result:
1999 case EK_Exception:
2000 return LocAndNRVO.NRVO;
2001
2002 case EK_Variable:
2003 case EK_Parameter:
2004 case EK_Member:
2005 case EK_New:
2006 case EK_Temporary:
2007 case EK_Base:
2008 case EK_ArrayElement:
2009 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002010 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002011 break;
2012 }
2013
2014 return false;
2015}
2016
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002017//===----------------------------------------------------------------------===//
2018// Initialization sequence
2019//===----------------------------------------------------------------------===//
2020
2021void InitializationSequence::Step::Destroy() {
2022 switch (Kind) {
2023 case SK_ResolveAddressOfOverloadedFunction:
2024 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002025 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002026 case SK_CastDerivedToBaseLValue:
2027 case SK_BindReference:
2028 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002029 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002030 case SK_UserConversion:
2031 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002032 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002033 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002034 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002035 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002036 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002037 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002038 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002039 case SK_ObjCObjectConversion:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002040 break;
2041
2042 case SK_ConversionSequence:
2043 delete ICS;
2044 }
2045}
2046
Douglas Gregor838fcc32010-03-26 20:14:36 +00002047bool InitializationSequence::isDirectReferenceBinding() const {
2048 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2049}
2050
2051bool InitializationSequence::isAmbiguous() const {
2052 if (getKind() != FailedSequence)
2053 return false;
2054
2055 switch (getFailureKind()) {
2056 case FK_TooManyInitsForReference:
2057 case FK_ArrayNeedsInitList:
2058 case FK_ArrayNeedsInitListOrStringLiteral:
2059 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2060 case FK_NonConstLValueReferenceBindingToTemporary:
2061 case FK_NonConstLValueReferenceBindingToUnrelated:
2062 case FK_RValueReferenceBindingToLValue:
2063 case FK_ReferenceInitDropsQualifiers:
2064 case FK_ReferenceInitFailed:
2065 case FK_ConversionFailed:
2066 case FK_TooManyInitsForScalar:
2067 case FK_ReferenceBindingToInitList:
2068 case FK_InitListBadDestinationType:
2069 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002070 case FK_Incomplete:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002071 return false;
2072
2073 case FK_ReferenceInitOverloadFailed:
2074 case FK_UserConversionOverloadFailed:
2075 case FK_ConstructorOverloadFailed:
2076 return FailedOverloadResult == OR_Ambiguous;
2077 }
2078
2079 return false;
2080}
2081
Douglas Gregorb33eed02010-04-16 22:09:46 +00002082bool InitializationSequence::isConstructorInitialization() const {
2083 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2084}
2085
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002086void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002087 FunctionDecl *Function,
2088 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002089 Step S;
2090 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2091 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002092 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002093 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002094 Steps.push_back(S);
2095}
2096
2097void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002098 ImplicitCastExpr::ResultCategory Category) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002099 Step S;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002100 switch (Category) {
2101 case ImplicitCastExpr::RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2102 case ImplicitCastExpr::XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2103 case ImplicitCastExpr::LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2104 default: llvm_unreachable("No such category");
2105 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002106 S.Type = BaseType;
2107 Steps.push_back(S);
2108}
2109
2110void InitializationSequence::AddReferenceBindingStep(QualType T,
2111 bool BindingTemporary) {
2112 Step S;
2113 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2114 S.Type = T;
2115 Steps.push_back(S);
2116}
2117
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002118void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2119 Step S;
2120 S.Kind = SK_ExtraneousCopyToTemporary;
2121 S.Type = T;
2122 Steps.push_back(S);
2123}
2124
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002125void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002126 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002127 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002128 Step S;
2129 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002130 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002131 S.Function.Function = Function;
2132 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002133 Steps.push_back(S);
2134}
2135
2136void InitializationSequence::AddQualificationConversionStep(QualType Ty,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002137 ImplicitCastExpr::ResultCategory Category) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002138 Step S;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002139 switch (Category) {
2140 case ImplicitCastExpr::RValue:
2141 S.Kind = SK_QualificationConversionRValue;
2142 break;
2143 case ImplicitCastExpr::XValue:
2144 S.Kind = SK_QualificationConversionXValue;
2145 break;
2146 case ImplicitCastExpr::LValue:
2147 S.Kind = SK_QualificationConversionLValue;
2148 break;
2149 default: llvm_unreachable("No such category");
2150 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002151 S.Type = Ty;
2152 Steps.push_back(S);
2153}
2154
2155void InitializationSequence::AddConversionSequenceStep(
2156 const ImplicitConversionSequence &ICS,
2157 QualType T) {
2158 Step S;
2159 S.Kind = SK_ConversionSequence;
2160 S.Type = T;
2161 S.ICS = new ImplicitConversionSequence(ICS);
2162 Steps.push_back(S);
2163}
2164
Douglas Gregor51e77d52009-12-10 17:56:55 +00002165void InitializationSequence::AddListInitializationStep(QualType T) {
2166 Step S;
2167 S.Kind = SK_ListInitialization;
2168 S.Type = T;
2169 Steps.push_back(S);
2170}
2171
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002172void
2173InitializationSequence::AddConstructorInitializationStep(
2174 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002175 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002176 QualType T) {
2177 Step S;
2178 S.Kind = SK_ConstructorInitialization;
2179 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002180 S.Function.Function = Constructor;
2181 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002182 Steps.push_back(S);
2183}
2184
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002185void InitializationSequence::AddZeroInitializationStep(QualType T) {
2186 Step S;
2187 S.Kind = SK_ZeroInitialization;
2188 S.Type = T;
2189 Steps.push_back(S);
2190}
2191
Douglas Gregore1314a62009-12-18 05:02:21 +00002192void InitializationSequence::AddCAssignmentStep(QualType T) {
2193 Step S;
2194 S.Kind = SK_CAssignment;
2195 S.Type = T;
2196 Steps.push_back(S);
2197}
2198
Eli Friedman78275202009-12-19 08:11:05 +00002199void InitializationSequence::AddStringInitStep(QualType T) {
2200 Step S;
2201 S.Kind = SK_StringInit;
2202 S.Type = T;
2203 Steps.push_back(S);
2204}
2205
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002206void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2207 Step S;
2208 S.Kind = SK_ObjCObjectConversion;
2209 S.Type = T;
2210 Steps.push_back(S);
2211}
2212
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002213void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2214 OverloadingResult Result) {
2215 SequenceKind = FailedSequence;
2216 this->Failure = Failure;
2217 this->FailedOverloadResult = Result;
2218}
2219
2220//===----------------------------------------------------------------------===//
2221// Attempt initialization
2222//===----------------------------------------------------------------------===//
2223
2224/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002225static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002226 const InitializedEntity &Entity,
2227 const InitializationKind &Kind,
2228 InitListExpr *InitList,
2229 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002230 // FIXME: We only perform rudimentary checking of list
2231 // initializations at this point, then assume that any list
2232 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002233 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002234 // do all of the necessary checking. C++0x initializer lists will
2235 // force us to perform more checking here.
2236 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2237
Douglas Gregor1b303932009-12-22 15:35:07 +00002238 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002239
2240 // C++ [dcl.init]p13:
2241 // If T is a scalar type, then a declaration of the form
2242 //
2243 // T x = { a };
2244 //
2245 // is equivalent to
2246 //
2247 // T x = a;
2248 if (DestType->isScalarType()) {
2249 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2250 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2251 return;
2252 }
2253
2254 // Assume scalar initialization from a single value works.
2255 } else if (DestType->isAggregateType()) {
2256 // Assume aggregate initialization works.
2257 } else if (DestType->isVectorType()) {
2258 // Assume vector initialization works.
2259 } else if (DestType->isReferenceType()) {
2260 // FIXME: C++0x defines behavior for this.
2261 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2262 return;
2263 } else if (DestType->isRecordType()) {
2264 // FIXME: C++0x defines behavior for this
2265 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2266 }
2267
2268 // Add a general "list initialization" step.
2269 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002270}
2271
2272/// \brief Try a reference initialization that involves calling a conversion
2273/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002274static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2275 const InitializedEntity &Entity,
2276 const InitializationKind &Kind,
2277 Expr *Initializer,
2278 bool AllowRValues,
2279 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002280 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002281 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2282 QualType T1 = cv1T1.getUnqualifiedType();
2283 QualType cv2T2 = Initializer->getType();
2284 QualType T2 = cv2T2.getUnqualifiedType();
2285
2286 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002287 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002288 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002289 T1, T2, DerivedToBase,
2290 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002291 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002292 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002293 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002294
2295 // Build the candidate set directly in the initialization sequence
2296 // structure, so that it will persist if we fail.
2297 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2298 CandidateSet.clear();
2299
2300 // Determine whether we are allowed to call explicit constructors or
2301 // explicit conversion operators.
2302 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2303
2304 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002305 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2306 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002307 // The type we're converting to is a class type. Enumerate its constructors
2308 // to see if there is a suitable conversion.
2309 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002310
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002311 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002312 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002313 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002314 NamedDecl *D = *Con;
2315 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2316
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 // Find the constructor (which may be a template).
2318 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002319 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002320 if (ConstructorTmpl)
2321 Constructor = cast<CXXConstructorDecl>(
2322 ConstructorTmpl->getTemplatedDecl());
2323 else
John McCalla0296f72010-03-19 07:35:19 +00002324 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002325
2326 if (!Constructor->isInvalidDecl() &&
2327 Constructor->isConvertingConstructor(AllowExplicit)) {
2328 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002329 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002330 /*ExplicitArgs*/ 0,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002331 &Initializer, 1, CandidateSet);
2332 else
John McCalla0296f72010-03-19 07:35:19 +00002333 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002334 &Initializer, 1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002335 }
2336 }
2337 }
John McCall3696dcb2010-08-17 07:23:57 +00002338 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2339 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002340
Douglas Gregor496e8b342010-05-07 19:42:26 +00002341 const RecordType *T2RecordType = 0;
2342 if ((T2RecordType = T2->getAs<RecordType>()) &&
2343 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002344 // The type we're converting from is a class type, enumerate its conversion
2345 // functions.
2346 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2347
2348 // Determine the type we are converting to. If we are allowed to
2349 // convert to an rvalue, take the type that the destination type
2350 // refers to.
2351 QualType ToType = AllowRValues? cv1T1 : DestType;
2352
John McCallad371252010-01-20 00:46:10 +00002353 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002354 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002355 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2356 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002357 NamedDecl *D = *I;
2358 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2359 if (isa<UsingShadowDecl>(D))
2360 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2361
2362 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2363 CXXConversionDecl *Conv;
2364 if (ConvTemplate)
2365 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2366 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002367 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002368
2369 // If the conversion function doesn't return a reference type,
2370 // it can't be considered for this conversion unless we're allowed to
2371 // consider rvalues.
2372 // FIXME: Do we need to make sure that we only consider conversion
2373 // candidates with reference-compatible results? That might be needed to
2374 // break recursion.
2375 if ((AllowExplicit || !Conv->isExplicit()) &&
2376 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2377 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002378 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002379 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002380 ToType, CandidateSet);
2381 else
John McCalla0296f72010-03-19 07:35:19 +00002382 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002383 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002384 }
2385 }
2386 }
John McCall3696dcb2010-08-17 07:23:57 +00002387 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2388 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002389
2390 SourceLocation DeclLoc = Initializer->getLocStart();
2391
2392 // Perform overload resolution. If it fails, return the failed result.
2393 OverloadCandidateSet::iterator Best;
2394 if (OverloadingResult Result
2395 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2396 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002397
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002398 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002399
2400 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002401 if (isa<CXXConversionDecl>(Function))
2402 T2 = Function->getResultType();
2403 else
2404 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002405
2406 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002407 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002408 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002409
2410 // Determine whether we need to perform derived-to-base or
2411 // cv-qualification adjustments.
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002412 ImplicitCastExpr::ResultCategory Category = ImplicitCastExpr::RValue;
2413 if (T2->isLValueReferenceType())
2414 Category = ImplicitCastExpr::LValue;
2415 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
2416 Category = RRef->getPointeeType()->isFunctionType() ?
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002417 ImplicitCastExpr::LValue : ImplicitCastExpr::XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002418
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002419 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002420 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002421 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregora8a089b2010-07-13 18:40:04 +00002422 = S.CompareReferenceRelationship(DeclLoc, T1,
2423 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002424 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002425 if (NewRefRelationship == Sema::Ref_Incompatible) {
2426 // If the type we've converted to is not reference-related to the
2427 // type we're looking for, then there is another conversion step
2428 // we need to perform to produce a temporary of the right type
2429 // that we'll be binding to.
2430 ImplicitConversionSequence ICS;
2431 ICS.setStandard();
2432 ICS.Standard = Best->FinalConversion;
2433 T2 = ICS.Standard.getToType(2);
2434 Sequence.AddConversionSequenceStep(ICS, T2);
2435 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002436 Sequence.AddDerivedToBaseCastStep(
2437 S.Context.getQualifiedType(T1,
2438 T2.getNonReferenceType().getQualifiers()),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002439 Category);
2440 else if (NewObjCConversion)
2441 Sequence.AddObjCObjectConversionStep(
2442 S.Context.getQualifiedType(T1,
2443 T2.getNonReferenceType().getQualifiers()));
2444
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002445 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002446 Sequence.AddQualificationConversionStep(cv1T1, Category);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002447
2448 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2449 return OR_Success;
2450}
2451
Sebastian Redld92badf2010-06-30 18:13:39 +00002452/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002453static void TryReferenceInitialization(Sema &S,
2454 const InitializedEntity &Entity,
2455 const InitializationKind &Kind,
2456 Expr *Initializer,
2457 InitializationSequence &Sequence) {
2458 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002459
Douglas Gregor1b303932009-12-22 15:35:07 +00002460 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002461 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002462 Qualifiers T1Quals;
2463 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002464 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002465 Qualifiers T2Quals;
2466 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002467 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002468
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002469 // If the initializer is the address of an overloaded function, try
2470 // to resolve the overloaded function. If all goes well, T2 is the
2471 // type of the resulting function.
2472 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002473 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002474 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2475 T1,
John McCall16df1e52010-03-30 21:47:33 +00002476 false,
2477 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002478 if (!Fn) {
2479 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2480 return;
2481 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002482
John McCall16df1e52010-03-30 21:47:33 +00002483 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002484 cv2T2 = Fn->getType();
2485 T2 = cv2T2.getUnqualifiedType();
2486 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002487
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 // Compute some basic properties of the types and the initializer.
2489 bool isLValueRef = DestType->isLValueReferenceType();
2490 bool isRValueRef = !isLValueRef;
2491 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002492 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002493 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002494 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002495 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2496 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002497
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002498 // C++0x [dcl.init.ref]p5:
2499 // A reference to type "cv1 T1" is initialized by an expression of type
2500 // "cv2 T2" as follows:
2501 //
2502 // - If the reference is an lvalue reference and the initializer
2503 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002504 // Note the analogous bullet points for rvlaue refs to functions. Because
2505 // there are no function rvalues in C++, rvalue refs to functions are treated
2506 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002507 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002508 bool T1Function = T1->isFunctionType();
2509 if (isLValueRef || T1Function) {
2510 if (InitCategory.isLValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002511 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2512 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2513 // reference-compatible with "cv2 T2," or
2514 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002515 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002516 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002517 // can occur. However, we do pay attention to whether it is a bit-field
2518 // to decide whether we're actually binding to a temporary created from
2519 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002520 if (DerivedToBase)
2521 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002522 S.Context.getQualifiedType(T1, T2Quals),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002523 ImplicitCastExpr::LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002524 else if (ObjCConversion)
2525 Sequence.AddObjCObjectConversionStep(
2526 S.Context.getQualifiedType(T1, T2Quals));
2527
Chandler Carruth04bdce62010-01-12 20:32:25 +00002528 if (T1Quals != T2Quals)
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002529 Sequence.AddQualificationConversionStep(cv1T1,ImplicitCastExpr::LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002530 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002531 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002532 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002533 return;
2534 }
2535
2536 // - has a class type (i.e., T2 is a class type), where T1 is not
2537 // reference-related to T2, and can be implicitly converted to an
2538 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2539 // with "cv3 T3" (this conversion is selected by enumerating the
2540 // applicable conversion functions (13.3.1.6) and choosing the best
2541 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002542 // If we have an rvalue ref to function type here, the rhs must be
2543 // an rvalue.
2544 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2545 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002546 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2547 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002548 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002549 Sequence);
2550 if (ConvOvlResult == OR_Success)
2551 return;
John McCall0d1da222010-01-12 00:44:57 +00002552 if (ConvOvlResult != OR_No_Viable_Function) {
2553 Sequence.SetOverloadFailure(
2554 InitializationSequence::FK_ReferenceInitOverloadFailed,
2555 ConvOvlResult);
2556 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002557 }
2558 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002559
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002560 // - Otherwise, the reference shall be an lvalue reference to a
2561 // non-volatile const type (i.e., cv1 shall be const), or the reference
2562 // shall be an rvalue reference and the initializer expression shall
Sebastian Redld92badf2010-06-30 18:13:39 +00002563 // be an rvalue or have a function type.
2564 // We handled the function type stuff above.
Douglas Gregord1e08642010-01-29 19:39:15 +00002565 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redld92badf2010-06-30 18:13:39 +00002566 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002567 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2568 Sequence.SetOverloadFailure(
2569 InitializationSequence::FK_ReferenceInitOverloadFailed,
2570 ConvOvlResult);
2571 else if (isLValueRef)
Sebastian Redld92badf2010-06-30 18:13:39 +00002572 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002573 ? (RefRelationship == Sema::Ref_Related
2574 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2575 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2576 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2577 else
2578 Sequence.SetFailed(
2579 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redld92badf2010-06-30 18:13:39 +00002580
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002581 return;
2582 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002583
2584 // - [If T1 is not a function type], if T2 is a class type and
2585 if (!T1Function && T2->isRecordType()) {
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002586 bool isXValue = InitCategory.isXValue();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002587 // - the initializer expression is an rvalue and "cv1 T1" is
2588 // reference-compatible with "cv2 T2", or
Sebastian Redld92badf2010-06-30 18:13:39 +00002589 if (InitCategory.isRValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002590 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002591 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2592 // compiler the freedom to perform a copy here or bind to the
2593 // object, while C++0x requires that we bind directly to the
2594 // object. Hence, we always bind to the object without making an
2595 // extra copy. However, in C++03 requires that we check for the
2596 // presence of a suitable copy constructor:
2597 //
2598 // The constructor that would be used to make the copy shall
2599 // be callable whether or not the copy is actually done.
2600 if (!S.getLangOptions().CPlusPlus0x)
2601 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2602
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002603 if (DerivedToBase)
2604 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002605 S.Context.getQualifiedType(T1, T2Quals),
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002606 isXValue ? ImplicitCastExpr::XValue
2607 : ImplicitCastExpr::RValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002608 else if (ObjCConversion)
2609 Sequence.AddObjCObjectConversionStep(
2610 S.Context.getQualifiedType(T1, T2Quals));
2611
Chandler Carruth04bdce62010-01-12 20:32:25 +00002612 if (T1Quals != T2Quals)
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002613 Sequence.AddQualificationConversionStep(cv1T1,
2614 isXValue ? ImplicitCastExpr::XValue
2615 : ImplicitCastExpr::RValue);
2616 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002617 return;
2618 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002619
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002620 // - T1 is not reference-related to T2 and the initializer expression
2621 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2622 // conversion is selected by enumerating the applicable conversion
2623 // functions (13.3.1.6) and choosing the best one through overload
2624 // resolution (13.3)),
2625 if (RefRelationship == Sema::Ref_Incompatible) {
2626 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2627 Kind, Initializer,
2628 /*AllowRValues=*/true,
2629 Sequence);
2630 if (ConvOvlResult)
2631 Sequence.SetOverloadFailure(
2632 InitializationSequence::FK_ReferenceInitOverloadFailed,
2633 ConvOvlResult);
2634
2635 return;
2636 }
2637
2638 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2639 return;
2640 }
2641
2642 // - If the initializer expression is an rvalue, with T2 an array type,
2643 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2644 // is bound to the object represented by the rvalue (see 3.10).
2645 // FIXME: How can an array type be reference-compatible with anything?
2646 // Don't we mean the element types of T1 and T2?
2647
2648 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2649 // from the initializer expression using the rules for a non-reference
2650 // copy initialization (8.5). The reference is then bound to the
2651 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002652
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653 // Determine whether we are allowed to call explicit constructors or
2654 // explicit conversion operators.
2655 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002656
2657 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2658
2659 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2660 /*SuppressUserConversions*/ false,
2661 AllowExplicit,
2662 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002663 // FIXME: Use the conversion function set stored in ICS to turn
2664 // this into an overloading ambiguity diagnostic. However, we need
2665 // to keep that set as an OverloadCandidateSet rather than as some
2666 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002667 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2668 Sequence.SetOverloadFailure(
2669 InitializationSequence::FK_ReferenceInitOverloadFailed,
2670 ConvOvlResult);
2671 else
2672 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002673 return;
2674 }
2675
2676 // [...] If T1 is reference-related to T2, cv1 must be the
2677 // same cv-qualification as, or greater cv-qualification
2678 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002679 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2680 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002681 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002682 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002683 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2684 return;
2685 }
2686
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002687 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2688 return;
2689}
2690
2691/// \brief Attempt character array initialization from a string literal
2692/// (C++ [dcl.init.string], C99 6.7.8).
2693static void TryStringLiteralInitialization(Sema &S,
2694 const InitializedEntity &Entity,
2695 const InitializationKind &Kind,
2696 Expr *Initializer,
2697 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002698 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002699 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002700}
2701
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002702/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2703/// enumerates the constructors of the initialized entity and performs overload
2704/// resolution to select the best.
2705static void TryConstructorInitialization(Sema &S,
2706 const InitializedEntity &Entity,
2707 const InitializationKind &Kind,
2708 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002709 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002710 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002711 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002712
2713 // Build the candidate set directly in the initialization sequence
2714 // structure, so that it will persist if we fail.
2715 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2716 CandidateSet.clear();
2717
2718 // Determine whether we are allowed to call explicit constructors or
2719 // explicit conversion operators.
2720 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2721 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002722 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002723
2724 // The type we're constructing needs to be complete.
2725 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002726 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002727 return;
2728 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002729
2730 // The type we're converting to is a class type. Enumerate its constructors
2731 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002732 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2733 assert(DestRecordType && "Constructor initialization requires record type");
2734 CXXRecordDecl *DestRecordDecl
2735 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2736
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002737 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002738 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002739 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002740 NamedDecl *D = *Con;
2741 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002742 bool SuppressUserConversions = false;
2743
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002744 // Find the constructor (which may be a template).
2745 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002746 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002747 if (ConstructorTmpl)
2748 Constructor = cast<CXXConstructorDecl>(
2749 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002750 else {
John McCalla0296f72010-03-19 07:35:19 +00002751 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002752
2753 // If we're performing copy initialization using a copy constructor, we
2754 // suppress user-defined conversions on the arguments.
2755 // FIXME: Move constructors?
2756 if (Kind.getKind() == InitializationKind::IK_Copy &&
2757 Constructor->isCopyConstructor())
2758 SuppressUserConversions = true;
2759 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002760
2761 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002762 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002763 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002764 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002765 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002766 Args, NumArgs, CandidateSet,
2767 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002768 else
John McCalla0296f72010-03-19 07:35:19 +00002769 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002770 Args, NumArgs, CandidateSet,
2771 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002772 }
2773 }
2774
2775 SourceLocation DeclLoc = Kind.getLocation();
2776
2777 // Perform overload resolution. If it fails, return the failed result.
2778 OverloadCandidateSet::iterator Best;
2779 if (OverloadingResult Result
2780 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2781 Sequence.SetOverloadFailure(
2782 InitializationSequence::FK_ConstructorOverloadFailed,
2783 Result);
2784 return;
2785 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002786
2787 // C++0x [dcl.init]p6:
2788 // If a program calls for the default initialization of an object
2789 // of a const-qualified type T, T shall be a class type with a
2790 // user-provided default constructor.
2791 if (Kind.getKind() == InitializationKind::IK_Default &&
2792 Entity.getType().isConstQualified() &&
2793 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2794 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2795 return;
2796 }
2797
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002798 // Add the constructor initialization step. Any cv-qualification conversion is
2799 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002800 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002801 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002802 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002803 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002804}
2805
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002806/// \brief Attempt value initialization (C++ [dcl.init]p7).
2807static void TryValueInitialization(Sema &S,
2808 const InitializedEntity &Entity,
2809 const InitializationKind &Kind,
2810 InitializationSequence &Sequence) {
2811 // C++ [dcl.init]p5:
2812 //
2813 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002814 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002815
2816 // -- if T is an array type, then each element is value-initialized;
2817 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2818 T = AT->getElementType();
2819
2820 if (const RecordType *RT = T->getAs<RecordType>()) {
2821 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2822 // -- if T is a class type (clause 9) with a user-declared
2823 // constructor (12.1), then the default constructor for T is
2824 // called (and the initialization is ill-formed if T has no
2825 // accessible default constructor);
2826 //
2827 // FIXME: we really want to refer to a single subobject of the array,
2828 // but Entity doesn't have a way to capture that (yet).
2829 if (ClassDecl->hasUserDeclaredConstructor())
2830 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2831
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002832 // -- if T is a (possibly cv-qualified) non-union class type
2833 // without a user-provided constructor, then the object is
2834 // zero-initialized and, if T’s implicitly-declared default
2835 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002836 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002837 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002838 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002839 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2840 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002841 }
2842 }
2843
Douglas Gregor1b303932009-12-22 15:35:07 +00002844 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002845 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2846}
2847
Douglas Gregor85dabae2009-12-16 01:38:02 +00002848/// \brief Attempt default initialization (C++ [dcl.init]p6).
2849static void TryDefaultInitialization(Sema &S,
2850 const InitializedEntity &Entity,
2851 const InitializationKind &Kind,
2852 InitializationSequence &Sequence) {
2853 assert(Kind.getKind() == InitializationKind::IK_Default);
2854
2855 // C++ [dcl.init]p6:
2856 // To default-initialize an object of type T means:
2857 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002858 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002859 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2860 DestType = Array->getElementType();
2861
2862 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2863 // constructor for T is called (and the initialization is ill-formed if
2864 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002865 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002866 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2867 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002868 }
2869
2870 // - otherwise, no initialization is performed.
2871 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2872
2873 // If a program calls for the default initialization of an object of
2874 // a const-qualified type T, T shall be a class type with a user-provided
2875 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002876 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002877 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2878}
2879
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002880/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2881/// which enumerates all conversion functions and performs overload resolution
2882/// to select the best.
2883static void TryUserDefinedConversion(Sema &S,
2884 const InitializedEntity &Entity,
2885 const InitializationKind &Kind,
2886 Expr *Initializer,
2887 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002888 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2889
Douglas Gregor1b303932009-12-22 15:35:07 +00002890 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002891 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2892 QualType SourceType = Initializer->getType();
2893 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2894 "Must have a class type to perform a user-defined conversion");
2895
2896 // Build the candidate set directly in the initialization sequence
2897 // structure, so that it will persist if we fail.
2898 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2899 CandidateSet.clear();
2900
2901 // Determine whether we are allowed to call explicit constructors or
2902 // explicit conversion operators.
2903 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2904
2905 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2906 // The type we're converting to is a class type. Enumerate its constructors
2907 // to see if there is a suitable conversion.
2908 CXXRecordDecl *DestRecordDecl
2909 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2910
Douglas Gregord9848152010-04-26 14:36:57 +00002911 // Try to complete the type we're converting to.
2912 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002913 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002914 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002915 Con != ConEnd; ++Con) {
2916 NamedDecl *D = *Con;
2917 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002918
Douglas Gregord9848152010-04-26 14:36:57 +00002919 // Find the constructor (which may be a template).
2920 CXXConstructorDecl *Constructor = 0;
2921 FunctionTemplateDecl *ConstructorTmpl
2922 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002923 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002924 Constructor = cast<CXXConstructorDecl>(
2925 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002926 else
Douglas Gregord9848152010-04-26 14:36:57 +00002927 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord9848152010-04-26 14:36:57 +00002928
2929 if (!Constructor->isInvalidDecl() &&
2930 Constructor->isConvertingConstructor(AllowExplicit)) {
2931 if (ConstructorTmpl)
2932 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2933 /*ExplicitArgs*/ 0,
2934 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002935 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002936 else
2937 S.AddOverloadCandidate(Constructor, FoundDecl,
2938 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002939 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002940 }
2941 }
2942 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002943 }
Eli Friedman78275202009-12-19 08:11:05 +00002944
2945 SourceLocation DeclLoc = Initializer->getLocStart();
2946
Douglas Gregor540c3b02009-12-14 17:27:33 +00002947 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2948 // The type we're converting from is a class type, enumerate its conversion
2949 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002950
Eli Friedman4afe9a32009-12-20 22:12:03 +00002951 // We can only enumerate the conversion functions for a complete type; if
2952 // the type isn't complete, simply skip this step.
2953 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2954 CXXRecordDecl *SourceRecordDecl
2955 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002956
John McCallad371252010-01-20 00:46:10 +00002957 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002958 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002959 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002960 E = Conversions->end();
2961 I != E; ++I) {
2962 NamedDecl *D = *I;
2963 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2964 if (isa<UsingShadowDecl>(D))
2965 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2966
2967 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2968 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002969 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002970 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002971 else
John McCallda4458e2010-03-31 01:36:47 +00002972 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002973
2974 if (AllowExplicit || !Conv->isExplicit()) {
2975 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002976 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002977 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002978 CandidateSet);
2979 else
John McCalla0296f72010-03-19 07:35:19 +00002980 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00002981 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002982 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002983 }
2984 }
2985 }
2986
Douglas Gregor540c3b02009-12-14 17:27:33 +00002987 // Perform overload resolution. If it fails, return the failed result.
2988 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002989 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002990 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2991 Sequence.SetOverloadFailure(
2992 InitializationSequence::FK_UserConversionOverloadFailed,
2993 Result);
2994 return;
2995 }
John McCall0d1da222010-01-12 00:44:57 +00002996
Douglas Gregor540c3b02009-12-14 17:27:33 +00002997 FunctionDecl *Function = Best->Function;
2998
2999 if (isa<CXXConstructorDecl>(Function)) {
3000 // Add the user-defined conversion step. Any cv-qualification conversion is
3001 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003002 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003003 return;
3004 }
3005
3006 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003007 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003008 if (ConvType->getAs<RecordType>()) {
3009 // If we're converting to a class type, there may be an copy if
3010 // the resulting temporary object (possible to create an object of
3011 // a base class type). That copy is not a separate conversion, so
3012 // we just make a note of the actual destination type (possibly a
3013 // base class of the type returned by the conversion function) and
3014 // let the user-defined conversion step handle the conversion.
3015 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3016 return;
3017 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003018
Douglas Gregor5ab11652010-04-17 22:01:05 +00003019 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3020
3021 // If the conversion following the call to the conversion function
3022 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003023 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3024 Best->FinalConversion.Third) {
3025 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003026 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003027 ICS.Standard = Best->FinalConversion;
3028 Sequence.AddConversionSequenceStep(ICS, DestType);
3029 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003030}
3031
John McCallec6f4e92010-06-04 02:29:22 +00003032bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
3033 const InitializedEntity &Entity,
3034 Expr *Initializer,
3035 bool SuppressUserConversions,
3036 bool AllowExplicitConversions,
3037 bool InOverloadResolution) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003038 ImplicitConversionSequence ICS
John McCallec6f4e92010-06-04 02:29:22 +00003039 = TryImplicitConversion(Initializer, Entity.getType(),
3040 SuppressUserConversions,
3041 AllowExplicitConversions,
3042 InOverloadResolution);
3043 if (ICS.isBad()) return true;
3044
3045 // Perform the actual conversion.
Douglas Gregor1b303932009-12-22 15:35:07 +00003046 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
John McCallec6f4e92010-06-04 02:29:22 +00003047 return false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003048}
3049
3050InitializationSequence::InitializationSequence(Sema &S,
3051 const InitializedEntity &Entity,
3052 const InitializationKind &Kind,
3053 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003054 unsigned NumArgs)
3055 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003056 ASTContext &Context = S.Context;
3057
3058 // C++0x [dcl.init]p16:
3059 // The semantics of initializers are as follows. The destination type is
3060 // the type of the object or reference being initialized and the source
3061 // type is the type of the initializer expression. The source type is not
3062 // defined when the initializer is a braced-init-list or when it is a
3063 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003064 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003065
3066 if (DestType->isDependentType() ||
3067 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3068 SequenceKind = DependentSequence;
3069 return;
3070 }
3071
3072 QualType SourceType;
3073 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003074 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003075 Initializer = Args[0];
3076 if (!isa<InitListExpr>(Initializer))
3077 SourceType = Initializer->getType();
3078 }
3079
3080 // - If the initializer is a braced-init-list, the object is
3081 // list-initialized (8.5.4).
3082 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3083 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003084 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003085 }
3086
3087 // - If the destination type is a reference type, see 8.5.3.
3088 if (DestType->isReferenceType()) {
3089 // C++0x [dcl.init.ref]p1:
3090 // A variable declared to be a T& or T&&, that is, "reference to type T"
3091 // (8.3.2), shall be initialized by an object, or function, of type T or
3092 // by an object that can be converted into a T.
3093 // (Therefore, multiple arguments are not permitted.)
3094 if (NumArgs != 1)
3095 SetFailed(FK_TooManyInitsForReference);
3096 else
3097 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3098 return;
3099 }
3100
3101 // - If the destination type is an array of characters, an array of
3102 // char16_t, an array of char32_t, or an array of wchar_t, and the
3103 // initializer is a string literal, see 8.5.2.
3104 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3105 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3106 return;
3107 }
3108
3109 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003110 if (Kind.getKind() == InitializationKind::IK_Value ||
3111 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003112 TryValueInitialization(S, Entity, Kind, *this);
3113 return;
3114 }
3115
Douglas Gregor85dabae2009-12-16 01:38:02 +00003116 // Handle default initialization.
3117 if (Kind.getKind() == InitializationKind::IK_Default){
3118 TryDefaultInitialization(S, Entity, Kind, *this);
3119 return;
3120 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003121
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003122 // - Otherwise, if the destination type is an array, the program is
3123 // ill-formed.
3124 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3125 if (AT->getElementType()->isAnyCharacterType())
3126 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3127 else
3128 SetFailed(FK_ArrayNeedsInitList);
3129
3130 return;
3131 }
Eli Friedman78275202009-12-19 08:11:05 +00003132
3133 // Handle initialization in C
3134 if (!S.getLangOptions().CPlusPlus) {
3135 setSequenceKind(CAssignment);
3136 AddCAssignmentStep(DestType);
3137 return;
3138 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003139
3140 // - If the destination type is a (possibly cv-qualified) class type:
3141 if (DestType->isRecordType()) {
3142 // - If the initialization is direct-initialization, or if it is
3143 // copy-initialization where the cv-unqualified version of the
3144 // source type is the same class as, or a derived class of, the
3145 // class of the destination, constructors are considered. [...]
3146 if (Kind.getKind() == InitializationKind::IK_Direct ||
3147 (Kind.getKind() == InitializationKind::IK_Copy &&
3148 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3149 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003150 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003151 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003152 // - Otherwise (i.e., for the remaining copy-initialization cases),
3153 // user-defined conversion sequences that can convert from the source
3154 // type to the destination type or (when a conversion function is
3155 // used) to a derived class thereof are enumerated as described in
3156 // 13.3.1.4, and the best one is chosen through overload resolution
3157 // (13.3).
3158 else
3159 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3160 return;
3161 }
3162
Douglas Gregor85dabae2009-12-16 01:38:02 +00003163 if (NumArgs > 1) {
3164 SetFailed(FK_TooManyInitsForScalar);
3165 return;
3166 }
3167 assert(NumArgs == 1 && "Zero-argument case handled above");
3168
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003169 // - Otherwise, if the source type is a (possibly cv-qualified) class
3170 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003171 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003172 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3173 return;
3174 }
3175
3176 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003177 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003178 // conversions (Clause 4) will be used, if necessary, to convert the
3179 // initializer expression to the cv-unqualified version of the
3180 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003181 if (S.TryImplicitConversion(*this, Entity, Initializer,
3182 /*SuppressUserConversions*/ true,
3183 /*AllowExplicitConversions*/ false,
3184 /*InOverloadResolution*/ false))
3185 SetFailed(InitializationSequence::FK_ConversionFailed);
3186 else
3187 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003188}
3189
3190InitializationSequence::~InitializationSequence() {
3191 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3192 StepEnd = Steps.end();
3193 Step != StepEnd; ++Step)
3194 Step->Destroy();
3195}
3196
3197//===----------------------------------------------------------------------===//
3198// Perform initialization
3199//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003200static Sema::AssignmentAction
3201getAssignmentAction(const InitializedEntity &Entity) {
3202 switch(Entity.getKind()) {
3203 case InitializedEntity::EK_Variable:
3204 case InitializedEntity::EK_New:
3205 return Sema::AA_Initializing;
3206
3207 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003208 if (Entity.getDecl() &&
3209 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3210 return Sema::AA_Sending;
3211
Douglas Gregore1314a62009-12-18 05:02:21 +00003212 return Sema::AA_Passing;
3213
3214 case InitializedEntity::EK_Result:
3215 return Sema::AA_Returning;
3216
3217 case InitializedEntity::EK_Exception:
3218 case InitializedEntity::EK_Base:
3219 llvm_unreachable("No assignment action for C++-specific initialization");
3220 break;
3221
3222 case InitializedEntity::EK_Temporary:
3223 // FIXME: Can we tell apart casting vs. converting?
3224 return Sema::AA_Casting;
3225
3226 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003227 case InitializedEntity::EK_ArrayElement:
3228 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003229 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003230 return Sema::AA_Initializing;
3231 }
3232
3233 return Sema::AA_Converting;
3234}
3235
Douglas Gregor95562572010-04-24 23:45:46 +00003236/// \brief Whether we should binding a created object as a temporary when
3237/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003238static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003239 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003240 case InitializedEntity::EK_ArrayElement:
3241 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003242 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003243 case InitializedEntity::EK_New:
3244 case InitializedEntity::EK_Variable:
3245 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003246 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003247 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003248 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003249 return false;
3250
3251 case InitializedEntity::EK_Parameter:
3252 case InitializedEntity::EK_Temporary:
3253 return true;
3254 }
3255
3256 llvm_unreachable("missed an InitializedEntity kind?");
3257}
3258
Douglas Gregor95562572010-04-24 23:45:46 +00003259/// \brief Whether the given entity, when initialized with an object
3260/// created for that initialization, requires destruction.
3261static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3262 switch (Entity.getKind()) {
3263 case InitializedEntity::EK_Member:
3264 case InitializedEntity::EK_Result:
3265 case InitializedEntity::EK_New:
3266 case InitializedEntity::EK_Base:
3267 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003268 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003269 return false;
3270
3271 case InitializedEntity::EK_Variable:
3272 case InitializedEntity::EK_Parameter:
3273 case InitializedEntity::EK_Temporary:
3274 case InitializedEntity::EK_ArrayElement:
3275 case InitializedEntity::EK_Exception:
3276 return true;
3277 }
3278
3279 llvm_unreachable("missed an InitializedEntity kind?");
3280}
3281
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003282/// \brief Make a (potentially elidable) temporary copy of the object
3283/// provided by the given initializer by calling the appropriate copy
3284/// constructor.
3285///
3286/// \param S The Sema object used for type-checking.
3287///
3288/// \param T The type of the temporary object, which must either by
3289/// the type of the initializer expression or a superclass thereof.
3290///
3291/// \param Enter The entity being initialized.
3292///
3293/// \param CurInit The initializer expression.
3294///
3295/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3296/// is permitted in C++03 (but not C++0x) when binding a reference to
3297/// an rvalue.
3298///
3299/// \returns An expression that copies the initializer expression into
3300/// a temporary object, or an error expression if a copy could not be
3301/// created.
John McCalldadc5752010-08-24 06:29:42 +00003302static ExprResult CopyObject(Sema &S,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003303 QualType T,
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003304 const InitializedEntity &Entity,
John McCalldadc5752010-08-24 06:29:42 +00003305 ExprResult CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003306 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003307 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003308 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003309 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003310 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003311 Class = cast<CXXRecordDecl>(Record->getDecl());
3312 if (!Class)
3313 return move(CurInit);
3314
3315 // C++0x [class.copy]p34:
3316 // When certain criteria are met, an implementation is allowed to
3317 // omit the copy/move construction of a class object, even if the
3318 // copy/move constructor and/or destructor for the object have
3319 // side effects. [...]
3320 // - when a temporary class object that has not been bound to a
3321 // reference (12.2) would be copied/moved to a class object
3322 // with the same cv-unqualified type, the copy/move operation
3323 // can be omitted by constructing the temporary object
3324 // directly into the target of the omitted copy/move
3325 //
3326 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003327 // elision for return statements and throw expressions are handled as part
3328 // of constructor initialization, while copy elision for exception handlers
3329 // is handled by the run-time.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003330 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003331 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregore1314a62009-12-18 05:02:21 +00003332 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003333 switch (Entity.getKind()) {
3334 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003335 Loc = Entity.getReturnLoc();
3336 break;
3337
3338 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003339 Loc = Entity.getThrowLoc();
3340 break;
3341
3342 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003343 Loc = Entity.getDecl()->getLocation();
3344 break;
3345
Anders Carlsson0bd52402010-01-24 00:19:41 +00003346 case InitializedEntity::EK_ArrayElement:
3347 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003348 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003349 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003350 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003351 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003352 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003353 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003354 Loc = CurInitExpr->getLocStart();
3355 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003356 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003357
3358 // Make sure that the type we are copying is complete.
3359 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3360 return move(CurInit);
3361
Douglas Gregore1314a62009-12-18 05:02:21 +00003362 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003363 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003364 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003365 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003366 Con != ConEnd; ++Con) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003367 // Only consider copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003368 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3369 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor7566e4a2010-04-18 02:16:12 +00003370 !Constructor->isCopyConstructor() ||
3371 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregore1314a62009-12-18 05:02:21 +00003372 continue;
John McCalla0296f72010-03-19 07:35:19 +00003373
3374 DeclAccessPair FoundDecl
3375 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3376 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003377 &CurInitExpr, 1, CandidateSet);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003378 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003379
3380 OverloadCandidateSet::iterator Best;
3381 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3382 case OR_Success:
3383 break;
3384
3385 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003386 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3387 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3388 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003389 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003390 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003391 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3392 &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003393 if (!IsExtraneousCopy || S.isSFINAEContext())
3394 return S.ExprError();
3395 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003396
3397 case OR_Ambiguous:
3398 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003399 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003400 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003401 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3402 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003403 return S.ExprError();
3404
3405 case OR_Deleted:
3406 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003407 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003408 << CurInitExpr->getSourceRange();
3409 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3410 << Best->Function->isDeleted();
3411 return S.ExprError();
3412 }
3413
Douglas Gregor5ab11652010-04-17 22:01:05 +00003414 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003415 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003416 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003417
Anders Carlssona01874b2010-04-21 18:47:17 +00003418 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003419 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003420
3421 if (IsExtraneousCopy) {
3422 // If this is a totally extraneous copy for C++03 reference
3423 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003424 // expression. We don't generate an (elided) copy operation here
3425 // because doing so would require us to pass down a flag to avoid
3426 // infinite recursion, where each step adds another extraneous,
3427 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003428
Douglas Gregor30b52772010-04-18 07:57:34 +00003429 // Instantiate the default arguments of any extra parameters in
3430 // the selected copy constructor, as if we were going to create a
3431 // proper call to the copy constructor.
3432 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3433 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3434 if (S.RequireCompleteType(Loc, Parm->getType(),
3435 S.PDiag(diag::err_call_incomplete_argument)))
3436 break;
3437
3438 // Build the default argument expression; we don't actually care
3439 // if this succeeds or not, because this routine will complain
3440 // if there was a problem.
3441 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3442 }
3443
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003444 return S.Owned(CurInitExpr);
3445 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003446
3447 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003448 // constructor call (we might have derived-to-base conversions, or
3449 // the copy constructor may have default arguments).
Douglas Gregor5ab11652010-04-17 22:01:05 +00003450 if (S.CompleteConstructorCall(Constructor,
John McCall37ad5512010-08-23 06:44:23 +00003451 Sema::MultiExprArg(S, &CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003452 Loc, ConstructorArgs))
3453 return S.ExprError();
3454
Douglas Gregord0ace022010-04-25 00:55:24 +00003455 // Actually perform the constructor call.
3456 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
3457 move_arg(ConstructorArgs));
3458
3459 // If we're supposed to bind temporaries, do so.
3460 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3461 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3462 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003463}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003464
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003465void InitializationSequence::PrintInitLocationNote(Sema &S,
3466 const InitializedEntity &Entity) {
3467 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3468 if (Entity.getDecl()->getLocation().isInvalid())
3469 return;
3470
3471 if (Entity.getDecl()->getDeclName())
3472 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3473 << Entity.getDecl()->getDeclName();
3474 else
3475 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3476 }
3477}
3478
John McCalldadc5752010-08-24 06:29:42 +00003479ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003480InitializationSequence::Perform(Sema &S,
3481 const InitializedEntity &Entity,
3482 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003483 Action::MultiExprArg Args,
3484 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003485 if (SequenceKind == FailedSequence) {
3486 unsigned NumArgs = Args.size();
3487 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3488 return S.ExprError();
3489 }
3490
3491 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003492 // If the declaration is a non-dependent, incomplete array type
3493 // that has an initializer, then its type will be completed once
3494 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003495 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003496 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003497 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003498 if (const IncompleteArrayType *ArrayT
3499 = S.Context.getAsIncompleteArrayType(DeclType)) {
3500 // FIXME: We don't currently have the ability to accurately
3501 // compute the length of an initializer list without
3502 // performing full type-checking of the initializer list
3503 // (since we have to determine where braces are implicitly
3504 // introduced and such). So, we fall back to making the array
3505 // type a dependently-sized array type with no specified
3506 // bound.
3507 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3508 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003509
Douglas Gregor51e77d52009-12-10 17:56:55 +00003510 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003511 if (DeclaratorDecl *DD = Entity.getDecl()) {
3512 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3513 TypeLoc TL = TInfo->getTypeLoc();
3514 if (IncompleteArrayTypeLoc *ArrayLoc
3515 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3516 Brackets = ArrayLoc->getBracketsRange();
3517 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003518 }
3519
3520 *ResultType
3521 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3522 /*NumElts=*/0,
3523 ArrayT->getSizeModifier(),
3524 ArrayT->getIndexTypeCVRQualifiers(),
3525 Brackets);
3526 }
3527
3528 }
3529 }
3530
Eli Friedmana553d4a2009-12-22 02:35:53 +00003531 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003532 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003533
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003534 if (Args.size() == 0)
3535 return S.Owned((Expr *)0);
3536
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003537 unsigned NumArgs = Args.size();
3538 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3539 SourceLocation(),
3540 (Expr **)Args.release(),
3541 NumArgs,
3542 SourceLocation()));
3543 }
3544
Douglas Gregor85dabae2009-12-16 01:38:02 +00003545 if (SequenceKind == NoInitialization)
3546 return S.Owned((Expr *)0);
3547
Douglas Gregor1b303932009-12-22 15:35:07 +00003548 QualType DestType = Entity.getType().getNonReferenceType();
3549 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003550 // the same as Entity.getDecl()->getType() in cases involving type merging,
3551 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003552 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003553 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003554 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003555
John McCalldadc5752010-08-24 06:29:42 +00003556 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003557
3558 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3559
3560 // For initialization steps that start with a single initializer,
3561 // grab the only argument out the Args and place it into the "current"
3562 // initializer.
3563 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003564 case SK_ResolveAddressOfOverloadedFunction:
3565 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003566 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003567 case SK_CastDerivedToBaseLValue:
3568 case SK_BindReference:
3569 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003570 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003571 case SK_UserConversion:
3572 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003573 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003574 case SK_QualificationConversionRValue:
3575 case SK_ConversionSequence:
3576 case SK_ListInitialization:
3577 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003578 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003579 case SK_ObjCObjectConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00003580 assert(Args.size() == 1);
John McCalldadc5752010-08-24 06:29:42 +00003581 CurInit = ExprResult(((Expr **)(Args.get()))[0]->Retain());
Douglas Gregore1314a62009-12-18 05:02:21 +00003582 if (CurInit.isInvalid())
3583 return S.ExprError();
3584 break;
3585
3586 case SK_ConstructorInitialization:
3587 case SK_ZeroInitialization:
3588 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003589 }
3590
3591 // Walk through the computed steps for the initialization sequence,
3592 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003593 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003594 for (step_iterator Step = step_begin(), StepEnd = step_end();
3595 Step != StepEnd; ++Step) {
3596 if (CurInit.isInvalid())
3597 return S.ExprError();
3598
3599 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003600 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003601
3602 switch (Step->Kind) {
3603 case SK_ResolveAddressOfOverloadedFunction:
3604 // Overload resolution determined which function invoke; update the
3605 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003606 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003607 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003608 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003609 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003610 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003611 break;
3612
3613 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003614 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003615 case SK_CastDerivedToBaseLValue: {
3616 // We have a derived-to-base cast that produces either an rvalue or an
3617 // lvalue. Perform that cast.
3618
John McCallcf142162010-08-07 06:22:56 +00003619 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621 // Casts to inaccessible base classes are allowed with C-style casts.
3622 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3623 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3624 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003625 CurInitExpr->getSourceRange(),
3626 &BasePath, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003627 return S.ExprError();
3628
Douglas Gregor88d292c2010-05-13 16:44:06 +00003629 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3630 QualType T = SourceType;
3631 if (const PointerType *Pointer = T->getAs<PointerType>())
3632 T = Pointer->getPointeeType();
3633 if (const RecordType *RecordTy = T->getAs<RecordType>())
3634 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3635 cast<CXXRecordDecl>(RecordTy->getDecl()));
3636 }
3637
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003638 ImplicitCastExpr::ResultCategory Category =
3639 Step->Kind == SK_CastDerivedToBaseLValue ?
3640 ImplicitCastExpr::LValue :
3641 (Step->Kind == SK_CastDerivedToBaseXValue ?
3642 ImplicitCastExpr::XValue :
3643 ImplicitCastExpr::RValue);
John McCallcf142162010-08-07 06:22:56 +00003644 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3645 Step->Type,
3646 CastExpr::CK_DerivedToBase,
3647 (Expr*)CurInit.release(),
3648 &BasePath, Category));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003649 break;
3650 }
3651
3652 case SK_BindReference:
3653 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3654 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3655 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003656 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003657 << BitField->getDeclName()
3658 << CurInitExpr->getSourceRange();
3659 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3660 return S.ExprError();
3661 }
Anders Carlssona91be642010-01-29 02:47:33 +00003662
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003663 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003664 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003665 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3666 << Entity.getType().isVolatileQualified()
3667 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003668 PrintInitLocationNote(S, Entity);
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003669 return S.ExprError();
3670 }
3671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003672 // Reference binding does not have any corresponding ASTs.
3673
3674 // Check exception specifications
3675 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3676 return S.ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003677
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003678 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003679
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003680 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003681 // Reference binding does not have any corresponding ASTs.
3682
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003683 // Check exception specifications
3684 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3685 return S.ExprError();
3686
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003687 break;
3688
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003689 case SK_ExtraneousCopyToTemporary:
3690 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3691 /*IsExtraneousCopy=*/true);
3692 break;
3693
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003694 case SK_UserConversion: {
3695 // We have a user-defined conversion that invokes either a constructor
3696 // or a conversion function.
3697 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003698 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003699 FunctionDecl *Fn = Step->Function.Function;
3700 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003701 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003702 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003703 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003704 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003705 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003706 SourceLocation Loc = CurInitExpr->getLocStart();
3707 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003708
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003709 // Determine the arguments required to actually perform the constructor
3710 // call.
3711 if (S.CompleteConstructorCall(Constructor,
John McCall37ad5512010-08-23 06:44:23 +00003712 Sema::MultiExprArg(S, &CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003713 Loc, ConstructorArgs))
3714 return S.ExprError();
3715
3716 // Build the an expression that constructs a temporary.
3717 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3718 move_arg(ConstructorArgs));
3719 if (CurInit.isInvalid())
3720 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003721
Anders Carlssona01874b2010-04-21 18:47:17 +00003722 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003723 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003724 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003725
3726 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003727 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3728 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3729 S.IsDerivedFrom(SourceType, Class))
3730 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003731
3732 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003733 } else {
3734 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003735 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003736 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003737 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003738 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003739 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003740
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003741 // FIXME: Should we move this initialization into a separate
3742 // derived-to-base conversion? I believe the answer is "no", because
3743 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003744 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003745 FoundFn, Conversion))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003746 return S.ExprError();
3747
3748 // Do a little dance to make sure that CurInit has the proper
3749 // pointer.
3750 CurInit.release();
3751
3752 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003753 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3754 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003755 if (CurInit.isInvalid() || !CurInit.get())
3756 return S.ExprError();
3757
3758 CastKind = CastExpr::CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003759
3760 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003761 }
3762
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003763 bool RequiresCopy = !IsCopy &&
3764 getKind() != InitializationSequence::ReferenceBinding;
3765 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003766 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003767 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3768 CurInitExpr = static_cast<Expr *>(CurInit.get());
3769 QualType T = CurInitExpr->getType();
3770 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003771 CXXDestructorDecl *Destructor
3772 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003773 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3774 S.PDiag(diag::err_access_dtor_temp) << T);
3775 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3776 }
3777 }
3778
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003779 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003780 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003781 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3782 CurInitExpr->getType(),
3783 CastKind, CurInitExpr, 0,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003784 IsLvalue ? ImplicitCastExpr::LValue : ImplicitCastExpr::RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003785
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003786 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003787 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3788 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003789
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003790 break;
3791 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003792
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003793 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003794 case SK_QualificationConversionXValue:
3795 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003796 // Perform a qualification conversion; these can never go wrong.
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003797 ImplicitCastExpr::ResultCategory Category =
3798 Step->Kind == SK_QualificationConversionLValue ?
3799 ImplicitCastExpr::LValue :
3800 (Step->Kind == SK_QualificationConversionXValue ?
3801 ImplicitCastExpr::XValue :
3802 ImplicitCastExpr::RValue);
3803 S.ImpCastExprToType(CurInitExpr, Step->Type, CastExpr::CK_NoOp, Category);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003804 CurInit.release();
3805 CurInit = S.Owned(CurInitExpr);
3806 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003807 }
3808
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003809 case SK_ConversionSequence: {
3810 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3811
3812 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3813 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003814 return S.ExprError();
3815
3816 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003817 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003818 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003819 }
3820
Douglas Gregor51e77d52009-12-10 17:56:55 +00003821 case SK_ListInitialization: {
3822 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3823 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003824 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003825 return S.ExprError();
3826
3827 CurInit.release();
3828 CurInit = S.Owned(InitList);
3829 break;
3830 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003831
3832 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003833 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003834 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003835 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003836
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003837 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003838 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003839 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3840 ? Kind.getEqualLoc()
3841 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003842
3843 if (Kind.getKind() == InitializationKind::IK_Default) {
3844 // Force even a trivial, implicit default constructor to be
3845 // semantically checked. We do this explicitly because we don't build
3846 // the definition for completely trivial constructors.
3847 CXXRecordDecl *ClassDecl = Constructor->getParent();
3848 assert(ClassDecl && "No parent class for constructor.");
3849 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3850 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3851 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3852 }
3853
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003854 // Determine the arguments required to actually perform the constructor
3855 // call.
3856 if (S.CompleteConstructorCall(Constructor, move(Args),
3857 Loc, ConstructorArgs))
3858 return S.ExprError();
3859
Chandler Carruthc9262402010-08-23 07:55:51 +00003860
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003861 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003862 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003863 (Kind.getKind() == InitializationKind::IK_Direct ||
3864 Kind.getKind() == InitializationKind::IK_Value)) {
3865 // An explicitly-constructed temporary, e.g., X(1, 2).
3866 unsigned NumExprs = ConstructorArgs.size();
3867 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003868 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003869 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3870 Constructor,
3871 Entity.getType(),
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003872 Loc,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003873 Exprs,
3874 NumExprs,
Douglas Gregor199db362010-04-27 20:36:09 +00003875 Kind.getParenRange().getEnd(),
3876 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003877 } else {
3878 CXXConstructExpr::ConstructionKind ConstructKind =
3879 CXXConstructExpr::CK_Complete;
3880
3881 if (Entity.getKind() == InitializedEntity::EK_Base) {
3882 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3883 CXXConstructExpr::CK_VirtualBase :
3884 CXXConstructExpr::CK_NonVirtualBase;
3885 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003886
3887 // If the entity allows NRVO, mark the construction as elidable
3888 // unconditionally.
3889 if (Entity.allowsNRVO())
3890 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3891 Constructor, /*Elidable=*/true,
3892 move_arg(ConstructorArgs),
3893 ConstructorInitRequiresZeroInit,
3894 ConstructKind);
3895 else
3896 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3897 Constructor,
3898 move_arg(ConstructorArgs),
3899 ConstructorInitRequiresZeroInit,
3900 ConstructKind);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003901 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003902 if (CurInit.isInvalid())
3903 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003904
3905 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003906 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003907 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003908 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003909
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003910 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003911 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003912
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003913 break;
3914 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003915
3916 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003917 step_iterator NextStep = Step;
3918 ++NextStep;
3919 if (NextStep != StepEnd &&
3920 NextStep->Kind == SK_ConstructorInitialization) {
3921 // The need for zero-initialization is recorded directly into
3922 // the call to the object's constructor within the next step.
3923 ConstructorInitRequiresZeroInit = true;
3924 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3925 S.getLangOptions().CPlusPlus &&
3926 !Kind.isImplicitValueInit()) {
Douglas Gregor747eb782010-07-08 06:14:04 +00003927 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(Step->Type,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003928 Kind.getRange().getBegin(),
3929 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003930 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003931 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003932 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003933 break;
3934 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003935
3936 case SK_CAssignment: {
3937 QualType SourceType = CurInitExpr->getType();
3938 Sema::AssignConvertType ConvTy =
3939 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003940
3941 // If this is a call, allow conversion to a transparent union.
3942 if (ConvTy != Sema::Compatible &&
3943 Entity.getKind() == InitializedEntity::EK_Parameter &&
3944 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3945 == Sema::Compatible)
3946 ConvTy = Sema::Compatible;
3947
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003948 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00003949 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3950 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003951 CurInitExpr,
3952 getAssignmentAction(Entity),
3953 &Complained)) {
3954 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003955 return S.ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003956 } else if (Complained)
3957 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003958
3959 CurInit.release();
3960 CurInit = S.Owned(CurInitExpr);
3961 break;
3962 }
Eli Friedman78275202009-12-19 08:11:05 +00003963
3964 case SK_StringInit: {
3965 QualType Ty = Step->Type;
3966 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3967 break;
3968 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003969
3970 case SK_ObjCObjectConversion:
3971 S.ImpCastExprToType(CurInitExpr, Step->Type,
3972 CastExpr::CK_ObjCObjectLValueCast,
3973 S.CastCategory(CurInitExpr));
3974 CurInit.release();
3975 CurInit = S.Owned(CurInitExpr);
3976 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003977 }
3978 }
3979
3980 return move(CurInit);
3981}
3982
3983//===----------------------------------------------------------------------===//
3984// Diagnose initialization failures
3985//===----------------------------------------------------------------------===//
3986bool InitializationSequence::Diagnose(Sema &S,
3987 const InitializedEntity &Entity,
3988 const InitializationKind &Kind,
3989 Expr **Args, unsigned NumArgs) {
3990 if (SequenceKind != FailedSequence)
3991 return false;
3992
Douglas Gregor1b303932009-12-22 15:35:07 +00003993 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003994 switch (Failure) {
3995 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003996 // FIXME: Customize for the initialized entity?
3997 if (NumArgs == 0)
3998 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3999 << DestType.getNonReferenceType();
4000 else // FIXME: diagnostic below could be better!
4001 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4002 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004003 break;
4004
4005 case FK_ArrayNeedsInitList:
4006 case FK_ArrayNeedsInitListOrStringLiteral:
4007 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4008 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4009 break;
4010
John McCall16df1e52010-03-30 21:47:33 +00004011 case FK_AddressOfOverloadFailed: {
4012 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004013 S.ResolveAddressOfOverloadedFunction(Args[0],
4014 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004015 true,
4016 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004017 break;
John McCall16df1e52010-03-30 21:47:33 +00004018 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004019
4020 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004021 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004022 switch (FailedOverloadResult) {
4023 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004024 if (Failure == FK_UserConversionOverloadFailed)
4025 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4026 << Args[0]->getType() << DestType
4027 << Args[0]->getSourceRange();
4028 else
4029 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4030 << DestType << Args[0]->getType()
4031 << Args[0]->getSourceRange();
4032
John McCallad907772010-01-12 07:18:19 +00004033 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
4034 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004035 break;
4036
4037 case OR_No_Viable_Function:
4038 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4039 << Args[0]->getType() << DestType.getNonReferenceType()
4040 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00004041 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4042 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004043 break;
4044
4045 case OR_Deleted: {
4046 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4047 << Args[0]->getType() << DestType.getNonReferenceType()
4048 << Args[0]->getSourceRange();
4049 OverloadCandidateSet::iterator Best;
4050 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4051 Kind.getLocation(),
4052 Best);
4053 if (Ovl == OR_Deleted) {
4054 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4055 << Best->Function->isDeleted();
4056 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004057 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004058 }
4059 break;
4060 }
4061
4062 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004063 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004064 break;
4065 }
4066 break;
4067
4068 case FK_NonConstLValueReferenceBindingToTemporary:
4069 case FK_NonConstLValueReferenceBindingToUnrelated:
4070 S.Diag(Kind.getLocation(),
4071 Failure == FK_NonConstLValueReferenceBindingToTemporary
4072 ? diag::err_lvalue_reference_bind_to_temporary
4073 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004074 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004075 << DestType.getNonReferenceType()
4076 << Args[0]->getType()
4077 << Args[0]->getSourceRange();
4078 break;
4079
4080 case FK_RValueReferenceBindingToLValue:
4081 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4082 << Args[0]->getSourceRange();
4083 break;
4084
4085 case FK_ReferenceInitDropsQualifiers:
4086 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4087 << DestType.getNonReferenceType()
4088 << Args[0]->getType()
4089 << Args[0]->getSourceRange();
4090 break;
4091
4092 case FK_ReferenceInitFailed:
4093 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4094 << DestType.getNonReferenceType()
4095 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4096 << Args[0]->getType()
4097 << Args[0]->getSourceRange();
4098 break;
4099
4100 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004101 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4102 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004103 << DestType
4104 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4105 << Args[0]->getType()
4106 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004107 break;
4108
4109 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004110 SourceRange R;
4111
4112 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4113 R = SourceRange(InitList->getInit(1)->getLocStart(),
4114 InitList->getLocEnd());
4115 else
4116 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004117
4118 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00004119 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004120 break;
4121 }
4122
4123 case FK_ReferenceBindingToInitList:
4124 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4125 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4126 break;
4127
4128 case FK_InitListBadDestinationType:
4129 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4130 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4131 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004132
4133 case FK_ConstructorOverloadFailed: {
4134 SourceRange ArgsRange;
4135 if (NumArgs)
4136 ArgsRange = SourceRange(Args[0]->getLocStart(),
4137 Args[NumArgs - 1]->getLocEnd());
4138
4139 // FIXME: Using "DestType" for the entity we're printing is probably
4140 // bad.
4141 switch (FailedOverloadResult) {
4142 case OR_Ambiguous:
4143 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4144 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00004145 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00004146 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004147 break;
4148
4149 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004150 if (Kind.getKind() == InitializationKind::IK_Default &&
4151 (Entity.getKind() == InitializedEntity::EK_Base ||
4152 Entity.getKind() == InitializedEntity::EK_Member) &&
4153 isa<CXXConstructorDecl>(S.CurContext)) {
4154 // This is implicit default initialization of a member or
4155 // base within a constructor. If no viable function was
4156 // found, notify the user that she needs to explicitly
4157 // initialize this base/member.
4158 CXXConstructorDecl *Constructor
4159 = cast<CXXConstructorDecl>(S.CurContext);
4160 if (Entity.getKind() == InitializedEntity::EK_Base) {
4161 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4162 << Constructor->isImplicit()
4163 << S.Context.getTypeDeclType(Constructor->getParent())
4164 << /*base=*/0
4165 << Entity.getType();
4166
4167 RecordDecl *BaseDecl
4168 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4169 ->getDecl();
4170 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4171 << S.Context.getTagDeclType(BaseDecl);
4172 } else {
4173 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4174 << Constructor->isImplicit()
4175 << S.Context.getTypeDeclType(Constructor->getParent())
4176 << /*member=*/1
4177 << Entity.getName();
4178 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4179
4180 if (const RecordType *Record
4181 = Entity.getType()->getAs<RecordType>())
4182 S.Diag(Record->getDecl()->getLocation(),
4183 diag::note_previous_decl)
4184 << S.Context.getTagDeclType(Record->getDecl());
4185 }
4186 break;
4187 }
4188
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004189 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4190 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00004191 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4192 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004193 break;
4194
4195 case OR_Deleted: {
4196 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4197 << true << DestType << ArgsRange;
4198 OverloadCandidateSet::iterator Best;
4199 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4200 Kind.getLocation(),
4201 Best);
4202 if (Ovl == OR_Deleted) {
4203 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4204 << Best->Function->isDeleted();
4205 } else {
4206 llvm_unreachable("Inconsistent overload resolution?");
4207 }
4208 break;
4209 }
4210
4211 case OR_Success:
4212 llvm_unreachable("Conversion did not fail!");
4213 break;
4214 }
4215 break;
4216 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004217
4218 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004219 if (Entity.getKind() == InitializedEntity::EK_Member &&
4220 isa<CXXConstructorDecl>(S.CurContext)) {
4221 // This is implicit default-initialization of a const member in
4222 // a constructor. Complain that it needs to be explicitly
4223 // initialized.
4224 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4225 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4226 << Constructor->isImplicit()
4227 << S.Context.getTypeDeclType(Constructor->getParent())
4228 << /*const=*/1
4229 << Entity.getName();
4230 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4231 << Entity.getName();
4232 } else {
4233 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4234 << DestType << (bool)DestType->getAs<RecordType>();
4235 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004236 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004237
4238 case FK_Incomplete:
4239 S.RequireCompleteType(Kind.getLocation(), DestType,
4240 diag::err_init_incomplete_type);
4241 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004242 }
4243
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004244 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004245 return true;
4246}
Douglas Gregore1314a62009-12-18 05:02:21 +00004247
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004248void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4249 switch (SequenceKind) {
4250 case FailedSequence: {
4251 OS << "Failed sequence: ";
4252 switch (Failure) {
4253 case FK_TooManyInitsForReference:
4254 OS << "too many initializers for reference";
4255 break;
4256
4257 case FK_ArrayNeedsInitList:
4258 OS << "array requires initializer list";
4259 break;
4260
4261 case FK_ArrayNeedsInitListOrStringLiteral:
4262 OS << "array requires initializer list or string literal";
4263 break;
4264
4265 case FK_AddressOfOverloadFailed:
4266 OS << "address of overloaded function failed";
4267 break;
4268
4269 case FK_ReferenceInitOverloadFailed:
4270 OS << "overload resolution for reference initialization failed";
4271 break;
4272
4273 case FK_NonConstLValueReferenceBindingToTemporary:
4274 OS << "non-const lvalue reference bound to temporary";
4275 break;
4276
4277 case FK_NonConstLValueReferenceBindingToUnrelated:
4278 OS << "non-const lvalue reference bound to unrelated type";
4279 break;
4280
4281 case FK_RValueReferenceBindingToLValue:
4282 OS << "rvalue reference bound to an lvalue";
4283 break;
4284
4285 case FK_ReferenceInitDropsQualifiers:
4286 OS << "reference initialization drops qualifiers";
4287 break;
4288
4289 case FK_ReferenceInitFailed:
4290 OS << "reference initialization failed";
4291 break;
4292
4293 case FK_ConversionFailed:
4294 OS << "conversion failed";
4295 break;
4296
4297 case FK_TooManyInitsForScalar:
4298 OS << "too many initializers for scalar";
4299 break;
4300
4301 case FK_ReferenceBindingToInitList:
4302 OS << "referencing binding to initializer list";
4303 break;
4304
4305 case FK_InitListBadDestinationType:
4306 OS << "initializer list for non-aggregate, non-scalar type";
4307 break;
4308
4309 case FK_UserConversionOverloadFailed:
4310 OS << "overloading failed for user-defined conversion";
4311 break;
4312
4313 case FK_ConstructorOverloadFailed:
4314 OS << "constructor overloading failed";
4315 break;
4316
4317 case FK_DefaultInitOfConst:
4318 OS << "default initialization of a const variable";
4319 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004320
4321 case FK_Incomplete:
4322 OS << "initialization of incomplete type";
4323 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004324 }
4325 OS << '\n';
4326 return;
4327 }
4328
4329 case DependentSequence:
4330 OS << "Dependent sequence: ";
4331 return;
4332
4333 case UserDefinedConversion:
4334 OS << "User-defined conversion sequence: ";
4335 break;
4336
4337 case ConstructorInitialization:
4338 OS << "Constructor initialization sequence: ";
4339 break;
4340
4341 case ReferenceBinding:
4342 OS << "Reference binding: ";
4343 break;
4344
4345 case ListInitialization:
4346 OS << "List initialization: ";
4347 break;
4348
4349 case ZeroInitialization:
4350 OS << "Zero initialization\n";
4351 return;
4352
4353 case NoInitialization:
4354 OS << "No initialization\n";
4355 return;
4356
4357 case StandardConversion:
4358 OS << "Standard conversion: ";
4359 break;
4360
4361 case CAssignment:
4362 OS << "C assignment: ";
4363 break;
4364
4365 case StringInit:
4366 OS << "String initialization: ";
4367 break;
4368 }
4369
4370 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4371 if (S != step_begin()) {
4372 OS << " -> ";
4373 }
4374
4375 switch (S->Kind) {
4376 case SK_ResolveAddressOfOverloadedFunction:
4377 OS << "resolve address of overloaded function";
4378 break;
4379
4380 case SK_CastDerivedToBaseRValue:
4381 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4382 break;
4383
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004384 case SK_CastDerivedToBaseXValue:
4385 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4386 break;
4387
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004388 case SK_CastDerivedToBaseLValue:
4389 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4390 break;
4391
4392 case SK_BindReference:
4393 OS << "bind reference to lvalue";
4394 break;
4395
4396 case SK_BindReferenceToTemporary:
4397 OS << "bind reference to a temporary";
4398 break;
4399
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004400 case SK_ExtraneousCopyToTemporary:
4401 OS << "extraneous C++03 copy to temporary";
4402 break;
4403
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004404 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004405 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004406 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004407
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004408 case SK_QualificationConversionRValue:
4409 OS << "qualification conversion (rvalue)";
4410
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004411 case SK_QualificationConversionXValue:
4412 OS << "qualification conversion (xvalue)";
4413
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004414 case SK_QualificationConversionLValue:
4415 OS << "qualification conversion (lvalue)";
4416 break;
4417
4418 case SK_ConversionSequence:
4419 OS << "implicit conversion sequence (";
4420 S->ICS->DebugPrint(); // FIXME: use OS
4421 OS << ")";
4422 break;
4423
4424 case SK_ListInitialization:
4425 OS << "list initialization";
4426 break;
4427
4428 case SK_ConstructorInitialization:
4429 OS << "constructor initialization";
4430 break;
4431
4432 case SK_ZeroInitialization:
4433 OS << "zero initialization";
4434 break;
4435
4436 case SK_CAssignment:
4437 OS << "C assignment";
4438 break;
4439
4440 case SK_StringInit:
4441 OS << "string initialization";
4442 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004443
4444 case SK_ObjCObjectConversion:
4445 OS << "Objective-C object conversion";
4446 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004447 }
4448 }
4449}
4450
4451void InitializationSequence::dump() const {
4452 dump(llvm::errs());
4453}
4454
Douglas Gregore1314a62009-12-18 05:02:21 +00004455//===----------------------------------------------------------------------===//
4456// Initialization helper functions
4457//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004458ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004459Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4460 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004461 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004462 if (Init.isInvalid())
4463 return ExprError();
4464
4465 Expr *InitE = (Expr *)Init.get();
4466 assert(InitE && "No initialization expression?");
4467
4468 if (EqualLoc.isInvalid())
4469 EqualLoc = InitE->getLocStart();
4470
4471 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4472 EqualLoc);
4473 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4474 Init.release();
John McCall37ad5512010-08-23 06:44:23 +00004475 return Seq.Perform(*this, Entity, Kind, MultiExprArg(*this, &InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004476}