blob: 7a2db6337604bcbaaf318937f0a0a351b9fbf88b [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"
John McCall83024632010-08-25 22:03:47 +000021#include "clang/Sema/SemaInternal.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
John McCallfaf5fb42010-08-26 23:41:50 +0000268 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000269 if (MemberInit.isInvalid()) {
270 hadError = true;
271 return;
272 }
273
274 if (hadError) {
275 // Do nothing
276 } else if (Init < NumInits) {
277 ILE->setInit(Init, MemberInit.takeAs<Expr>());
278 } else if (InitSeq.getKind()
279 == InitializationSequence::ConstructorInitialization) {
280 // Value-initialization requires a constructor call, so
281 // extend the initializer list to include the constructor
282 // call and make a note that we'll need to take another pass
283 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000284 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000285 RequiresSecondPass = true;
286 }
287 } else if (InitListExpr *InnerILE
288 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289 FillInValueInitializations(MemberEntity, InnerILE,
290 RequiresSecondPass);
291}
292
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000307 if (RType->getDecl()->isUnion() &&
308 ILE->getInitializedFieldInUnion())
309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310 Entity, ILE, RequiresSecondPass);
311 else {
312 unsigned Init = 0;
313 for (RecordDecl::field_iterator
314 Field = RType->getDecl()->field_begin(),
315 FieldEnd = RType->getDecl()->field_end();
316 Field != FieldEnd; ++Field) {
317 if (Field->isUnnamedBitfield())
318 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000319
Douglas Gregor2bb07652009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000321 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000326
Douglas Gregor2bb07652009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000328
Douglas Gregor2bb07652009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump11289f42009-09-09 15:08:12 +0000336 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000339
Douglas Gregor723796a2009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000354 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor723796a2009-12-16 06:35:08 +0000357
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368 true);
369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370 if (!InitSeq) {
371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
John McCalldadc5752010-08-24 06:29:42 +0000376 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000377 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000378 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000379 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000380 return;
381 }
382
383 if (hadError) {
384 // Do nothing
385 } else if (Init < NumInits) {
386 ILE->setInit(Init, ElementInit.takeAs<Expr>());
387 } else if (InitSeq.getKind()
388 == InitializationSequence::ConstructorInitialization) {
389 // Value-initialization requires a constructor call, so
390 // extend the initializer list to include the constructor
391 // call and make a note that we'll need to take another pass
392 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000393 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000394 RequiresSecondPass = true;
395 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000396 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
398 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 }
400}
401
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000402
Douglas Gregor723796a2009-12-16 06:35:08 +0000403InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
404 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000405 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000406 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000407
Eli Friedman23a9e312008-05-19 19:16:24 +0000408 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000409 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000410 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000411 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000412 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000413 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000414 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000415
Douglas Gregor723796a2009-12-16 06:35:08 +0000416 if (!hadError) {
417 bool RequiresSecondPass = false;
418 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000419 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 FillInValueInitializations(Entity, FullyStructuredList,
421 RequiresSecondPass);
422 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000423}
424
425int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000426 // FIXME: use a proper constant
427 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000428 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000429 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000430 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
431 }
432 return maxElements;
433}
434
435int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000436 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000437 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000438 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000439 Field = structDecl->field_begin(),
440 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000441 Field != FieldEnd; ++Field) {
442 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
443 ++InitializableMembers;
444 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000445 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000446 return std::min(InitializableMembers, 1);
447 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000448}
449
Anders Carlsson6cabf312010-01-23 23:23:01 +0000450void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000451 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000452 QualType T, unsigned &Index,
453 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000454 unsigned &StructuredIndex,
455 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000456 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Steve Narofff8ecff22008-05-01 22:18:59 +0000458 if (T->isArrayType())
459 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000460 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000461 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000462 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000463 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000464 else
465 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000466
Eli Friedmane0f832b2008-05-25 13:49:22 +0000467 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000468 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000469 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000470 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000471 hadError = true;
472 return;
473 }
474
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000475 // Build a structured initializer list corresponding to this subobject.
476 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000477 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
478 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000479 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
480 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000481 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000482
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000483 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000484 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000485 CheckListElementTypes(Entity, ParentIList, T,
486 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000487 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000488 StructuredSubobjectInitIndex,
489 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000490 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000491 StructuredSubobjectInitList->setType(T);
492
Douglas Gregor5741efb2009-03-01 17:12:46 +0000493 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000494 // range corresponds with the end of the last initializer it used.
495 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000496 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000497 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
498 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
499 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000500
501 // Warn about missing braces.
502 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000503 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
504 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000505 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000506 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
507 "{")
508 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner5cb196e2010-03-07 04:47:12 +0000509 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000510 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000511 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000512}
513
Anders Carlsson6cabf312010-01-23 23:23:01 +0000514void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000515 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000516 unsigned &Index,
517 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000518 unsigned &StructuredIndex,
519 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000520 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000521 SyntacticToSemantic[IList] = StructuredList;
522 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000523 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
524 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000525 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
526 IList->setType(ExprTy);
527 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000528 if (hadError)
529 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000530
Eli Friedman85f54972008-05-25 13:22:35 +0000531 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000532 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000533 if (StructuredIndex == 1 &&
534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000536 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000537 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000538 hadError = true;
539 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000540 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000542 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000543 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000544 // Don't complain for incomplete types, since we'll get an error
545 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000546 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000547 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000548 CurrentObjectType->isArrayType()? 0 :
549 CurrentObjectType->isVectorType()? 1 :
550 CurrentObjectType->isScalarType()? 2 :
551 CurrentObjectType->isUnionType()? 3 :
552 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000553
554 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Nate Begeman425038c2009-07-07 21:53:06 +0000559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000563
Chris Lattnerb0912a52009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000565 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000566 }
567 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000568
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000569 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000571 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000572 << FixItHint::CreateRemoval(IList->getLocStart())
573 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000574}
575
Anders Carlsson6cabf312010-01-23 23:23:01 +0000576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000577 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000578 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000579 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000580 unsigned &Index,
581 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000582 unsigned &StructuredIndex,
583 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000584 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000585 CheckScalarType(Entity, IList, DeclType, Index,
586 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000587 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000588 CheckVectorType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000590 } else if (DeclType->isAggregateType()) {
591 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000592 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000593 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000594 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 StructuredList, StructuredIndex,
596 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000597 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000598 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000599 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000600 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000601 CheckArrayType(Entity, IList, DeclType, Zero,
602 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000603 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000604 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000605 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000608 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000610 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000611 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000612 } else if (DeclType->isRecordType()) {
613 // C++ [dcl.init]p14:
614 // [...] If the class is an aggregate (8.5.1), and the initializer
615 // is a brace-enclosed list, see 8.5.1.
616 //
617 // Note: 8.5.1 is handled below; here, we diagnose the case where
618 // we have an initializer list and a destination type that is not
619 // an aggregate.
620 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000622 << DeclType << IList->getSourceRange();
623 hadError = true;
624 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000625 CheckReferenceType(Entity, IList, DeclType, Index,
626 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000627 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000628 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
629 << DeclType;
630 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000631 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000632 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
633 << DeclType;
634 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000635 }
636}
637
Anders Carlsson6cabf312010-01-23 23:23:01 +0000638void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000639 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000640 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000641 unsigned &Index,
642 InitListExpr *StructuredList,
643 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000644 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000645 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
646 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000647 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000648 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 = getStructuredSubobjectInit(IList, Index, ElemType,
650 StructuredList, StructuredIndex,
651 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000652 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000653 newStructuredList, newStructuredIndex);
654 ++StructuredIndex;
655 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000656 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
657 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000658 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000659 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000660 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000661 CheckScalarType(Entity, IList, ElemType, Index,
662 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000663 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000664 CheckReferenceType(Entity, IList, ElemType, Index,
665 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000666 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000667 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000668 // C++ [dcl.init.aggr]p12:
669 // All implicit type conversions (clause 4) are considered when
670 // initializing the aggregate member with an ini- tializer from
671 // an initializer-list. If the initializer can initialize a
672 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000673
Anders Carlsson0bd52402010-01-24 00:19:41 +0000674 // FIXME: Better EqualLoc?
675 InitializationKind Kind =
676 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
677 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
678
679 if (Seq) {
John McCalldadc5752010-08-24 06:29:42 +0000680 ExprResult Result =
John McCallfaf5fb42010-08-26 23:41:50 +0000681 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
Anders Carlsson0bd52402010-01-24 00:19:41 +0000682 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000683 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000684
685 UpdateStructuredListElement(StructuredList, StructuredIndex,
686 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000687 ++Index;
688 return;
689 }
690
691 // Fall through for subaggregate initialization
692 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000693 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000694 //
695 // The initializer for a structure or union object that has
696 // automatic storage duration shall be either an initializer
697 // list as described below, or a single expression that has
698 // compatible structure or union type. In the latter case, the
699 // initial value of the object, including unnamed members, is
700 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000701 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000702 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000703 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
704 ++Index;
705 return;
706 }
707
708 // Fall through for subaggregate initialization
709 }
710
711 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000712 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000713 // [...] Otherwise, if the member is itself a non-empty
714 // subaggregate, brace elision is assumed and the initializer is
715 // considered for the initialization of the first member of
716 // the subaggregate.
717 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000718 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000719 StructuredIndex);
720 ++StructuredIndex;
721 } else {
722 // We cannot initialize this element, so let
723 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssona18f0fb2010-01-30 01:56:32 +0000724 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
725 SemaRef.Owned(expr));
Douglas Gregord14247a2009-01-30 22:09:00 +0000726 hadError = true;
727 ++Index;
728 ++StructuredIndex;
729 }
730 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000731}
732
Anders Carlsson6cabf312010-01-23 23:23:01 +0000733void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000734 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000735 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000736 InitListExpr *StructuredList,
737 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000738 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000739 Expr *expr = IList->getInit(Index);
Eli Friedmandf239252010-08-14 03:14:53 +0000740 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
741 SemaRef.Diag(SubIList->getLocStart(),
742 diag::warn_many_braces_around_scalar_init)
743 << SubIList->getSourceRange();
744
745 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
746 StructuredIndex);
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000747 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000748 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000749 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000750 diag::err_designator_for_scalar_init)
751 << DeclType << expr->getSourceRange();
752 hadError = true;
753 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000754 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000755 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000756 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000757
John McCalldadc5752010-08-24 06:29:42 +0000758 ExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000759 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
760 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000761
Chandler Carruthdfe198b2010-02-13 07:23:01 +0000762 Expr *ResultExpr = 0;
Anders Carlsson26d05642010-01-23 18:35:41 +0000763
764 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000765 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000766 else {
767 ResultExpr = Result.takeAs<Expr>();
768
769 if (ResultExpr != expr) {
770 // The type was promoted, update initializer list.
771 IList->setInit(Index, ResultExpr);
772 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000773 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000774 if (hadError)
775 ++StructuredIndex;
776 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000777 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000778 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000779 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000780 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000781 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000782 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000783 ++Index;
784 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000785 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000786 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000787}
788
Anders Carlsson6cabf312010-01-23 23:23:01 +0000789void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
790 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000791 unsigned &Index,
792 InitListExpr *StructuredList,
793 unsigned &StructuredIndex) {
794 if (Index < IList->getNumInits()) {
795 Expr *expr = IList->getInit(Index);
796 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000797 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000798 << DeclType << IList->getSourceRange();
799 hadError = true;
800 ++Index;
801 ++StructuredIndex;
802 return;
Mike Stump11289f42009-09-09 15:08:12 +0000803 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000804
John McCalldadc5752010-08-24 06:29:42 +0000805 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000806 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
807 SemaRef.Owned(expr));
808
809 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000810 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000811
812 expr = Result.takeAs<Expr>();
813 IList->setInit(Index, expr);
814
Douglas Gregord14247a2009-01-30 22:09:00 +0000815 if (hadError)
816 ++StructuredIndex;
817 else
818 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
819 ++Index;
820 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000821 // FIXME: It would be wonderful if we could point at the actual member. In
822 // general, it would be useful to pass location information down the stack,
823 // so that we know the location (or decl) of the "current object" being
824 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000825 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000826 diag::err_init_reference_member_uninitialized)
827 << DeclType
828 << IList->getSourceRange();
829 hadError = true;
830 ++Index;
831 ++StructuredIndex;
832 return;
833 }
834}
835
Anders Carlsson6cabf312010-01-23 23:23:01 +0000836void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000837 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000838 unsigned &Index,
839 InitListExpr *StructuredList,
840 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000841 if (Index >= IList->getNumInits())
842 return;
Mike Stump11289f42009-09-09 15:08:12 +0000843
John McCall6a16b2f2010-10-30 00:11:39 +0000844 const VectorType *VT = DeclType->getAs<VectorType>();
845 unsigned maxElements = VT->getNumElements();
846 unsigned numEltsInit = 0;
847 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000848
John McCall6a16b2f2010-10-30 00:11:39 +0000849 if (!SemaRef.getLangOptions().OpenCL) {
850 // If the initializing element is a vector, try to copy-initialize
851 // instead of breaking it apart (which is doomed to failure anyway).
852 Expr *Init = IList->getInit(Index);
853 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
854 ExprResult Result =
855 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
856 SemaRef.Owned(Init));
857
858 Expr *ResultExpr = 0;
859 if (Result.isInvalid())
860 hadError = true; // types weren't compatible.
861 else {
862 ResultExpr = Result.takeAs<Expr>();
Anders Carlsson6cabf312010-01-23 23:23:01 +0000863
John McCall6a16b2f2010-10-30 00:11:39 +0000864 if (ResultExpr != Init) {
865 // The type was promoted, update initializer list.
866 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000867 }
868 }
John McCall6a16b2f2010-10-30 00:11:39 +0000869 if (hadError)
870 ++StructuredIndex;
871 else
872 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
873 ++Index;
874 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000875 }
Mike Stump11289f42009-09-09 15:08:12 +0000876
John McCall6a16b2f2010-10-30 00:11:39 +0000877 InitializedEntity ElementEntity =
878 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
879
880 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
881 // Don't attempt to go past the end of the init list
882 if (Index >= IList->getNumInits())
883 break;
884
885 ElementEntity.setElementIndex(Index);
886 CheckSubElementType(ElementEntity, IList, elementType, Index,
887 StructuredList, StructuredIndex);
888 }
889 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000890 }
John McCall6a16b2f2010-10-30 00:11:39 +0000891
892 InitializedEntity ElementEntity =
893 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
894
895 // OpenCL initializers allows vectors to be constructed from vectors.
896 for (unsigned i = 0; i < maxElements; ++i) {
897 // Don't attempt to go past the end of the init list
898 if (Index >= IList->getNumInits())
899 break;
900
901 ElementEntity.setElementIndex(Index);
902
903 QualType IType = IList->getInit(Index)->getType();
904 if (!IType->isVectorType()) {
905 CheckSubElementType(ElementEntity, IList, elementType, Index,
906 StructuredList, StructuredIndex);
907 ++numEltsInit;
908 } else {
909 QualType VecType;
910 const VectorType *IVT = IType->getAs<VectorType>();
911 unsigned numIElts = IVT->getNumElements();
912
913 if (IType->isExtVectorType())
914 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
915 else
916 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000917 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000918 CheckSubElementType(ElementEntity, IList, VecType, Index,
919 StructuredList, StructuredIndex);
920 numEltsInit += numIElts;
921 }
922 }
923
924 // OpenCL requires all elements to be initialized.
925 if (numEltsInit != maxElements)
926 if (SemaRef.getLangOptions().OpenCL)
927 SemaRef.Diag(IList->getSourceRange().getBegin(),
928 diag::err_vector_incorrect_num_initializers)
929 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000930}
931
Anders Carlsson6cabf312010-01-23 23:23:01 +0000932void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000933 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000934 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000935 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000936 unsigned &Index,
937 InitListExpr *StructuredList,
938 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000939 // Check for the special-case of initializing an array with a string.
940 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000941 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
942 SemaRef.Context)) {
943 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000944 // We place the string literal directly into the resulting
945 // initializer list. This is the only place where the structure
946 // of the structured initializer list doesn't match exactly,
947 // because doing so would involve allocating one character
948 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000949 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000950 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000951 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000952 return;
953 }
954 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000955 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000956 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000957 // Check for VLAs; in standard C it would be possible to check this
958 // earlier, but I don't know where clang accepts VLAs (gcc accepts
959 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000960 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000961 diag::err_variable_object_no_init)
962 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000963 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000964 ++Index;
965 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000966 return;
967 }
968
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000969 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000970 llvm::APSInt maxElements(elementIndex.getBitWidth(),
971 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000972 bool maxElementsKnown = false;
973 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000974 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000975 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000976 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000977 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000978 maxElementsKnown = true;
979 }
980
Chris Lattnerb0912a52009-02-24 22:50:46 +0000981 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000982 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000983 while (Index < IList->getNumInits()) {
984 Expr *Init = IList->getInit(Index);
985 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000986 // If we're not the subobject that matches up with the '{' for
987 // the designator, we shouldn't be handling the
988 // designator. Return immediately.
989 if (!SubobjectIsDesignatorContext)
990 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000991
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000992 // Handle this designated initializer. elementIndex will be
993 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000994 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000995 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000996 StructuredList, StructuredIndex, true,
997 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000998 hadError = true;
999 continue;
1000 }
1001
Douglas Gregor033d1252009-01-23 16:54:12 +00001002 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1003 maxElements.extend(elementIndex.getBitWidth());
1004 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1005 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001006 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001007
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001008 // If the array is of incomplete type, keep track of the number of
1009 // elements in the initializer.
1010 if (!maxElementsKnown && elementIndex > maxElements)
1011 maxElements = elementIndex;
1012
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001013 continue;
1014 }
1015
1016 // If we know the maximum number of elements, and we've already
1017 // hit it, stop consuming elements in the initializer list.
1018 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001019 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001020
Anders Carlsson6cabf312010-01-23 23:23:01 +00001021 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001022 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001023 Entity);
1024 // Check this element.
1025 CheckSubElementType(ElementEntity, IList, elementType, Index,
1026 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001027 ++elementIndex;
1028
1029 // If the array is of incomplete type, keep track of the number of
1030 // elements in the initializer.
1031 if (!maxElementsKnown && elementIndex > maxElements)
1032 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001033 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001034 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001035 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001036 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001037 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001038 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001039 // Sizing an array implicitly to zero is not allowed by ISO C,
1040 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001041 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001042 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001043 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001044
Mike Stump11289f42009-09-09 15:08:12 +00001045 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001046 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001047 }
1048}
1049
Anders Carlsson6cabf312010-01-23 23:23:01 +00001050void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001051 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001052 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001053 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001054 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001055 unsigned &Index,
1056 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001057 unsigned &StructuredIndex,
1058 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001059 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001060
Eli Friedman23a9e312008-05-19 19:16:24 +00001061 // If the record is invalid, some of it's members are invalid. To avoid
1062 // confusion, we forgo checking the intializer for the entire record.
1063 if (structDecl->isInvalidDecl()) {
1064 hadError = true;
1065 return;
Mike Stump11289f42009-09-09 15:08:12 +00001066 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001067
1068 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1069 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001070 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001071 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001072 Field != FieldEnd; ++Field) {
1073 if (Field->getDeclName()) {
1074 StructuredList->setInitializedFieldInUnion(*Field);
1075 break;
1076 }
1077 }
1078 return;
1079 }
1080
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001081 // If structDecl is a forward declaration, this loop won't do
1082 // anything except look at designated initializers; That's okay,
1083 // because an error should get printed out elsewhere. It might be
1084 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001085 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001086 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001087 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001088 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001089 while (Index < IList->getNumInits()) {
1090 Expr *Init = IList->getInit(Index);
1091
1092 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001093 // If we're not the subobject that matches up with the '{' for
1094 // the designator, we shouldn't be handling the
1095 // designator. Return immediately.
1096 if (!SubobjectIsDesignatorContext)
1097 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001098
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001099 // Handle this designated initializer. Field will be updated to
1100 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001101 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001102 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001103 StructuredList, StructuredIndex,
1104 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001105 hadError = true;
1106
Douglas Gregora9add4e2009-02-12 19:00:39 +00001107 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001108
1109 // Disable check for missing fields when designators are used.
1110 // This matches gcc behaviour.
1111 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001112 continue;
1113 }
1114
1115 if (Field == FieldEnd) {
1116 // We've run out of fields. We're done.
1117 break;
1118 }
1119
Douglas Gregora9add4e2009-02-12 19:00:39 +00001120 // We've already initialized a member of a union. We're done.
1121 if (InitializedSomething && DeclType->isUnionType())
1122 break;
1123
Douglas Gregor91f84212008-12-11 16:49:14 +00001124 // If we've hit the flexible array member at the end, we're done.
1125 if (Field->getType()->isIncompleteArrayType())
1126 break;
1127
Douglas Gregor51695702009-01-29 16:53:55 +00001128 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001129 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001130 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001131 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001132 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001133
Anders Carlsson6cabf312010-01-23 23:23:01 +00001134 InitializedEntity MemberEntity =
1135 InitializedEntity::InitializeMember(*Field, &Entity);
1136 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1137 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001138 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001139
1140 if (DeclType->isUnionType()) {
1141 // Initialize the first field within the union.
1142 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001143 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001144
1145 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001146 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001147
John McCalle40b58e2010-03-11 19:32:38 +00001148 // Emit warnings for missing struct field initializers.
Douglas Gregor8fba4f22010-06-18 21:43:10 +00001149 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001150 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1151 // It is possible we have one or more unnamed bitfields remaining.
1152 // Find first (if any) named field and emit warning.
1153 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1154 it != end; ++it) {
1155 if (!it->isUnnamedBitfield()) {
1156 SemaRef.Diag(IList->getSourceRange().getEnd(),
1157 diag::warn_missing_field_initializers) << it->getName();
1158 break;
1159 }
1160 }
1161 }
1162
Mike Stump11289f42009-09-09 15:08:12 +00001163 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001164 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001165 return;
1166
1167 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001168 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001169 (!isa<InitListExpr>(IList->getInit(Index)) ||
1170 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001171 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001172 diag::err_flexible_array_init_nonempty)
1173 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001174 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001175 << *Field;
1176 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001177 ++Index;
1178 return;
1179 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001180 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001181 diag::ext_flexible_array_init)
1182 << IList->getInit(Index)->getSourceRange().getBegin();
1183 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1184 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001185 }
1186
Anders Carlsson6cabf312010-01-23 23:23:01 +00001187 InitializedEntity MemberEntity =
1188 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001189
Anders Carlsson6cabf312010-01-23 23:23:01 +00001190 if (isa<InitListExpr>(IList->getInit(Index)))
1191 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1192 StructuredList, StructuredIndex);
1193 else
1194 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001195 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001196}
Steve Narofff8ecff22008-05-01 22:18:59 +00001197
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001198/// \brief Similar to Sema::BuildAnonymousStructUnionMemberPath() but builds a
1199/// relative path and has strict checks.
1200static void BuildRelativeAnonymousStructUnionMemberPath(FieldDecl *Field,
1201 llvm::SmallVectorImpl<FieldDecl *> &Path,
1202 DeclContext *BaseDC) {
1203 Path.push_back(Field);
1204 for (DeclContext *Ctx = Field->getDeclContext();
1205 !Ctx->Equals(BaseDC);
1206 Ctx = Ctx->getParent()) {
1207 ValueDecl *AnonObject =
1208 cast<RecordDecl>(Ctx)->getAnonymousStructOrUnionObject();
1209 FieldDecl *AnonField = cast<FieldDecl>(AnonObject);
1210 Path.push_back(AnonField);
1211 }
1212}
1213
Douglas Gregord5846a12009-04-15 06:41:24 +00001214/// \brief Expand a field designator that refers to a member of an
1215/// anonymous struct or union into a series of field designators that
1216/// refers to the field within the appropriate subobject.
1217///
1218/// Field/FieldIndex will be updated to point to the (new)
1219/// currently-designated field.
1220static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001221 DesignatedInitExpr *DIE,
1222 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001223 FieldDecl *Field,
1224 RecordDecl::field_iterator &FieldIter,
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001225 unsigned &FieldIndex,
1226 DeclContext *BaseDC) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001227 typedef DesignatedInitExpr::Designator Designator;
1228
1229 // Build the path from the current object to the member of the
1230 // anonymous struct/union (backwards).
1231 llvm::SmallVector<FieldDecl *, 4> Path;
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001232 BuildRelativeAnonymousStructUnionMemberPath(Field, Path, BaseDC);
Mike Stump11289f42009-09-09 15:08:12 +00001233
Douglas Gregord5846a12009-04-15 06:41:24 +00001234 // Build the replacement designators.
1235 llvm::SmallVector<Designator, 4> Replacements;
1236 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1237 FI = Path.rbegin(), FIEnd = Path.rend();
1238 FI != FIEnd; ++FI) {
1239 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001240 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001241 DIE->getDesignator(DesigIdx)->getDotLoc(),
1242 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1243 else
1244 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1245 SourceLocation()));
1246 Replacements.back().setField(*FI);
1247 }
1248
1249 // Expand the current designator into the set of replacement
1250 // designators, so we have a full subobject path down to where the
1251 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001252 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001253 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001254
Douglas Gregord5846a12009-04-15 06:41:24 +00001255 // Update FieldIter/FieldIndex;
1256 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001257 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001258 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001259 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001260 FieldIter != FEnd; ++FieldIter) {
1261 if (FieldIter->isUnnamedBitfield())
1262 continue;
1263
1264 if (*FieldIter == Path.back())
1265 return;
1266
1267 ++FieldIndex;
1268 }
1269
1270 assert(false && "Unable to find anonymous struct/union field");
1271}
1272
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001273/// @brief Check the well-formedness of a C99 designated initializer.
1274///
1275/// Determines whether the designated initializer @p DIE, which
1276/// resides at the given @p Index within the initializer list @p
1277/// IList, is well-formed for a current object of type @p DeclType
1278/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001279/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001280/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001281///
1282/// @param IList The initializer list in which this designated
1283/// initializer occurs.
1284///
Douglas Gregora5324162009-04-15 04:56:10 +00001285/// @param DIE The designated initializer expression.
1286///
1287/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001288///
1289/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1290/// into which the designation in @p DIE should refer.
1291///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001292/// @param NextField If non-NULL and the first designator in @p DIE is
1293/// a field, this will be set to the field declaration corresponding
1294/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001295///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001296/// @param NextElementIndex If non-NULL and the first designator in @p
1297/// DIE is an array designator or GNU array-range designator, this
1298/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001299///
1300/// @param Index Index into @p IList where the designated initializer
1301/// @p DIE occurs.
1302///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001303/// @param StructuredList The initializer list expression that
1304/// describes all of the subobject initializers in the order they'll
1305/// actually be initialized.
1306///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001307/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001308bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001309InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001310 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001311 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001312 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001313 QualType &CurrentObjectType,
1314 RecordDecl::field_iterator *NextField,
1315 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001316 unsigned &Index,
1317 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001318 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001319 bool FinishSubobjectInit,
1320 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001321 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001322 // Check the actual initialization for the designated object type.
1323 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001324
1325 // Temporarily remove the designator expression from the
1326 // initializer list that the child calls see, so that we don't try
1327 // to re-process the designator.
1328 unsigned OldIndex = Index;
1329 IList->setInit(OldIndex, DIE->getInit());
1330
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001331 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001332 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001333
1334 // Restore the designated initializer expression in the syntactic
1335 // form of the initializer list.
1336 if (IList->getInit(OldIndex) != DIE->getInit())
1337 DIE->setInit(IList->getInit(OldIndex));
1338 IList->setInit(OldIndex, DIE);
1339
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001340 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001341 }
1342
Douglas Gregora5324162009-04-15 04:56:10 +00001343 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001344 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001345 "Need a non-designated initializer list to start from");
1346
Douglas Gregora5324162009-04-15 04:56:10 +00001347 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001348 // Determine the structural initializer list that corresponds to the
1349 // current subobject.
1350 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001351 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001352 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001353 SourceRange(D->getStartLocation(),
1354 DIE->getSourceRange().getEnd()));
1355 assert(StructuredList && "Expected a structured initializer list");
1356
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001357 if (D->isFieldDesignator()) {
1358 // C99 6.7.8p7:
1359 //
1360 // If a designator has the form
1361 //
1362 // . identifier
1363 //
1364 // then the current object (defined below) shall have
1365 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001366 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001367 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001368 if (!RT) {
1369 SourceLocation Loc = D->getDotLoc();
1370 if (Loc.isInvalid())
1371 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001372 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1373 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001374 ++Index;
1375 return true;
1376 }
1377
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001378 // Note: we perform a linear search of the fields here, despite
1379 // the fact that we have a faster lookup method, because we always
1380 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001381 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001382 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001383 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001384 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001385 Field = RT->getDecl()->field_begin(),
1386 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001387 for (; Field != FieldEnd; ++Field) {
1388 if (Field->isUnnamedBitfield())
1389 continue;
1390
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001391 if (KnownField && KnownField == *Field)
1392 break;
1393 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 break;
1395
1396 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001397 }
1398
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001399 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001400 // There was no normal field in the struct with the designated
1401 // name. Perform another lookup for this name, which may find
1402 // something that we can't designate (e.g., a member function),
1403 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001404 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001405 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001406 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001407 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001408 // Name lookup didn't find anything. Determine whether this
1409 // was a typo for another field name.
1410 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1411 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001412 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1413 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001414 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001415 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001416 ->Equals(RT->getDecl())) {
1417 SemaRef.Diag(D->getFieldLoc(),
1418 diag::err_field_designator_unknown_suggest)
1419 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001420 << FixItHint::CreateReplacement(D->getFieldLoc(),
1421 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001422 SemaRef.Diag(ReplacementField->getLocation(),
1423 diag::note_previous_decl)
1424 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001425 } else {
1426 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1427 << FieldName << CurrentObjectType;
1428 ++Index;
1429 return true;
1430 }
1431 } else if (!KnownField) {
1432 // Determine whether we found a field at all.
1433 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1434 }
1435
1436 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001437 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001438 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001439 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001440 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001441 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001442 ++Index;
1443 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001444 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001445
1446 if (!KnownField &&
1447 cast<RecordDecl>((ReplacementField)->getDeclContext())
1448 ->isAnonymousStructOrUnion()) {
1449 // Handle an field designator that refers to a member of an
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001450 // anonymous struct or union. This is a C1X feature.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001451 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1452 ReplacementField,
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001453 Field, FieldIndex, RT->getDecl());
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001454 D = DIE->getDesignator(DesigIdx);
1455 } else if (!KnownField) {
1456 // The replacement field comes from typo correction; find it
1457 // in the list of fields.
1458 FieldIndex = 0;
1459 Field = RT->getDecl()->field_begin();
1460 for (; Field != FieldEnd; ++Field) {
1461 if (Field->isUnnamedBitfield())
1462 continue;
1463
1464 if (ReplacementField == *Field ||
1465 Field->getIdentifier() == ReplacementField->getIdentifier())
1466 break;
1467
1468 ++FieldIndex;
1469 }
1470 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001471 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001472
1473 // All of the fields of a union are located at the same place in
1474 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001475 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001476 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001477 StructuredList->setInitializedFieldInUnion(*Field);
1478 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001479
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001480 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001481 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001482
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001483 // Make sure that our non-designated initializer list has space
1484 // for a subobject corresponding to this field.
1485 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001486 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001487
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001488 // This designator names a flexible array member.
1489 if (Field->getType()->isIncompleteArrayType()) {
1490 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001491 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001492 // We can't designate an object within the flexible array
1493 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001494 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001495 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001496 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001497 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001498 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001499 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001500 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001501 << *Field;
1502 Invalid = true;
1503 }
1504
Chris Lattner001b29c2010-10-10 17:49:49 +00001505 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1506 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001507 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001508 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001509 diag::err_flexible_array_init_needs_braces)
1510 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001511 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001512 << *Field;
1513 Invalid = true;
1514 }
1515
1516 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001517 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001518 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001519 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001520 diag::err_flexible_array_init_nonempty)
1521 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001522 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001523 << *Field;
1524 Invalid = true;
1525 }
1526
1527 if (Invalid) {
1528 ++Index;
1529 return true;
1530 }
1531
1532 // Initialize the array.
1533 bool prevHadError = hadError;
1534 unsigned newStructuredIndex = FieldIndex;
1535 unsigned OldIndex = Index;
1536 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001537
1538 InitializedEntity MemberEntity =
1539 InitializedEntity::InitializeMember(*Field, &Entity);
1540 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001541 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001542
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001543 IList->setInit(OldIndex, DIE);
1544 if (hadError && !prevHadError) {
1545 ++Field;
1546 ++FieldIndex;
1547 if (NextField)
1548 *NextField = Field;
1549 StructuredIndex = FieldIndex;
1550 return true;
1551 }
1552 } else {
1553 // Recurse to check later designated subobjects.
1554 QualType FieldType = (*Field)->getType();
1555 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001556
1557 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001558 InitializedEntity::InitializeMember(*Field, &Entity);
1559 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001560 FieldType, 0, 0, Index,
1561 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001562 true, false))
1563 return true;
1564 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001565
1566 // Find the position of the next field to be initialized in this
1567 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001568 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001569 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001570
1571 // If this the first designator, our caller will continue checking
1572 // the rest of this struct/class/union subobject.
1573 if (IsFirstDesignator) {
1574 if (NextField)
1575 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001576 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001577 return false;
1578 }
1579
Douglas Gregor17bd0942009-01-28 23:36:17 +00001580 if (!FinishSubobjectInit)
1581 return false;
1582
Douglas Gregord5846a12009-04-15 06:41:24 +00001583 // We've already initialized something in the union; we're done.
1584 if (RT->getDecl()->isUnion())
1585 return hadError;
1586
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001587 // Check the remaining fields within this class/struct/union subobject.
1588 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001589
Anders Carlsson6cabf312010-01-23 23:23:01 +00001590 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001591 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001592 return hadError && !prevHadError;
1593 }
1594
1595 // C99 6.7.8p6:
1596 //
1597 // If a designator has the form
1598 //
1599 // [ constant-expression ]
1600 //
1601 // then the current object (defined below) shall have array
1602 // type and the expression shall be an integer constant
1603 // expression. If the array is of unknown size, any
1604 // nonnegative value is valid.
1605 //
1606 // Additionally, cope with the GNU extension that permits
1607 // designators of the form
1608 //
1609 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001610 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001611 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001612 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001613 << CurrentObjectType;
1614 ++Index;
1615 return true;
1616 }
1617
1618 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001619 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1620 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001621 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001622 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001623 DesignatedEndIndex = DesignatedStartIndex;
1624 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001625 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001626
Mike Stump11289f42009-09-09 15:08:12 +00001627
1628 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001629 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001630 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001631 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001632 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001633
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001634 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001635 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001636 }
1637
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001638 if (isa<ConstantArrayType>(AT)) {
1639 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001640 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1641 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1642 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1643 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1644 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001645 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001646 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001647 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001648 << IndexExpr->getSourceRange();
1649 ++Index;
1650 return true;
1651 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001652 } else {
1653 // Make sure the bit-widths and signedness match.
1654 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1655 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001656 else if (DesignatedStartIndex.getBitWidth() <
1657 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001658 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1659 DesignatedStartIndex.setIsUnsigned(true);
1660 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001661 }
Mike Stump11289f42009-09-09 15:08:12 +00001662
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 // Make sure that our non-designated initializer list has space
1664 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001665 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001666 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001667 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001668
Douglas Gregor17bd0942009-01-28 23:36:17 +00001669 // Repeatedly perform subobject initializations in the range
1670 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001671
Douglas Gregor17bd0942009-01-28 23:36:17 +00001672 // Move to the next designator
1673 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1674 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001675
1676 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001677 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001678
Douglas Gregor17bd0942009-01-28 23:36:17 +00001679 while (DesignatedStartIndex <= DesignatedEndIndex) {
1680 // Recurse to check later designated subobjects.
1681 QualType ElementType = AT->getElementType();
1682 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001683
1684 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001685 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001686 ElementType, 0, 0, Index,
1687 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001688 (DesignatedStartIndex == DesignatedEndIndex),
1689 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001690 return true;
1691
1692 // Move to the next index in the array that we'll be initializing.
1693 ++DesignatedStartIndex;
1694 ElementIndex = DesignatedStartIndex.getZExtValue();
1695 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001696
1697 // If this the first designator, our caller will continue checking
1698 // the rest of this array subobject.
1699 if (IsFirstDesignator) {
1700 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001701 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001702 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001703 return false;
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Douglas Gregor17bd0942009-01-28 23:36:17 +00001706 if (!FinishSubobjectInit)
1707 return false;
1708
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001709 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001710 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001711 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001712 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001713 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001714 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001715}
1716
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001717// Get the structured initializer list for a subobject of type
1718// @p CurrentObjectType.
1719InitListExpr *
1720InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1721 QualType CurrentObjectType,
1722 InitListExpr *StructuredList,
1723 unsigned StructuredIndex,
1724 SourceRange InitRange) {
1725 Expr *ExistingInit = 0;
1726 if (!StructuredList)
1727 ExistingInit = SyntacticToSemantic[IList];
1728 else if (StructuredIndex < StructuredList->getNumInits())
1729 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001730
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001731 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1732 return Result;
1733
1734 if (ExistingInit) {
1735 // We are creating an initializer list that initializes the
1736 // subobjects of the current object, but there was already an
1737 // initialization that completely initialized the current
1738 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001739 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001740 // struct X { int a, b; };
1741 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001742 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1744 // designated initializer re-initializes the whole
1745 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001746 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001747 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001748 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001749 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001750 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001751 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001752 << ExistingInit->getSourceRange();
1753 }
1754
Mike Stump11289f42009-09-09 15:08:12 +00001755 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001756 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1757 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001758 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001759
Douglas Gregora8a089b2010-07-13 18:40:04 +00001760 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001761
Douglas Gregor6d00c992009-03-20 23:58:33 +00001762 // Pre-allocate storage for the structured initializer list.
1763 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001764 unsigned NumInits = 0;
1765 if (!StructuredList)
1766 NumInits = IList->getNumInits();
1767 else if (Index < IList->getNumInits()) {
1768 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1769 NumInits = SubList->getNumInits();
1770 }
1771
Mike Stump11289f42009-09-09 15:08:12 +00001772 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001773 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1774 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1775 NumElements = CAType->getSize().getZExtValue();
1776 // Simple heuristic so that we don't allocate a very large
1777 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001778 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001779 NumElements = 0;
1780 }
John McCall9dd450b2009-09-21 23:43:11 +00001781 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001782 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001783 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001784 RecordDecl *RDecl = RType->getDecl();
1785 if (RDecl->isUnion())
1786 NumElements = 1;
1787 else
Mike Stump11289f42009-09-09 15:08:12 +00001788 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001789 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001790 }
1791
Douglas Gregor221c9a52009-03-21 18:13:52 +00001792 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001793 NumElements = IList->getNumInits();
1794
Ted Kremenekac034612010-04-13 23:39:13 +00001795 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001796
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001797 // Link this new initializer list into the structured initializer
1798 // lists.
1799 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001800 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001801 else {
1802 Result->setSyntacticForm(IList);
1803 SyntacticToSemantic[IList] = Result;
1804 }
1805
1806 return Result;
1807}
1808
1809/// Update the initializer at index @p StructuredIndex within the
1810/// structured initializer list to the value @p expr.
1811void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1812 unsigned &StructuredIndex,
1813 Expr *expr) {
1814 // No structured initializer list to update
1815 if (!StructuredList)
1816 return;
1817
Ted Kremenekac034612010-04-13 23:39:13 +00001818 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1819 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001820 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001821 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001822 diag::warn_initializer_overrides)
1823 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001824 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001825 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001826 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001827 << PrevInit->getSourceRange();
1828 }
Mike Stump11289f42009-09-09 15:08:12 +00001829
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001830 ++StructuredIndex;
1831}
1832
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001833/// Check that the given Index expression is a valid array designator
1834/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001835/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001836/// and produces a reasonable diagnostic if there is a
1837/// failure. Returns true if there was an error, false otherwise. If
1838/// everything went okay, Value will receive the value of the constant
1839/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001840static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001841CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001842 SourceLocation Loc = Index->getSourceRange().getBegin();
1843
1844 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001845 if (S.VerifyIntegerConstantExpression(Index, &Value))
1846 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001847
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001848 if (Value.isSigned() && Value.isNegative())
1849 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001850 << Value.toString(10) << Index->getSourceRange();
1851
Douglas Gregor51650d32009-01-23 21:04:18 +00001852 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001853 return false;
1854}
1855
John McCalldadc5752010-08-24 06:29:42 +00001856ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001857 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001858 bool GNUSyntax,
John McCalldadc5752010-08-24 06:29:42 +00001859 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001860 typedef DesignatedInitExpr::Designator ASTDesignator;
1861
1862 bool Invalid = false;
1863 llvm::SmallVector<ASTDesignator, 32> Designators;
1864 llvm::SmallVector<Expr *, 32> InitExpressions;
1865
1866 // Build designators and check array designator expressions.
1867 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1868 const Designator &D = Desig.getDesignator(Idx);
1869 switch (D.getKind()) {
1870 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001871 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001872 D.getFieldLoc()));
1873 break;
1874
1875 case Designator::ArrayDesignator: {
1876 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1877 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001878 if (!Index->isTypeDependent() &&
1879 !Index->isValueDependent() &&
1880 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001881 Invalid = true;
1882 else {
1883 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001884 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001885 D.getRBracketLoc()));
1886 InitExpressions.push_back(Index);
1887 }
1888 break;
1889 }
1890
1891 case Designator::ArrayRangeDesignator: {
1892 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1893 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1894 llvm::APSInt StartValue;
1895 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001896 bool StartDependent = StartIndex->isTypeDependent() ||
1897 StartIndex->isValueDependent();
1898 bool EndDependent = EndIndex->isTypeDependent() ||
1899 EndIndex->isValueDependent();
1900 if ((!StartDependent &&
1901 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1902 (!EndDependent &&
1903 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001904 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001905 else {
1906 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001907 if (StartDependent || EndDependent) {
1908 // Nothing to compute.
1909 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001910 EndValue.extend(StartValue.getBitWidth());
1911 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1912 StartValue.extend(EndValue.getBitWidth());
1913
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001914 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001915 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001916 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001917 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1918 Invalid = true;
1919 } else {
1920 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001921 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001922 D.getEllipsisLoc(),
1923 D.getRBracketLoc()));
1924 InitExpressions.push_back(StartIndex);
1925 InitExpressions.push_back(EndIndex);
1926 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001927 }
1928 break;
1929 }
1930 }
1931 }
1932
1933 if (Invalid || Init.isInvalid())
1934 return ExprError();
1935
1936 // Clear out the expressions within the designation.
1937 Desig.ClearExprs(*this);
1938
1939 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001940 = DesignatedInitExpr::Create(Context,
1941 Designators.data(), Designators.size(),
1942 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001943 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001944 return Owned(DIE);
1945}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001946
Douglas Gregor723796a2009-12-16 06:35:08 +00001947bool Sema::CheckInitList(const InitializedEntity &Entity,
1948 InitListExpr *&InitList, QualType &DeclType) {
1949 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001950 if (!CheckInitList.HadError())
1951 InitList = CheckInitList.getFullyStructuredList();
1952
1953 return CheckInitList.HadError();
1954}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001955
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001956//===----------------------------------------------------------------------===//
1957// Initialization entity
1958//===----------------------------------------------------------------------===//
1959
Douglas Gregor723796a2009-12-16 06:35:08 +00001960InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1961 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001962 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001963{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001964 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1965 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001966 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001967 } else {
1968 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001969 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001970 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001971}
1972
1973InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001974 CXXBaseSpecifier *Base,
1975 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001976{
1977 InitializedEntity Result;
1978 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001979 Result.Base = reinterpret_cast<uintptr_t>(Base);
1980 if (IsInheritedVirtualBase)
1981 Result.Base |= 0x01;
1982
Douglas Gregor1b303932009-12-22 15:35:07 +00001983 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001984 return Result;
1985}
1986
Douglas Gregor85dabae2009-12-16 01:38:02 +00001987DeclarationName InitializedEntity::getName() const {
1988 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001989 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001990 if (!VariableOrMember)
1991 return DeclarationName();
1992 // Fall through
1993
1994 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001995 case EK_Member:
1996 return VariableOrMember->getDeclName();
1997
1998 case EK_Result:
1999 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002000 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002001 case EK_Temporary:
2002 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002003 case EK_ArrayElement:
2004 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002005 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002006 return DeclarationName();
2007 }
2008
2009 // Silence GCC warning
2010 return DeclarationName();
2011}
2012
Douglas Gregora4b592a2009-12-19 03:01:41 +00002013DeclaratorDecl *InitializedEntity::getDecl() const {
2014 switch (getKind()) {
2015 case EK_Variable:
2016 case EK_Parameter:
2017 case EK_Member:
2018 return VariableOrMember;
2019
2020 case EK_Result:
2021 case EK_Exception:
2022 case EK_New:
2023 case EK_Temporary:
2024 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002025 case EK_ArrayElement:
2026 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002027 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002028 return 0;
2029 }
2030
2031 // Silence GCC warning
2032 return 0;
2033}
2034
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002035bool InitializedEntity::allowsNRVO() const {
2036 switch (getKind()) {
2037 case EK_Result:
2038 case EK_Exception:
2039 return LocAndNRVO.NRVO;
2040
2041 case EK_Variable:
2042 case EK_Parameter:
2043 case EK_Member:
2044 case EK_New:
2045 case EK_Temporary:
2046 case EK_Base:
2047 case EK_ArrayElement:
2048 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002049 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002050 break;
2051 }
2052
2053 return false;
2054}
2055
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002056//===----------------------------------------------------------------------===//
2057// Initialization sequence
2058//===----------------------------------------------------------------------===//
2059
2060void InitializationSequence::Step::Destroy() {
2061 switch (Kind) {
2062 case SK_ResolveAddressOfOverloadedFunction:
2063 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002064 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002065 case SK_CastDerivedToBaseLValue:
2066 case SK_BindReference:
2067 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002068 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002069 case SK_UserConversion:
2070 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002071 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002072 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002073 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002074 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002075 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002076 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002077 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002078 case SK_ObjCObjectConversion:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002079 break;
2080
2081 case SK_ConversionSequence:
2082 delete ICS;
2083 }
2084}
2085
Douglas Gregor838fcc32010-03-26 20:14:36 +00002086bool InitializationSequence::isDirectReferenceBinding() const {
2087 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2088}
2089
2090bool InitializationSequence::isAmbiguous() const {
2091 if (getKind() != FailedSequence)
2092 return false;
2093
2094 switch (getFailureKind()) {
2095 case FK_TooManyInitsForReference:
2096 case FK_ArrayNeedsInitList:
2097 case FK_ArrayNeedsInitListOrStringLiteral:
2098 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2099 case FK_NonConstLValueReferenceBindingToTemporary:
2100 case FK_NonConstLValueReferenceBindingToUnrelated:
2101 case FK_RValueReferenceBindingToLValue:
2102 case FK_ReferenceInitDropsQualifiers:
2103 case FK_ReferenceInitFailed:
2104 case FK_ConversionFailed:
2105 case FK_TooManyInitsForScalar:
2106 case FK_ReferenceBindingToInitList:
2107 case FK_InitListBadDestinationType:
2108 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002109 case FK_Incomplete:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002110 return false;
2111
2112 case FK_ReferenceInitOverloadFailed:
2113 case FK_UserConversionOverloadFailed:
2114 case FK_ConstructorOverloadFailed:
2115 return FailedOverloadResult == OR_Ambiguous;
2116 }
2117
2118 return false;
2119}
2120
Douglas Gregorb33eed02010-04-16 22:09:46 +00002121bool InitializationSequence::isConstructorInitialization() const {
2122 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2123}
2124
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002125void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002126 FunctionDecl *Function,
2127 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002128 Step S;
2129 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2130 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002131 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002132 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002133 Steps.push_back(S);
2134}
2135
2136void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002137 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002138 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002139 switch (VK) {
2140 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2141 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2142 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002143 default: llvm_unreachable("No such category");
2144 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002145 S.Type = BaseType;
2146 Steps.push_back(S);
2147}
2148
2149void InitializationSequence::AddReferenceBindingStep(QualType T,
2150 bool BindingTemporary) {
2151 Step S;
2152 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2153 S.Type = T;
2154 Steps.push_back(S);
2155}
2156
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002157void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2158 Step S;
2159 S.Kind = SK_ExtraneousCopyToTemporary;
2160 S.Type = T;
2161 Steps.push_back(S);
2162}
2163
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002164void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002165 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002166 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002167 Step S;
2168 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002169 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002170 S.Function.Function = Function;
2171 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002172 Steps.push_back(S);
2173}
2174
2175void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002176 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002177 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002178 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002179 switch (VK) {
2180 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002181 S.Kind = SK_QualificationConversionRValue;
2182 break;
John McCall2536c6d2010-08-25 10:28:54 +00002183 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002184 S.Kind = SK_QualificationConversionXValue;
2185 break;
John McCall2536c6d2010-08-25 10:28:54 +00002186 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002187 S.Kind = SK_QualificationConversionLValue;
2188 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002189 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002190 S.Type = Ty;
2191 Steps.push_back(S);
2192}
2193
2194void InitializationSequence::AddConversionSequenceStep(
2195 const ImplicitConversionSequence &ICS,
2196 QualType T) {
2197 Step S;
2198 S.Kind = SK_ConversionSequence;
2199 S.Type = T;
2200 S.ICS = new ImplicitConversionSequence(ICS);
2201 Steps.push_back(S);
2202}
2203
Douglas Gregor51e77d52009-12-10 17:56:55 +00002204void InitializationSequence::AddListInitializationStep(QualType T) {
2205 Step S;
2206 S.Kind = SK_ListInitialization;
2207 S.Type = T;
2208 Steps.push_back(S);
2209}
2210
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002211void
2212InitializationSequence::AddConstructorInitializationStep(
2213 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002214 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002215 QualType T) {
2216 Step S;
2217 S.Kind = SK_ConstructorInitialization;
2218 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002219 S.Function.Function = Constructor;
2220 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002221 Steps.push_back(S);
2222}
2223
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002224void InitializationSequence::AddZeroInitializationStep(QualType T) {
2225 Step S;
2226 S.Kind = SK_ZeroInitialization;
2227 S.Type = T;
2228 Steps.push_back(S);
2229}
2230
Douglas Gregore1314a62009-12-18 05:02:21 +00002231void InitializationSequence::AddCAssignmentStep(QualType T) {
2232 Step S;
2233 S.Kind = SK_CAssignment;
2234 S.Type = T;
2235 Steps.push_back(S);
2236}
2237
Eli Friedman78275202009-12-19 08:11:05 +00002238void InitializationSequence::AddStringInitStep(QualType T) {
2239 Step S;
2240 S.Kind = SK_StringInit;
2241 S.Type = T;
2242 Steps.push_back(S);
2243}
2244
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002245void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2246 Step S;
2247 S.Kind = SK_ObjCObjectConversion;
2248 S.Type = T;
2249 Steps.push_back(S);
2250}
2251
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002252void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2253 OverloadingResult Result) {
2254 SequenceKind = FailedSequence;
2255 this->Failure = Failure;
2256 this->FailedOverloadResult = Result;
2257}
2258
2259//===----------------------------------------------------------------------===//
2260// Attempt initialization
2261//===----------------------------------------------------------------------===//
2262
2263/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002264static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002265 const InitializedEntity &Entity,
2266 const InitializationKind &Kind,
2267 InitListExpr *InitList,
2268 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002269 // FIXME: We only perform rudimentary checking of list
2270 // initializations at this point, then assume that any list
2271 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002272 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002273 // do all of the necessary checking. C++0x initializer lists will
2274 // force us to perform more checking here.
2275 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2276
Douglas Gregor1b303932009-12-22 15:35:07 +00002277 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002278
2279 // C++ [dcl.init]p13:
2280 // If T is a scalar type, then a declaration of the form
2281 //
2282 // T x = { a };
2283 //
2284 // is equivalent to
2285 //
2286 // T x = a;
2287 if (DestType->isScalarType()) {
2288 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2289 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2290 return;
2291 }
2292
2293 // Assume scalar initialization from a single value works.
2294 } else if (DestType->isAggregateType()) {
2295 // Assume aggregate initialization works.
2296 } else if (DestType->isVectorType()) {
2297 // Assume vector initialization works.
2298 } else if (DestType->isReferenceType()) {
2299 // FIXME: C++0x defines behavior for this.
2300 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2301 return;
2302 } else if (DestType->isRecordType()) {
2303 // FIXME: C++0x defines behavior for this
2304 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2305 }
2306
2307 // Add a general "list initialization" step.
2308 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002309}
2310
2311/// \brief Try a reference initialization that involves calling a conversion
2312/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002313static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2314 const InitializedEntity &Entity,
2315 const InitializationKind &Kind,
2316 Expr *Initializer,
2317 bool AllowRValues,
2318 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002319 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002320 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2321 QualType T1 = cv1T1.getUnqualifiedType();
2322 QualType cv2T2 = Initializer->getType();
2323 QualType T2 = cv2T2.getUnqualifiedType();
2324
2325 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002326 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002327 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002328 T1, T2, DerivedToBase,
2329 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002330 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002331 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002332 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002333
2334 // Build the candidate set directly in the initialization sequence
2335 // structure, so that it will persist if we fail.
2336 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2337 CandidateSet.clear();
2338
2339 // Determine whether we are allowed to call explicit constructors or
2340 // explicit conversion operators.
2341 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2342
2343 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002344 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2345 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002346 // The type we're converting to is a class type. Enumerate its constructors
2347 // to see if there is a suitable conversion.
2348 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002349
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002350 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002351 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002352 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002353 NamedDecl *D = *Con;
2354 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2355
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002356 // Find the constructor (which may be a template).
2357 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002358 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002359 if (ConstructorTmpl)
2360 Constructor = cast<CXXConstructorDecl>(
2361 ConstructorTmpl->getTemplatedDecl());
2362 else
John McCalla0296f72010-03-19 07:35:19 +00002363 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002364
2365 if (!Constructor->isInvalidDecl() &&
2366 Constructor->isConvertingConstructor(AllowExplicit)) {
2367 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002368 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002369 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002370 &Initializer, 1, CandidateSet,
2371 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002372 else
John McCalla0296f72010-03-19 07:35:19 +00002373 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002374 &Initializer, 1, CandidateSet,
2375 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002376 }
2377 }
2378 }
John McCall3696dcb2010-08-17 07:23:57 +00002379 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2380 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002381
Douglas Gregor496e8b342010-05-07 19:42:26 +00002382 const RecordType *T2RecordType = 0;
2383 if ((T2RecordType = T2->getAs<RecordType>()) &&
2384 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002385 // The type we're converting from is a class type, enumerate its conversion
2386 // functions.
2387 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2388
2389 // Determine the type we are converting to. If we are allowed to
2390 // convert to an rvalue, take the type that the destination type
2391 // refers to.
2392 QualType ToType = AllowRValues? cv1T1 : DestType;
2393
John McCallad371252010-01-20 00:46:10 +00002394 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002395 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002396 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2397 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002398 NamedDecl *D = *I;
2399 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2400 if (isa<UsingShadowDecl>(D))
2401 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2402
2403 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2404 CXXConversionDecl *Conv;
2405 if (ConvTemplate)
2406 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2407 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002408 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002409
2410 // If the conversion function doesn't return a reference type,
2411 // it can't be considered for this conversion unless we're allowed to
2412 // consider rvalues.
2413 // FIXME: Do we need to make sure that we only consider conversion
2414 // candidates with reference-compatible results? That might be needed to
2415 // break recursion.
2416 if ((AllowExplicit || !Conv->isExplicit()) &&
2417 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2418 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002419 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002420 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002421 ToType, CandidateSet);
2422 else
John McCalla0296f72010-03-19 07:35:19 +00002423 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002424 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002425 }
2426 }
2427 }
John McCall3696dcb2010-08-17 07:23:57 +00002428 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2429 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002430
2431 SourceLocation DeclLoc = Initializer->getLocStart();
2432
2433 // Perform overload resolution. If it fails, return the failed result.
2434 OverloadCandidateSet::iterator Best;
2435 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002436 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002437 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002438
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002439 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002440
2441 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002442 if (isa<CXXConversionDecl>(Function))
2443 T2 = Function->getResultType();
2444 else
2445 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002446
2447 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002448 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002449 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002450
2451 // Determine whether we need to perform derived-to-base or
2452 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002453 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002454 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002455 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002456 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002457 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002458
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002459 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002460 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002461 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregora8a089b2010-07-13 18:40:04 +00002462 = S.CompareReferenceRelationship(DeclLoc, T1,
2463 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002464 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002465 if (NewRefRelationship == Sema::Ref_Incompatible) {
2466 // If the type we've converted to is not reference-related to the
2467 // type we're looking for, then there is another conversion step
2468 // we need to perform to produce a temporary of the right type
2469 // that we'll be binding to.
2470 ImplicitConversionSequence ICS;
2471 ICS.setStandard();
2472 ICS.Standard = Best->FinalConversion;
2473 T2 = ICS.Standard.getToType(2);
2474 Sequence.AddConversionSequenceStep(ICS, T2);
2475 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002476 Sequence.AddDerivedToBaseCastStep(
2477 S.Context.getQualifiedType(T1,
2478 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002479 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002480 else if (NewObjCConversion)
2481 Sequence.AddObjCObjectConversionStep(
2482 S.Context.getQualifiedType(T1,
2483 T2.getNonReferenceType().getQualifiers()));
2484
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002485 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002486 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487
2488 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2489 return OR_Success;
2490}
2491
Sebastian Redld92badf2010-06-30 18:13:39 +00002492/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002493static void TryReferenceInitialization(Sema &S,
2494 const InitializedEntity &Entity,
2495 const InitializationKind &Kind,
2496 Expr *Initializer,
2497 InitializationSequence &Sequence) {
2498 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002499
Douglas Gregor1b303932009-12-22 15:35:07 +00002500 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002501 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002502 Qualifiers T1Quals;
2503 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002504 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002505 Qualifiers T2Quals;
2506 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002507 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002508
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002509 // If the initializer is the address of an overloaded function, try
2510 // to resolve the overloaded function. If all goes well, T2 is the
2511 // type of the resulting function.
2512 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002513 DeclAccessPair Found;
Douglas Gregorbcd62532010-11-08 15:20:28 +00002514 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2515 T1,
2516 false,
2517 Found)) {
2518 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2519 cv2T2 = Fn->getType();
2520 T2 = cv2T2.getUnqualifiedType();
2521 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002522 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2523 return;
2524 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002525 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002526
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002527 // Compute some basic properties of the types and the initializer.
2528 bool isLValueRef = DestType->isLValueReferenceType();
2529 bool isRValueRef = !isLValueRef;
2530 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002531 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002532 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002533 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002534 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2535 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002536
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002537 // C++0x [dcl.init.ref]p5:
2538 // A reference to type "cv1 T1" is initialized by an expression of type
2539 // "cv2 T2" as follows:
2540 //
2541 // - If the reference is an lvalue reference and the initializer
2542 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002543 // Note the analogous bullet points for rvlaue refs to functions. Because
2544 // there are no function rvalues in C++, rvalue refs to functions are treated
2545 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002546 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002547 bool T1Function = T1->isFunctionType();
2548 if (isLValueRef || T1Function) {
2549 if (InitCategory.isLValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002550 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2551 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2552 // reference-compatible with "cv2 T2," or
2553 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002554 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002555 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002556 // can occur. However, we do pay attention to whether it is a bit-field
2557 // to decide whether we're actually binding to a temporary created from
2558 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002559 if (DerivedToBase)
2560 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002561 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002562 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002563 else if (ObjCConversion)
2564 Sequence.AddObjCObjectConversionStep(
2565 S.Context.getQualifiedType(T1, T2Quals));
2566
Chandler Carruth04bdce62010-01-12 20:32:25 +00002567 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002568 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002569 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002570 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002571 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002572 return;
2573 }
2574
2575 // - has a class type (i.e., T2 is a class type), where T1 is not
2576 // reference-related to T2, and can be implicitly converted to an
2577 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2578 // with "cv3 T3" (this conversion is selected by enumerating the
2579 // applicable conversion functions (13.3.1.6) and choosing the best
2580 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002581 // If we have an rvalue ref to function type here, the rhs must be
2582 // an rvalue.
2583 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2584 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002585 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2586 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002587 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002588 Sequence);
2589 if (ConvOvlResult == OR_Success)
2590 return;
John McCall0d1da222010-01-12 00:44:57 +00002591 if (ConvOvlResult != OR_No_Viable_Function) {
2592 Sequence.SetOverloadFailure(
2593 InitializationSequence::FK_ReferenceInitOverloadFailed,
2594 ConvOvlResult);
2595 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002596 }
2597 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002598
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002599 // - Otherwise, the reference shall be an lvalue reference to a
2600 // non-volatile const type (i.e., cv1 shall be const), or the reference
2601 // shall be an rvalue reference and the initializer expression shall
Sebastian Redld92badf2010-06-30 18:13:39 +00002602 // be an rvalue or have a function type.
2603 // We handled the function type stuff above.
Douglas Gregord1e08642010-01-29 19:39:15 +00002604 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redld92badf2010-06-30 18:13:39 +00002605 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002606 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2607 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2608 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002609 Sequence.SetOverloadFailure(
2610 InitializationSequence::FK_ReferenceInitOverloadFailed,
2611 ConvOvlResult);
2612 else if (isLValueRef)
Sebastian Redld92badf2010-06-30 18:13:39 +00002613 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002614 ? (RefRelationship == Sema::Ref_Related
2615 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2616 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2617 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2618 else
2619 Sequence.SetFailed(
2620 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redld92badf2010-06-30 18:13:39 +00002621
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002622 return;
2623 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002624
2625 // - [If T1 is not a function type], if T2 is a class type and
2626 if (!T1Function && T2->isRecordType()) {
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002627 bool isXValue = InitCategory.isXValue();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002628 // - the initializer expression is an rvalue and "cv1 T1" is
2629 // reference-compatible with "cv2 T2", or
Sebastian Redld92badf2010-06-30 18:13:39 +00002630 if (InitCategory.isRValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002631 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002632 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2633 // compiler the freedom to perform a copy here or bind to the
2634 // object, while C++0x requires that we bind directly to the
2635 // object. Hence, we always bind to the object without making an
2636 // extra copy. However, in C++03 requires that we check for the
2637 // presence of a suitable copy constructor:
2638 //
2639 // The constructor that would be used to make the copy shall
2640 // be callable whether or not the copy is actually done.
2641 if (!S.getLangOptions().CPlusPlus0x)
2642 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2643
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002644 if (DerivedToBase)
2645 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002646 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002647 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002648 else if (ObjCConversion)
2649 Sequence.AddObjCObjectConversionStep(
2650 S.Context.getQualifiedType(T1, T2Quals));
2651
Chandler Carruth04bdce62010-01-12 20:32:25 +00002652 if (T1Quals != T2Quals)
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002653 Sequence.AddQualificationConversionStep(cv1T1,
John McCall2536c6d2010-08-25 10:28:54 +00002654 isXValue ? VK_XValue : VK_RValue);
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002655 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002656 return;
2657 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002658
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002659 // - T1 is not reference-related to T2 and the initializer expression
2660 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2661 // conversion is selected by enumerating the applicable conversion
2662 // functions (13.3.1.6) and choosing the best one through overload
2663 // resolution (13.3)),
2664 if (RefRelationship == Sema::Ref_Incompatible) {
2665 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2666 Kind, Initializer,
2667 /*AllowRValues=*/true,
2668 Sequence);
2669 if (ConvOvlResult)
2670 Sequence.SetOverloadFailure(
2671 InitializationSequence::FK_ReferenceInitOverloadFailed,
2672 ConvOvlResult);
2673
2674 return;
2675 }
2676
2677 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2678 return;
2679 }
2680
2681 // - If the initializer expression is an rvalue, with T2 an array type,
2682 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2683 // is bound to the object represented by the rvalue (see 3.10).
2684 // FIXME: How can an array type be reference-compatible with anything?
2685 // Don't we mean the element types of T1 and T2?
2686
2687 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2688 // from the initializer expression using the rules for a non-reference
2689 // copy initialization (8.5). The reference is then bound to the
2690 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002691
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002692 // Determine whether we are allowed to call explicit constructors or
2693 // explicit conversion operators.
2694 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002695
2696 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2697
2698 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2699 /*SuppressUserConversions*/ false,
2700 AllowExplicit,
2701 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002702 // FIXME: Use the conversion function set stored in ICS to turn
2703 // this into an overloading ambiguity diagnostic. However, we need
2704 // to keep that set as an OverloadCandidateSet rather than as some
2705 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002706 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2707 Sequence.SetOverloadFailure(
2708 InitializationSequence::FK_ReferenceInitOverloadFailed,
2709 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002710 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2711 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002712 else
2713 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002714 return;
2715 }
2716
2717 // [...] If T1 is reference-related to T2, cv1 must be the
2718 // same cv-qualification as, or greater cv-qualification
2719 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002720 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2721 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002722 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002723 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002724 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2725 return;
2726 }
2727
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002728 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2729 return;
2730}
2731
2732/// \brief Attempt character array initialization from a string literal
2733/// (C++ [dcl.init.string], C99 6.7.8).
2734static void TryStringLiteralInitialization(Sema &S,
2735 const InitializedEntity &Entity,
2736 const InitializationKind &Kind,
2737 Expr *Initializer,
2738 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002739 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002740 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002741}
2742
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002743/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2744/// enumerates the constructors of the initialized entity and performs overload
2745/// resolution to select the best.
2746static void TryConstructorInitialization(Sema &S,
2747 const InitializedEntity &Entity,
2748 const InitializationKind &Kind,
2749 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002750 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002751 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002752 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002753
2754 // Build the candidate set directly in the initialization sequence
2755 // structure, so that it will persist if we fail.
2756 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2757 CandidateSet.clear();
2758
2759 // Determine whether we are allowed to call explicit constructors or
2760 // explicit conversion operators.
2761 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2762 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002763 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002764
2765 // The type we're constructing needs to be complete.
2766 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002767 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002768 return;
2769 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002770
2771 // The type we're converting to is a class type. Enumerate its constructors
2772 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002773 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2774 assert(DestRecordType && "Constructor initialization requires record type");
2775 CXXRecordDecl *DestRecordDecl
2776 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2777
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002778 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002779 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002780 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002781 NamedDecl *D = *Con;
2782 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002783 bool SuppressUserConversions = false;
2784
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002785 // Find the constructor (which may be a template).
2786 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002787 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002788 if (ConstructorTmpl)
2789 Constructor = cast<CXXConstructorDecl>(
2790 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002791 else {
John McCalla0296f72010-03-19 07:35:19 +00002792 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002793
2794 // If we're performing copy initialization using a copy constructor, we
2795 // suppress user-defined conversions on the arguments.
2796 // FIXME: Move constructors?
2797 if (Kind.getKind() == InitializationKind::IK_Copy &&
2798 Constructor->isCopyConstructor())
2799 SuppressUserConversions = true;
2800 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002801
2802 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002803 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002804 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002805 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002806 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002807 Args, NumArgs, CandidateSet,
2808 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002809 else
John McCalla0296f72010-03-19 07:35:19 +00002810 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002811 Args, NumArgs, CandidateSet,
2812 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002813 }
2814 }
2815
2816 SourceLocation DeclLoc = Kind.getLocation();
2817
2818 // Perform overload resolution. If it fails, return the failed result.
2819 OverloadCandidateSet::iterator Best;
2820 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002821 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002822 Sequence.SetOverloadFailure(
2823 InitializationSequence::FK_ConstructorOverloadFailed,
2824 Result);
2825 return;
2826 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002827
2828 // C++0x [dcl.init]p6:
2829 // If a program calls for the default initialization of an object
2830 // of a const-qualified type T, T shall be a class type with a
2831 // user-provided default constructor.
2832 if (Kind.getKind() == InitializationKind::IK_Default &&
2833 Entity.getType().isConstQualified() &&
2834 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2835 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2836 return;
2837 }
2838
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002839 // Add the constructor initialization step. Any cv-qualification conversion is
2840 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002841 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002842 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002843 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002844 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002845}
2846
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002847/// \brief Attempt value initialization (C++ [dcl.init]p7).
2848static void TryValueInitialization(Sema &S,
2849 const InitializedEntity &Entity,
2850 const InitializationKind &Kind,
2851 InitializationSequence &Sequence) {
2852 // C++ [dcl.init]p5:
2853 //
2854 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002855 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002856
2857 // -- if T is an array type, then each element is value-initialized;
2858 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2859 T = AT->getElementType();
2860
2861 if (const RecordType *RT = T->getAs<RecordType>()) {
2862 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2863 // -- if T is a class type (clause 9) with a user-declared
2864 // constructor (12.1), then the default constructor for T is
2865 // called (and the initialization is ill-formed if T has no
2866 // accessible default constructor);
2867 //
2868 // FIXME: we really want to refer to a single subobject of the array,
2869 // but Entity doesn't have a way to capture that (yet).
2870 if (ClassDecl->hasUserDeclaredConstructor())
2871 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2872
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002873 // -- if T is a (possibly cv-qualified) non-union class type
2874 // without a user-provided constructor, then the object is
2875 // zero-initialized and, if T’s implicitly-declared default
2876 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002877 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002878 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002879 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002880 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2881 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002882 }
2883 }
2884
Douglas Gregor1b303932009-12-22 15:35:07 +00002885 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002886 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2887}
2888
Douglas Gregor85dabae2009-12-16 01:38:02 +00002889/// \brief Attempt default initialization (C++ [dcl.init]p6).
2890static void TryDefaultInitialization(Sema &S,
2891 const InitializedEntity &Entity,
2892 const InitializationKind &Kind,
2893 InitializationSequence &Sequence) {
2894 assert(Kind.getKind() == InitializationKind::IK_Default);
2895
2896 // C++ [dcl.init]p6:
2897 // To default-initialize an object of type T means:
2898 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002899 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002900 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2901 DestType = Array->getElementType();
2902
2903 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2904 // constructor for T is called (and the initialization is ill-formed if
2905 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002906 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002907 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2908 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002909 }
2910
2911 // - otherwise, no initialization is performed.
2912 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2913
2914 // If a program calls for the default initialization of an object of
2915 // a const-qualified type T, T shall be a class type with a user-provided
2916 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002917 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002918 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2919}
2920
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002921/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2922/// which enumerates all conversion functions and performs overload resolution
2923/// to select the best.
2924static void TryUserDefinedConversion(Sema &S,
2925 const InitializedEntity &Entity,
2926 const InitializationKind &Kind,
2927 Expr *Initializer,
2928 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002929 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2930
Douglas Gregor1b303932009-12-22 15:35:07 +00002931 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002932 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2933 QualType SourceType = Initializer->getType();
2934 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2935 "Must have a class type to perform a user-defined conversion");
2936
2937 // Build the candidate set directly in the initialization sequence
2938 // structure, so that it will persist if we fail.
2939 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2940 CandidateSet.clear();
2941
2942 // Determine whether we are allowed to call explicit constructors or
2943 // explicit conversion operators.
2944 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2945
2946 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2947 // The type we're converting to is a class type. Enumerate its constructors
2948 // to see if there is a suitable conversion.
2949 CXXRecordDecl *DestRecordDecl
2950 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2951
Douglas Gregord9848152010-04-26 14:36:57 +00002952 // Try to complete the type we're converting to.
2953 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002954 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002955 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002956 Con != ConEnd; ++Con) {
2957 NamedDecl *D = *Con;
2958 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002959
Douglas Gregord9848152010-04-26 14:36:57 +00002960 // Find the constructor (which may be a template).
2961 CXXConstructorDecl *Constructor = 0;
2962 FunctionTemplateDecl *ConstructorTmpl
2963 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002964 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002965 Constructor = cast<CXXConstructorDecl>(
2966 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002967 else
Douglas Gregord9848152010-04-26 14:36:57 +00002968 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord9848152010-04-26 14:36:57 +00002969
2970 if (!Constructor->isInvalidDecl() &&
2971 Constructor->isConvertingConstructor(AllowExplicit)) {
2972 if (ConstructorTmpl)
2973 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2974 /*ExplicitArgs*/ 0,
2975 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002976 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002977 else
2978 S.AddOverloadCandidate(Constructor, FoundDecl,
2979 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002980 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002981 }
2982 }
2983 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002984 }
Eli Friedman78275202009-12-19 08:11:05 +00002985
2986 SourceLocation DeclLoc = Initializer->getLocStart();
2987
Douglas Gregor540c3b02009-12-14 17:27:33 +00002988 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2989 // The type we're converting from is a class type, enumerate its conversion
2990 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002991
Eli Friedman4afe9a32009-12-20 22:12:03 +00002992 // We can only enumerate the conversion functions for a complete type; if
2993 // the type isn't complete, simply skip this step.
2994 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2995 CXXRecordDecl *SourceRecordDecl
2996 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002997
John McCallad371252010-01-20 00:46:10 +00002998 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002999 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003000 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00003001 E = Conversions->end();
3002 I != E; ++I) {
3003 NamedDecl *D = *I;
3004 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3005 if (isa<UsingShadowDecl>(D))
3006 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3007
3008 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3009 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003010 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003011 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003012 else
John McCallda4458e2010-03-31 01:36:47 +00003013 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003014
3015 if (AllowExplicit || !Conv->isExplicit()) {
3016 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003017 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003018 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003019 CandidateSet);
3020 else
John McCalla0296f72010-03-19 07:35:19 +00003021 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003022 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003023 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003024 }
3025 }
3026 }
3027
Douglas Gregor540c3b02009-12-14 17:27:33 +00003028 // Perform overload resolution. If it fails, return the failed result.
3029 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003030 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003031 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003032 Sequence.SetOverloadFailure(
3033 InitializationSequence::FK_UserConversionOverloadFailed,
3034 Result);
3035 return;
3036 }
John McCall0d1da222010-01-12 00:44:57 +00003037
Douglas Gregor540c3b02009-12-14 17:27:33 +00003038 FunctionDecl *Function = Best->Function;
3039
3040 if (isa<CXXConstructorDecl>(Function)) {
3041 // Add the user-defined conversion step. Any cv-qualification conversion is
3042 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003043 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003044 return;
3045 }
3046
3047 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003048 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003049 if (ConvType->getAs<RecordType>()) {
3050 // If we're converting to a class type, there may be an copy if
3051 // the resulting temporary object (possible to create an object of
3052 // a base class type). That copy is not a separate conversion, so
3053 // we just make a note of the actual destination type (possibly a
3054 // base class of the type returned by the conversion function) and
3055 // let the user-defined conversion step handle the conversion.
3056 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3057 return;
3058 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003059
Douglas Gregor5ab11652010-04-17 22:01:05 +00003060 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3061
3062 // If the conversion following the call to the conversion function
3063 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003064 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3065 Best->FinalConversion.Third) {
3066 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003067 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003068 ICS.Standard = Best->FinalConversion;
3069 Sequence.AddConversionSequenceStep(ICS, DestType);
3070 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003071}
3072
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003073InitializationSequence::InitializationSequence(Sema &S,
3074 const InitializedEntity &Entity,
3075 const InitializationKind &Kind,
3076 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003077 unsigned NumArgs)
3078 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003079 ASTContext &Context = S.Context;
3080
3081 // C++0x [dcl.init]p16:
3082 // The semantics of initializers are as follows. The destination type is
3083 // the type of the object or reference being initialized and the source
3084 // type is the type of the initializer expression. The source type is not
3085 // defined when the initializer is a braced-init-list or when it is a
3086 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003087 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003088
3089 if (DestType->isDependentType() ||
3090 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3091 SequenceKind = DependentSequence;
3092 return;
3093 }
3094
3095 QualType SourceType;
3096 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003097 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003098 Initializer = Args[0];
3099 if (!isa<InitListExpr>(Initializer))
3100 SourceType = Initializer->getType();
3101 }
3102
3103 // - If the initializer is a braced-init-list, the object is
3104 // list-initialized (8.5.4).
3105 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3106 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003107 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003108 }
3109
3110 // - If the destination type is a reference type, see 8.5.3.
3111 if (DestType->isReferenceType()) {
3112 // C++0x [dcl.init.ref]p1:
3113 // A variable declared to be a T& or T&&, that is, "reference to type T"
3114 // (8.3.2), shall be initialized by an object, or function, of type T or
3115 // by an object that can be converted into a T.
3116 // (Therefore, multiple arguments are not permitted.)
3117 if (NumArgs != 1)
3118 SetFailed(FK_TooManyInitsForReference);
3119 else
3120 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3121 return;
3122 }
3123
3124 // - If the destination type is an array of characters, an array of
3125 // char16_t, an array of char32_t, or an array of wchar_t, and the
3126 // initializer is a string literal, see 8.5.2.
3127 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3128 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3129 return;
3130 }
3131
3132 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003133 if (Kind.getKind() == InitializationKind::IK_Value ||
3134 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003135 TryValueInitialization(S, Entity, Kind, *this);
3136 return;
3137 }
3138
Douglas Gregor85dabae2009-12-16 01:38:02 +00003139 // Handle default initialization.
3140 if (Kind.getKind() == InitializationKind::IK_Default){
3141 TryDefaultInitialization(S, Entity, Kind, *this);
3142 return;
3143 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003144
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003145 // - Otherwise, if the destination type is an array, the program is
3146 // ill-formed.
3147 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3148 if (AT->getElementType()->isAnyCharacterType())
3149 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3150 else
3151 SetFailed(FK_ArrayNeedsInitList);
3152
3153 return;
3154 }
Eli Friedman78275202009-12-19 08:11:05 +00003155
3156 // Handle initialization in C
3157 if (!S.getLangOptions().CPlusPlus) {
3158 setSequenceKind(CAssignment);
3159 AddCAssignmentStep(DestType);
3160 return;
3161 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003162
3163 // - If the destination type is a (possibly cv-qualified) class type:
3164 if (DestType->isRecordType()) {
3165 // - If the initialization is direct-initialization, or if it is
3166 // copy-initialization where the cv-unqualified version of the
3167 // source type is the same class as, or a derived class of, the
3168 // class of the destination, constructors are considered. [...]
3169 if (Kind.getKind() == InitializationKind::IK_Direct ||
3170 (Kind.getKind() == InitializationKind::IK_Copy &&
3171 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3172 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003173 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003174 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003175 // - Otherwise (i.e., for the remaining copy-initialization cases),
3176 // user-defined conversion sequences that can convert from the source
3177 // type to the destination type or (when a conversion function is
3178 // used) to a derived class thereof are enumerated as described in
3179 // 13.3.1.4, and the best one is chosen through overload resolution
3180 // (13.3).
3181 else
3182 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3183 return;
3184 }
3185
Douglas Gregor85dabae2009-12-16 01:38:02 +00003186 if (NumArgs > 1) {
3187 SetFailed(FK_TooManyInitsForScalar);
3188 return;
3189 }
3190 assert(NumArgs == 1 && "Zero-argument case handled above");
3191
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003192 // - Otherwise, if the source type is a (possibly cv-qualified) class
3193 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003194 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003195 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3196 return;
3197 }
3198
3199 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003200 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003201 // conversions (Clause 4) will be used, if necessary, to convert the
3202 // initializer expression to the cv-unqualified version of the
3203 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003204 if (S.TryImplicitConversion(*this, Entity, Initializer,
3205 /*SuppressUserConversions*/ true,
3206 /*AllowExplicitConversions*/ false,
3207 /*InOverloadResolution*/ false))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003208 {
3209 if (Initializer->getType() == Context.OverloadTy )
3210 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3211 else
3212 SetFailed(InitializationSequence::FK_ConversionFailed);
3213 }
John McCallec6f4e92010-06-04 02:29:22 +00003214 else
3215 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003216}
3217
3218InitializationSequence::~InitializationSequence() {
3219 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3220 StepEnd = Steps.end();
3221 Step != StepEnd; ++Step)
3222 Step->Destroy();
3223}
3224
3225//===----------------------------------------------------------------------===//
3226// Perform initialization
3227//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003228static Sema::AssignmentAction
3229getAssignmentAction(const InitializedEntity &Entity) {
3230 switch(Entity.getKind()) {
3231 case InitializedEntity::EK_Variable:
3232 case InitializedEntity::EK_New:
3233 return Sema::AA_Initializing;
3234
3235 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003236 if (Entity.getDecl() &&
3237 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3238 return Sema::AA_Sending;
3239
Douglas Gregore1314a62009-12-18 05:02:21 +00003240 return Sema::AA_Passing;
3241
3242 case InitializedEntity::EK_Result:
3243 return Sema::AA_Returning;
3244
3245 case InitializedEntity::EK_Exception:
3246 case InitializedEntity::EK_Base:
3247 llvm_unreachable("No assignment action for C++-specific initialization");
3248 break;
3249
3250 case InitializedEntity::EK_Temporary:
3251 // FIXME: Can we tell apart casting vs. converting?
3252 return Sema::AA_Casting;
3253
3254 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003255 case InitializedEntity::EK_ArrayElement:
3256 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003257 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003258 return Sema::AA_Initializing;
3259 }
3260
3261 return Sema::AA_Converting;
3262}
3263
Douglas Gregor95562572010-04-24 23:45:46 +00003264/// \brief Whether we should binding a created object as a temporary when
3265/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003266static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003267 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003268 case InitializedEntity::EK_ArrayElement:
3269 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003270 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003271 case InitializedEntity::EK_New:
3272 case InitializedEntity::EK_Variable:
3273 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003274 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003275 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003276 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003277 return false;
3278
3279 case InitializedEntity::EK_Parameter:
3280 case InitializedEntity::EK_Temporary:
3281 return true;
3282 }
3283
3284 llvm_unreachable("missed an InitializedEntity kind?");
3285}
3286
Douglas Gregor95562572010-04-24 23:45:46 +00003287/// \brief Whether the given entity, when initialized with an object
3288/// created for that initialization, requires destruction.
3289static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3290 switch (Entity.getKind()) {
3291 case InitializedEntity::EK_Member:
3292 case InitializedEntity::EK_Result:
3293 case InitializedEntity::EK_New:
3294 case InitializedEntity::EK_Base:
3295 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003296 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003297 return false;
3298
3299 case InitializedEntity::EK_Variable:
3300 case InitializedEntity::EK_Parameter:
3301 case InitializedEntity::EK_Temporary:
3302 case InitializedEntity::EK_ArrayElement:
3303 case InitializedEntity::EK_Exception:
3304 return true;
3305 }
3306
3307 llvm_unreachable("missed an InitializedEntity kind?");
3308}
3309
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003310/// \brief Make a (potentially elidable) temporary copy of the object
3311/// provided by the given initializer by calling the appropriate copy
3312/// constructor.
3313///
3314/// \param S The Sema object used for type-checking.
3315///
3316/// \param T The type of the temporary object, which must either by
3317/// the type of the initializer expression or a superclass thereof.
3318///
3319/// \param Enter The entity being initialized.
3320///
3321/// \param CurInit The initializer expression.
3322///
3323/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3324/// is permitted in C++03 (but not C++0x) when binding a reference to
3325/// an rvalue.
3326///
3327/// \returns An expression that copies the initializer expression into
3328/// a temporary object, or an error expression if a copy could not be
3329/// created.
John McCalldadc5752010-08-24 06:29:42 +00003330static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003331 QualType T,
3332 const InitializedEntity &Entity,
3333 ExprResult CurInit,
3334 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003335 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003336 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003337 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003338 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003339 Class = cast<CXXRecordDecl>(Record->getDecl());
3340 if (!Class)
3341 return move(CurInit);
3342
3343 // C++0x [class.copy]p34:
3344 // When certain criteria are met, an implementation is allowed to
3345 // omit the copy/move construction of a class object, even if the
3346 // copy/move constructor and/or destructor for the object have
3347 // side effects. [...]
3348 // - when a temporary class object that has not been bound to a
3349 // reference (12.2) would be copied/moved to a class object
3350 // with the same cv-unqualified type, the copy/move operation
3351 // can be omitted by constructing the temporary object
3352 // directly into the target of the omitted copy/move
3353 //
3354 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003355 // elision for return statements and throw expressions are handled as part
3356 // of constructor initialization, while copy elision for exception handlers
3357 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003358 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003359 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003360 switch (Entity.getKind()) {
3361 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003362 Loc = Entity.getReturnLoc();
3363 break;
3364
3365 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003366 Loc = Entity.getThrowLoc();
3367 break;
3368
3369 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003370 Loc = Entity.getDecl()->getLocation();
3371 break;
3372
Anders Carlsson0bd52402010-01-24 00:19:41 +00003373 case InitializedEntity::EK_ArrayElement:
3374 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003375 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003376 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003377 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003378 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003379 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003380 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003381 Loc = CurInitExpr->getLocStart();
3382 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003383 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003384
3385 // Make sure that the type we are copying is complete.
3386 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3387 return move(CurInit);
3388
Douglas Gregore1314a62009-12-18 05:02:21 +00003389 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003390 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003391 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003392 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003393 Con != ConEnd; ++Con) {
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003394 // Only consider copy constructors and constructor templates.
3395 CXXConstructorDecl *Constructor = 0;
3396
3397 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
3398 // Handle copy constructors, only.
3399 if (!Constructor || Constructor->isInvalidDecl() ||
3400 !Constructor->isCopyConstructor() ||
3401 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
3402 continue;
3403
3404 DeclAccessPair FoundDecl
3405 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3406 S.AddOverloadCandidate(Constructor, FoundDecl,
3407 &CurInitExpr, 1, CandidateSet);
3408 continue;
3409 }
3410
3411 // Handle constructor templates.
3412 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3413 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003414 continue;
John McCalla0296f72010-03-19 07:35:19 +00003415
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003416 Constructor = cast<CXXConstructorDecl>(
3417 ConstructorTmpl->getTemplatedDecl());
3418 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
3419 continue;
3420
3421 // FIXME: Do we need to limit this to copy-constructor-like
3422 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003423 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003424 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3425 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3426 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003427 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003428
3429 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00003430 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003431 case OR_Success:
3432 break;
3433
3434 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003435 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3436 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3437 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003438 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003439 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003440 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003441 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003442 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003443 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003444
3445 case OR_Ambiguous:
3446 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003447 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003448 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003449 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003450 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003451
3452 case OR_Deleted:
3453 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003454 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003455 << CurInitExpr->getSourceRange();
3456 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3457 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003458 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003459 }
3460
Douglas Gregor5ab11652010-04-17 22:01:05 +00003461 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003462 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003463 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003464
Anders Carlssona01874b2010-04-21 18:47:17 +00003465 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003466 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003467
3468 if (IsExtraneousCopy) {
3469 // If this is a totally extraneous copy for C++03 reference
3470 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003471 // expression. We don't generate an (elided) copy operation here
3472 // because doing so would require us to pass down a flag to avoid
3473 // infinite recursion, where each step adds another extraneous,
3474 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003475
Douglas Gregor30b52772010-04-18 07:57:34 +00003476 // Instantiate the default arguments of any extra parameters in
3477 // the selected copy constructor, as if we were going to create a
3478 // proper call to the copy constructor.
3479 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3480 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3481 if (S.RequireCompleteType(Loc, Parm->getType(),
3482 S.PDiag(diag::err_call_incomplete_argument)))
3483 break;
3484
3485 // Build the default argument expression; we don't actually care
3486 // if this succeeds or not, because this routine will complain
3487 // if there was a problem.
3488 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3489 }
3490
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003491 return S.Owned(CurInitExpr);
3492 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003493
3494 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003495 // constructor call (we might have derived-to-base conversions, or
3496 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003497 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003498 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003499 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003500
Douglas Gregord0ace022010-04-25 00:55:24 +00003501 // Actually perform the constructor call.
3502 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003503 move_arg(ConstructorArgs),
3504 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003505 CXXConstructExpr::CK_Complete,
3506 SourceRange());
Douglas Gregord0ace022010-04-25 00:55:24 +00003507
3508 // If we're supposed to bind temporaries, do so.
3509 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3510 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3511 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003512}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003513
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003514void InitializationSequence::PrintInitLocationNote(Sema &S,
3515 const InitializedEntity &Entity) {
3516 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3517 if (Entity.getDecl()->getLocation().isInvalid())
3518 return;
3519
3520 if (Entity.getDecl()->getDeclName())
3521 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3522 << Entity.getDecl()->getDeclName();
3523 else
3524 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3525 }
3526}
3527
John McCalldadc5752010-08-24 06:29:42 +00003528ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003529InitializationSequence::Perform(Sema &S,
3530 const InitializedEntity &Entity,
3531 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003532 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003533 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003534 if (SequenceKind == FailedSequence) {
3535 unsigned NumArgs = Args.size();
3536 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003537 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003538 }
3539
3540 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003541 // If the declaration is a non-dependent, incomplete array type
3542 // that has an initializer, then its type will be completed once
3543 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003544 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003545 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003546 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003547 if (const IncompleteArrayType *ArrayT
3548 = S.Context.getAsIncompleteArrayType(DeclType)) {
3549 // FIXME: We don't currently have the ability to accurately
3550 // compute the length of an initializer list without
3551 // performing full type-checking of the initializer list
3552 // (since we have to determine where braces are implicitly
3553 // introduced and such). So, we fall back to making the array
3554 // type a dependently-sized array type with no specified
3555 // bound.
3556 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3557 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003558
Douglas Gregor51e77d52009-12-10 17:56:55 +00003559 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003560 if (DeclaratorDecl *DD = Entity.getDecl()) {
3561 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3562 TypeLoc TL = TInfo->getTypeLoc();
3563 if (IncompleteArrayTypeLoc *ArrayLoc
3564 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3565 Brackets = ArrayLoc->getBracketsRange();
3566 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003567 }
3568
3569 *ResultType
3570 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3571 /*NumElts=*/0,
3572 ArrayT->getSizeModifier(),
3573 ArrayT->getIndexTypeCVRQualifiers(),
3574 Brackets);
3575 }
3576
3577 }
3578 }
3579
Eli Friedmana553d4a2009-12-22 02:35:53 +00003580 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003581 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003582
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003583 if (Args.size() == 0)
3584 return S.Owned((Expr *)0);
3585
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003586 unsigned NumArgs = Args.size();
3587 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3588 SourceLocation(),
3589 (Expr **)Args.release(),
3590 NumArgs,
3591 SourceLocation()));
3592 }
3593
Douglas Gregor85dabae2009-12-16 01:38:02 +00003594 if (SequenceKind == NoInitialization)
3595 return S.Owned((Expr *)0);
3596
Douglas Gregor1b303932009-12-22 15:35:07 +00003597 QualType DestType = Entity.getType().getNonReferenceType();
3598 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003599 // the same as Entity.getDecl()->getType() in cases involving type merging,
3600 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003601 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003602 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003603 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604
John McCalldadc5752010-08-24 06:29:42 +00003605 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003606
3607 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3608
3609 // For initialization steps that start with a single initializer,
3610 // grab the only argument out the Args and place it into the "current"
3611 // initializer.
3612 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003613 case SK_ResolveAddressOfOverloadedFunction:
3614 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003615 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003616 case SK_CastDerivedToBaseLValue:
3617 case SK_BindReference:
3618 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003619 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003620 case SK_UserConversion:
3621 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003622 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003623 case SK_QualificationConversionRValue:
3624 case SK_ConversionSequence:
3625 case SK_ListInitialization:
3626 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003627 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003628 case SK_ObjCObjectConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00003629 assert(Args.size() == 1);
John McCallc3007a22010-10-26 07:05:15 +00003630 CurInit = ExprResult(Args.get()[0]);
Douglas Gregore1314a62009-12-18 05:02:21 +00003631 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003632 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003633 break;
3634
3635 case SK_ConstructorInitialization:
3636 case SK_ZeroInitialization:
3637 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003638 }
3639
3640 // Walk through the computed steps for the initialization sequence,
3641 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003642 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003643 for (step_iterator Step = step_begin(), StepEnd = step_end();
3644 Step != StepEnd; ++Step) {
3645 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003646 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003647
3648 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003649 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003650
3651 switch (Step->Kind) {
3652 case SK_ResolveAddressOfOverloadedFunction:
3653 // Overload resolution determined which function invoke; update the
3654 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003655 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003656 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003657 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003658 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003659 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003660 break;
3661
3662 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003663 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003664 case SK_CastDerivedToBaseLValue: {
3665 // We have a derived-to-base cast that produces either an rvalue or an
3666 // lvalue. Perform that cast.
3667
John McCallcf142162010-08-07 06:22:56 +00003668 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003670 // Casts to inaccessible base classes are allowed with C-style casts.
3671 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3672 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3673 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003674 CurInitExpr->getSourceRange(),
3675 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003676 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003677
Douglas Gregor88d292c2010-05-13 16:44:06 +00003678 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3679 QualType T = SourceType;
3680 if (const PointerType *Pointer = T->getAs<PointerType>())
3681 T = Pointer->getPointeeType();
3682 if (const RecordType *RecordTy = T->getAs<RecordType>())
3683 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3684 cast<CXXRecordDecl>(RecordTy->getDecl()));
3685 }
3686
John McCall2536c6d2010-08-25 10:28:54 +00003687 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003688 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003689 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003690 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003691 VK_XValue :
3692 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003693 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3694 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003695 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003696 CurInit.get(),
3697 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003698 break;
3699 }
3700
3701 case SK_BindReference:
3702 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3703 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3704 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003705 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003706 << BitField->getDeclName()
3707 << CurInitExpr->getSourceRange();
3708 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003709 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003710 }
Anders Carlssona91be642010-01-29 02:47:33 +00003711
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003712 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003713 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003714 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3715 << Entity.getType().isVolatileQualified()
3716 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003717 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003718 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003719 }
3720
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003721 // Reference binding does not have any corresponding ASTs.
3722
3723 // Check exception specifications
3724 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003725 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003726
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003727 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003728
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003729 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003730 // Reference binding does not have any corresponding ASTs.
3731
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003732 // Check exception specifications
3733 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003734 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003735
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003736 break;
3737
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003738 case SK_ExtraneousCopyToTemporary:
3739 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3740 /*IsExtraneousCopy=*/true);
3741 break;
3742
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003743 case SK_UserConversion: {
3744 // We have a user-defined conversion that invokes either a constructor
3745 // or a conversion function.
John McCalle3027922010-08-25 11:45:40 +00003746 CastKind CastKind = CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003747 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003748 FunctionDecl *Fn = Step->Function.Function;
3749 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003750 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003751 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003752 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003753 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003754 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003755 SourceLocation Loc = CurInitExpr->getLocStart();
3756 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003757
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003758 // Determine the arguments required to actually perform the constructor
3759 // call.
3760 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00003761 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003762 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003763 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003764
3765 // Build the an expression that constructs a temporary.
3766 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003767 move_arg(ConstructorArgs),
3768 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003769 CXXConstructExpr::CK_Complete,
3770 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003771 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003772 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003773
Anders Carlssona01874b2010-04-21 18:47:17 +00003774 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003775 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003776 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003777
John McCalle3027922010-08-25 11:45:40 +00003778 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003779 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3780 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3781 S.IsDerivedFrom(SourceType, Class))
3782 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003783
3784 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003785 } else {
3786 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003787 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003788 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003789 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003790 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003791 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003792
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003793 // FIXME: Should we move this initialization into a separate
3794 // derived-to-base conversion? I believe the answer is "no", because
3795 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003796 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003797 FoundFn, Conversion))
John McCallfaf5fb42010-08-26 23:41:50 +00003798 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003799
3800 // Do a little dance to make sure that CurInit has the proper
3801 // pointer.
3802 CurInit.release();
3803
3804 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003805 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3806 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003807 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003808 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003809
John McCalle3027922010-08-25 11:45:40 +00003810 CastKind = CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003811
3812 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003813 }
3814
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003815 bool RequiresCopy = !IsCopy &&
3816 getKind() != InitializationSequence::ReferenceBinding;
3817 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003818 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003819 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3820 CurInitExpr = static_cast<Expr *>(CurInit.get());
3821 QualType T = CurInitExpr->getType();
3822 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003823 CXXDestructorDecl *Destructor
3824 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003825 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3826 S.PDiag(diag::err_access_dtor_temp) << T);
3827 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003828 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00003829 }
3830 }
3831
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003832 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003833 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003834 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3835 CurInitExpr->getType(),
3836 CastKind, CurInitExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00003837 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003838
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003839 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003840 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3841 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003842
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003843 break;
3844 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003845
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003846 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003847 case SK_QualificationConversionXValue:
3848 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003849 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003850 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003851 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003852 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003853 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003854 VK_XValue :
3855 VK_RValue);
John McCalle3027922010-08-25 11:45:40 +00003856 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003857 CurInit.release();
3858 CurInit = S.Owned(CurInitExpr);
3859 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003860 }
3861
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003862 case SK_ConversionSequence: {
3863 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3864
3865 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3866 Sema::AA_Converting, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003867 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003868
3869 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003870 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003871 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003872 }
3873
Douglas Gregor51e77d52009-12-10 17:56:55 +00003874 case SK_ListInitialization: {
3875 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3876 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003877 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003878 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003879
3880 CurInit.release();
3881 CurInit = S.Owned(InitList);
3882 break;
3883 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003884
3885 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003886 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003887 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003888 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003889
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003890 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003891 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003892 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3893 ? Kind.getEqualLoc()
3894 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003895
3896 if (Kind.getKind() == InitializationKind::IK_Default) {
3897 // Force even a trivial, implicit default constructor to be
3898 // semantically checked. We do this explicitly because we don't build
3899 // the definition for completely trivial constructors.
3900 CXXRecordDecl *ClassDecl = Constructor->getParent();
3901 assert(ClassDecl && "No parent class for constructor.");
3902 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3903 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3904 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3905 }
3906
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003907 // Determine the arguments required to actually perform the constructor
3908 // call.
3909 if (S.CompleteConstructorCall(Constructor, move(Args),
3910 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003911 return ExprError();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003912
Chandler Carruthc9262402010-08-23 07:55:51 +00003913
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003914 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003915 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003916 (Kind.getKind() == InitializationKind::IK_Direct ||
3917 Kind.getKind() == InitializationKind::IK_Value)) {
3918 // An explicitly-constructed temporary, e.g., X(1, 2).
3919 unsigned NumExprs = ConstructorArgs.size();
3920 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003921 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003922 S.DiagnoseUseOfDecl(Constructor, Loc);
3923
Douglas Gregor2b88c112010-09-08 00:15:04 +00003924 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3925 if (!TSInfo)
3926 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3927
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003928 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3929 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00003930 TSInfo,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003931 Exprs,
3932 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00003933 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00003934 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003935 } else {
3936 CXXConstructExpr::ConstructionKind ConstructKind =
3937 CXXConstructExpr::CK_Complete;
3938
3939 if (Entity.getKind() == InitializedEntity::EK_Base) {
3940 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3941 CXXConstructExpr::CK_VirtualBase :
3942 CXXConstructExpr::CK_NonVirtualBase;
3943 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003944
Chandler Carruth01718152010-10-25 08:47:36 +00003945 // Only get the parenthesis range if it is a direct construction.
3946 SourceRange parenRange =
3947 Kind.getKind() == InitializationKind::IK_Direct ?
3948 Kind.getParenRange() : SourceRange();
3949
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003950 // If the entity allows NRVO, mark the construction as elidable
3951 // unconditionally.
3952 if (Entity.allowsNRVO())
3953 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3954 Constructor, /*Elidable=*/true,
3955 move_arg(ConstructorArgs),
3956 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00003957 ConstructKind,
3958 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003959 else
3960 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3961 Constructor,
3962 move_arg(ConstructorArgs),
3963 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00003964 ConstructKind,
3965 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003966 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003967 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003968 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003969
3970 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003971 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003972 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003973 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003974
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003975 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003976 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003977
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003978 break;
3979 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003980
3981 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003982 step_iterator NextStep = Step;
3983 ++NextStep;
3984 if (NextStep != StepEnd &&
3985 NextStep->Kind == SK_ConstructorInitialization) {
3986 // The need for zero-initialization is recorded directly into
3987 // the call to the object's constructor within the next step.
3988 ConstructorInitRequiresZeroInit = true;
3989 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3990 S.getLangOptions().CPlusPlus &&
3991 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00003992 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3993 if (!TSInfo)
3994 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
3995 Kind.getRange().getBegin());
3996
3997 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
3998 TSInfo->getType().getNonLValueExprType(S.Context),
3999 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004000 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004001 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004002 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004003 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004004 break;
4005 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004006
4007 case SK_CAssignment: {
4008 QualType SourceType = CurInitExpr->getType();
4009 Sema::AssignConvertType ConvTy =
4010 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00004011
4012 // If this is a call, allow conversion to a transparent union.
4013 if (ConvTy != Sema::Compatible &&
4014 Entity.getKind() == InitializedEntity::EK_Parameter &&
4015 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4016 == Sema::Compatible)
4017 ConvTy = Sema::Compatible;
4018
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004019 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004020 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4021 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004022 CurInitExpr,
4023 getAssignmentAction(Entity),
4024 &Complained)) {
4025 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004026 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004027 } else if (Complained)
4028 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004029
4030 CurInit.release();
4031 CurInit = S.Owned(CurInitExpr);
4032 break;
4033 }
Eli Friedman78275202009-12-19 08:11:05 +00004034
4035 case SK_StringInit: {
4036 QualType Ty = Step->Type;
4037 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
4038 break;
4039 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004040
4041 case SK_ObjCObjectConversion:
4042 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004043 CK_ObjCObjectLValueCast,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004044 S.CastCategory(CurInitExpr));
4045 CurInit.release();
4046 CurInit = S.Owned(CurInitExpr);
4047 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004048 }
4049 }
4050
4051 return move(CurInit);
4052}
4053
4054//===----------------------------------------------------------------------===//
4055// Diagnose initialization failures
4056//===----------------------------------------------------------------------===//
4057bool InitializationSequence::Diagnose(Sema &S,
4058 const InitializedEntity &Entity,
4059 const InitializationKind &Kind,
4060 Expr **Args, unsigned NumArgs) {
4061 if (SequenceKind != FailedSequence)
4062 return false;
4063
Douglas Gregor1b303932009-12-22 15:35:07 +00004064 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004065 switch (Failure) {
4066 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004067 // FIXME: Customize for the initialized entity?
4068 if (NumArgs == 0)
4069 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4070 << DestType.getNonReferenceType();
4071 else // FIXME: diagnostic below could be better!
4072 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4073 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004074 break;
4075
4076 case FK_ArrayNeedsInitList:
4077 case FK_ArrayNeedsInitListOrStringLiteral:
4078 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4079 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4080 break;
4081
John McCall16df1e52010-03-30 21:47:33 +00004082 case FK_AddressOfOverloadFailed: {
4083 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004084 S.ResolveAddressOfOverloadedFunction(Args[0],
4085 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004086 true,
4087 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004088 break;
John McCall16df1e52010-03-30 21:47:33 +00004089 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004090
4091 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004092 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004093 switch (FailedOverloadResult) {
4094 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004095 if (Failure == FK_UserConversionOverloadFailed)
4096 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4097 << Args[0]->getType() << DestType
4098 << Args[0]->getSourceRange();
4099 else
4100 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4101 << DestType << Args[0]->getType()
4102 << Args[0]->getSourceRange();
4103
John McCall5c32be02010-08-24 20:38:10 +00004104 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004105 break;
4106
4107 case OR_No_Viable_Function:
4108 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4109 << Args[0]->getType() << DestType.getNonReferenceType()
4110 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004111 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004112 break;
4113
4114 case OR_Deleted: {
4115 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4116 << Args[0]->getType() << DestType.getNonReferenceType()
4117 << Args[0]->getSourceRange();
4118 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004119 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004120 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4121 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004122 if (Ovl == OR_Deleted) {
4123 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4124 << Best->Function->isDeleted();
4125 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004126 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004127 }
4128 break;
4129 }
4130
4131 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004132 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004133 break;
4134 }
4135 break;
4136
4137 case FK_NonConstLValueReferenceBindingToTemporary:
4138 case FK_NonConstLValueReferenceBindingToUnrelated:
4139 S.Diag(Kind.getLocation(),
4140 Failure == FK_NonConstLValueReferenceBindingToTemporary
4141 ? diag::err_lvalue_reference_bind_to_temporary
4142 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004143 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004144 << DestType.getNonReferenceType()
4145 << Args[0]->getType()
4146 << Args[0]->getSourceRange();
4147 break;
4148
4149 case FK_RValueReferenceBindingToLValue:
4150 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4151 << Args[0]->getSourceRange();
4152 break;
4153
4154 case FK_ReferenceInitDropsQualifiers:
4155 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4156 << DestType.getNonReferenceType()
4157 << Args[0]->getType()
4158 << Args[0]->getSourceRange();
4159 break;
4160
4161 case FK_ReferenceInitFailed:
4162 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4163 << DestType.getNonReferenceType()
4164 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4165 << Args[0]->getType()
4166 << Args[0]->getSourceRange();
4167 break;
4168
4169 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004170 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4171 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004172 << DestType
4173 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4174 << Args[0]->getType()
4175 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004176 break;
4177
4178 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004179 SourceRange R;
4180
4181 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004182 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004183 InitList->getLocEnd());
Douglas Gregor8ec51732010-09-08 21:40:08 +00004184 else
4185 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004186
Douglas Gregor8ec51732010-09-08 21:40:08 +00004187 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4188 if (Kind.isCStyleOrFunctionalCast())
4189 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4190 << R;
4191 else
4192 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4193 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004194 break;
4195 }
4196
4197 case FK_ReferenceBindingToInitList:
4198 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4199 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4200 break;
4201
4202 case FK_InitListBadDestinationType:
4203 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4204 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4205 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004206
4207 case FK_ConstructorOverloadFailed: {
4208 SourceRange ArgsRange;
4209 if (NumArgs)
4210 ArgsRange = SourceRange(Args[0]->getLocStart(),
4211 Args[NumArgs - 1]->getLocEnd());
4212
4213 // FIXME: Using "DestType" for the entity we're printing is probably
4214 // bad.
4215 switch (FailedOverloadResult) {
4216 case OR_Ambiguous:
4217 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4218 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004219 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4220 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004221 break;
4222
4223 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004224 if (Kind.getKind() == InitializationKind::IK_Default &&
4225 (Entity.getKind() == InitializedEntity::EK_Base ||
4226 Entity.getKind() == InitializedEntity::EK_Member) &&
4227 isa<CXXConstructorDecl>(S.CurContext)) {
4228 // This is implicit default initialization of a member or
4229 // base within a constructor. If no viable function was
4230 // found, notify the user that she needs to explicitly
4231 // initialize this base/member.
4232 CXXConstructorDecl *Constructor
4233 = cast<CXXConstructorDecl>(S.CurContext);
4234 if (Entity.getKind() == InitializedEntity::EK_Base) {
4235 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4236 << Constructor->isImplicit()
4237 << S.Context.getTypeDeclType(Constructor->getParent())
4238 << /*base=*/0
4239 << Entity.getType();
4240
4241 RecordDecl *BaseDecl
4242 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4243 ->getDecl();
4244 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4245 << S.Context.getTagDeclType(BaseDecl);
4246 } else {
4247 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4248 << Constructor->isImplicit()
4249 << S.Context.getTypeDeclType(Constructor->getParent())
4250 << /*member=*/1
4251 << Entity.getName();
4252 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4253
4254 if (const RecordType *Record
4255 = Entity.getType()->getAs<RecordType>())
4256 S.Diag(Record->getDecl()->getLocation(),
4257 diag::note_previous_decl)
4258 << S.Context.getTagDeclType(Record->getDecl());
4259 }
4260 break;
4261 }
4262
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004263 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4264 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004265 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004266 break;
4267
4268 case OR_Deleted: {
4269 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4270 << true << DestType << ArgsRange;
4271 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004272 OverloadingResult Ovl
4273 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004274 if (Ovl == OR_Deleted) {
4275 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4276 << Best->Function->isDeleted();
4277 } else {
4278 llvm_unreachable("Inconsistent overload resolution?");
4279 }
4280 break;
4281 }
4282
4283 case OR_Success:
4284 llvm_unreachable("Conversion did not fail!");
4285 break;
4286 }
4287 break;
4288 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004289
4290 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004291 if (Entity.getKind() == InitializedEntity::EK_Member &&
4292 isa<CXXConstructorDecl>(S.CurContext)) {
4293 // This is implicit default-initialization of a const member in
4294 // a constructor. Complain that it needs to be explicitly
4295 // initialized.
4296 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4297 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4298 << Constructor->isImplicit()
4299 << S.Context.getTypeDeclType(Constructor->getParent())
4300 << /*const=*/1
4301 << Entity.getName();
4302 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4303 << Entity.getName();
4304 } else {
4305 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4306 << DestType << (bool)DestType->getAs<RecordType>();
4307 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004308 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004309
4310 case FK_Incomplete:
4311 S.RequireCompleteType(Kind.getLocation(), DestType,
4312 diag::err_init_incomplete_type);
4313 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004314 }
4315
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004316 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004317 return true;
4318}
Douglas Gregore1314a62009-12-18 05:02:21 +00004319
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004320void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4321 switch (SequenceKind) {
4322 case FailedSequence: {
4323 OS << "Failed sequence: ";
4324 switch (Failure) {
4325 case FK_TooManyInitsForReference:
4326 OS << "too many initializers for reference";
4327 break;
4328
4329 case FK_ArrayNeedsInitList:
4330 OS << "array requires initializer list";
4331 break;
4332
4333 case FK_ArrayNeedsInitListOrStringLiteral:
4334 OS << "array requires initializer list or string literal";
4335 break;
4336
4337 case FK_AddressOfOverloadFailed:
4338 OS << "address of overloaded function failed";
4339 break;
4340
4341 case FK_ReferenceInitOverloadFailed:
4342 OS << "overload resolution for reference initialization failed";
4343 break;
4344
4345 case FK_NonConstLValueReferenceBindingToTemporary:
4346 OS << "non-const lvalue reference bound to temporary";
4347 break;
4348
4349 case FK_NonConstLValueReferenceBindingToUnrelated:
4350 OS << "non-const lvalue reference bound to unrelated type";
4351 break;
4352
4353 case FK_RValueReferenceBindingToLValue:
4354 OS << "rvalue reference bound to an lvalue";
4355 break;
4356
4357 case FK_ReferenceInitDropsQualifiers:
4358 OS << "reference initialization drops qualifiers";
4359 break;
4360
4361 case FK_ReferenceInitFailed:
4362 OS << "reference initialization failed";
4363 break;
4364
4365 case FK_ConversionFailed:
4366 OS << "conversion failed";
4367 break;
4368
4369 case FK_TooManyInitsForScalar:
4370 OS << "too many initializers for scalar";
4371 break;
4372
4373 case FK_ReferenceBindingToInitList:
4374 OS << "referencing binding to initializer list";
4375 break;
4376
4377 case FK_InitListBadDestinationType:
4378 OS << "initializer list for non-aggregate, non-scalar type";
4379 break;
4380
4381 case FK_UserConversionOverloadFailed:
4382 OS << "overloading failed for user-defined conversion";
4383 break;
4384
4385 case FK_ConstructorOverloadFailed:
4386 OS << "constructor overloading failed";
4387 break;
4388
4389 case FK_DefaultInitOfConst:
4390 OS << "default initialization of a const variable";
4391 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004392
4393 case FK_Incomplete:
4394 OS << "initialization of incomplete type";
4395 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004396 }
4397 OS << '\n';
4398 return;
4399 }
4400
4401 case DependentSequence:
4402 OS << "Dependent sequence: ";
4403 return;
4404
4405 case UserDefinedConversion:
4406 OS << "User-defined conversion sequence: ";
4407 break;
4408
4409 case ConstructorInitialization:
4410 OS << "Constructor initialization sequence: ";
4411 break;
4412
4413 case ReferenceBinding:
4414 OS << "Reference binding: ";
4415 break;
4416
4417 case ListInitialization:
4418 OS << "List initialization: ";
4419 break;
4420
4421 case ZeroInitialization:
4422 OS << "Zero initialization\n";
4423 return;
4424
4425 case NoInitialization:
4426 OS << "No initialization\n";
4427 return;
4428
4429 case StandardConversion:
4430 OS << "Standard conversion: ";
4431 break;
4432
4433 case CAssignment:
4434 OS << "C assignment: ";
4435 break;
4436
4437 case StringInit:
4438 OS << "String initialization: ";
4439 break;
4440 }
4441
4442 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4443 if (S != step_begin()) {
4444 OS << " -> ";
4445 }
4446
4447 switch (S->Kind) {
4448 case SK_ResolveAddressOfOverloadedFunction:
4449 OS << "resolve address of overloaded function";
4450 break;
4451
4452 case SK_CastDerivedToBaseRValue:
4453 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4454 break;
4455
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004456 case SK_CastDerivedToBaseXValue:
4457 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4458 break;
4459
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004460 case SK_CastDerivedToBaseLValue:
4461 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4462 break;
4463
4464 case SK_BindReference:
4465 OS << "bind reference to lvalue";
4466 break;
4467
4468 case SK_BindReferenceToTemporary:
4469 OS << "bind reference to a temporary";
4470 break;
4471
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004472 case SK_ExtraneousCopyToTemporary:
4473 OS << "extraneous C++03 copy to temporary";
4474 break;
4475
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004476 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004477 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004478 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004479
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004480 case SK_QualificationConversionRValue:
4481 OS << "qualification conversion (rvalue)";
4482
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004483 case SK_QualificationConversionXValue:
4484 OS << "qualification conversion (xvalue)";
4485
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004486 case SK_QualificationConversionLValue:
4487 OS << "qualification conversion (lvalue)";
4488 break;
4489
4490 case SK_ConversionSequence:
4491 OS << "implicit conversion sequence (";
4492 S->ICS->DebugPrint(); // FIXME: use OS
4493 OS << ")";
4494 break;
4495
4496 case SK_ListInitialization:
4497 OS << "list initialization";
4498 break;
4499
4500 case SK_ConstructorInitialization:
4501 OS << "constructor initialization";
4502 break;
4503
4504 case SK_ZeroInitialization:
4505 OS << "zero initialization";
4506 break;
4507
4508 case SK_CAssignment:
4509 OS << "C assignment";
4510 break;
4511
4512 case SK_StringInit:
4513 OS << "string initialization";
4514 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004515
4516 case SK_ObjCObjectConversion:
4517 OS << "Objective-C object conversion";
4518 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004519 }
4520 }
4521}
4522
4523void InitializationSequence::dump() const {
4524 dump(llvm::errs());
4525}
4526
Douglas Gregore1314a62009-12-18 05:02:21 +00004527//===----------------------------------------------------------------------===//
4528// Initialization helper functions
4529//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004530ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004531Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4532 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004533 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004534 if (Init.isInvalid())
4535 return ExprError();
4536
4537 Expr *InitE = (Expr *)Init.get();
4538 assert(InitE && "No initialization expression?");
4539
4540 if (EqualLoc.isInvalid())
4541 EqualLoc = InitE->getLocStart();
4542
4543 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4544 EqualLoc);
4545 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4546 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004547 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004548}