blob: 4e4558479aae6c6d896209cffca8ea215404f887 [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));
726 IList->setInit(Index, 0);
Douglas Gregord14247a2009-01-30 22:09:00 +0000727 hadError = true;
728 ++Index;
729 ++StructuredIndex;
730 }
731 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000732}
733
Anders Carlsson6cabf312010-01-23 23:23:01 +0000734void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000735 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000736 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000737 InitListExpr *StructuredList,
738 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000739 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000740 Expr *expr = IList->getInit(Index);
Eli Friedmandf239252010-08-14 03:14:53 +0000741 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
742 SemaRef.Diag(SubIList->getLocStart(),
743 diag::warn_many_braces_around_scalar_init)
744 << SubIList->getSourceRange();
745
746 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
747 StructuredIndex);
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000748 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000749 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000750 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000751 diag::err_designator_for_scalar_init)
752 << DeclType << expr->getSourceRange();
753 hadError = true;
754 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000755 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000756 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000757 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000758
John McCalldadc5752010-08-24 06:29:42 +0000759 ExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000760 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
761 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000762
Chandler Carruthdfe198b2010-02-13 07:23:01 +0000763 Expr *ResultExpr = 0;
Anders Carlsson26d05642010-01-23 18:35:41 +0000764
765 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000766 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000767 else {
768 ResultExpr = Result.takeAs<Expr>();
769
770 if (ResultExpr != expr) {
771 // The type was promoted, update initializer list.
772 IList->setInit(Index, ResultExpr);
773 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000774 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000775 if (hadError)
776 ++StructuredIndex;
777 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000778 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000779 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000780 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000781 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000782 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000783 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000784 ++Index;
785 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000786 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000787 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000788}
789
Anders Carlsson6cabf312010-01-23 23:23:01 +0000790void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
791 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000792 unsigned &Index,
793 InitListExpr *StructuredList,
794 unsigned &StructuredIndex) {
795 if (Index < IList->getNumInits()) {
796 Expr *expr = IList->getInit(Index);
797 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000798 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000799 << DeclType << IList->getSourceRange();
800 hadError = true;
801 ++Index;
802 ++StructuredIndex;
803 return;
Mike Stump11289f42009-09-09 15:08:12 +0000804 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000805
John McCalldadc5752010-08-24 06:29:42 +0000806 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000807 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
808 SemaRef.Owned(expr));
809
810 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000811 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000812
813 expr = Result.takeAs<Expr>();
814 IList->setInit(Index, expr);
815
Douglas Gregord14247a2009-01-30 22:09:00 +0000816 if (hadError)
817 ++StructuredIndex;
818 else
819 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
820 ++Index;
821 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000822 // FIXME: It would be wonderful if we could point at the actual member. In
823 // general, it would be useful to pass location information down the stack,
824 // so that we know the location (or decl) of the "current object" being
825 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000826 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000827 diag::err_init_reference_member_uninitialized)
828 << DeclType
829 << IList->getSourceRange();
830 hadError = true;
831 ++Index;
832 ++StructuredIndex;
833 return;
834 }
835}
836
Anders Carlsson6cabf312010-01-23 23:23:01 +0000837void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000838 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000839 unsigned &Index,
840 InitListExpr *StructuredList,
841 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000842 if (Index >= IList->getNumInits())
843 return;
Mike Stump11289f42009-09-09 15:08:12 +0000844
John McCall6a16b2f2010-10-30 00:11:39 +0000845 const VectorType *VT = DeclType->getAs<VectorType>();
846 unsigned maxElements = VT->getNumElements();
847 unsigned numEltsInit = 0;
848 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000849
John McCall6a16b2f2010-10-30 00:11:39 +0000850 if (!SemaRef.getLangOptions().OpenCL) {
851 // If the initializing element is a vector, try to copy-initialize
852 // instead of breaking it apart (which is doomed to failure anyway).
853 Expr *Init = IList->getInit(Index);
854 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
855 ExprResult Result =
856 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
857 SemaRef.Owned(Init));
858
859 Expr *ResultExpr = 0;
860 if (Result.isInvalid())
861 hadError = true; // types weren't compatible.
862 else {
863 ResultExpr = Result.takeAs<Expr>();
Anders Carlsson6cabf312010-01-23 23:23:01 +0000864
John McCall6a16b2f2010-10-30 00:11:39 +0000865 if (ResultExpr != Init) {
866 // The type was promoted, update initializer list.
867 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000868 }
869 }
John McCall6a16b2f2010-10-30 00:11:39 +0000870 if (hadError)
871 ++StructuredIndex;
872 else
873 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
874 ++Index;
875 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000876 }
Mike Stump11289f42009-09-09 15:08:12 +0000877
John McCall6a16b2f2010-10-30 00:11:39 +0000878 InitializedEntity ElementEntity =
879 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
880
881 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
882 // Don't attempt to go past the end of the init list
883 if (Index >= IList->getNumInits())
884 break;
885
886 ElementEntity.setElementIndex(Index);
887 CheckSubElementType(ElementEntity, IList, elementType, Index,
888 StructuredList, StructuredIndex);
889 }
890 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000891 }
John McCall6a16b2f2010-10-30 00:11:39 +0000892
893 InitializedEntity ElementEntity =
894 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
895
896 // OpenCL initializers allows vectors to be constructed from vectors.
897 for (unsigned i = 0; i < maxElements; ++i) {
898 // Don't attempt to go past the end of the init list
899 if (Index >= IList->getNumInits())
900 break;
901
902 ElementEntity.setElementIndex(Index);
903
904 QualType IType = IList->getInit(Index)->getType();
905 if (!IType->isVectorType()) {
906 CheckSubElementType(ElementEntity, IList, elementType, Index,
907 StructuredList, StructuredIndex);
908 ++numEltsInit;
909 } else {
910 QualType VecType;
911 const VectorType *IVT = IType->getAs<VectorType>();
912 unsigned numIElts = IVT->getNumElements();
913
914 if (IType->isExtVectorType())
915 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
916 else
917 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
918 IVT->getAltiVecSpecific());
919 CheckSubElementType(ElementEntity, IList, VecType, Index,
920 StructuredList, StructuredIndex);
921 numEltsInit += numIElts;
922 }
923 }
924
925 // OpenCL requires all elements to be initialized.
926 if (numEltsInit != maxElements)
927 if (SemaRef.getLangOptions().OpenCL)
928 SemaRef.Diag(IList->getSourceRange().getBegin(),
929 diag::err_vector_incorrect_num_initializers)
930 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000931}
932
Anders Carlsson6cabf312010-01-23 23:23:01 +0000933void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000934 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000935 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000936 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000937 unsigned &Index,
938 InitListExpr *StructuredList,
939 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000940 // Check for the special-case of initializing an array with a string.
941 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000942 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
943 SemaRef.Context)) {
944 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000945 // We place the string literal directly into the resulting
946 // initializer list. This is the only place where the structure
947 // of the structured initializer list doesn't match exactly,
948 // because doing so would involve allocating one character
949 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000950 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000951 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000952 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000953 return;
954 }
955 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000956 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000957 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000958 // Check for VLAs; in standard C it would be possible to check this
959 // earlier, but I don't know where clang accepts VLAs (gcc accepts
960 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000961 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000962 diag::err_variable_object_no_init)
963 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000964 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000965 ++Index;
966 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000967 return;
968 }
969
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000970 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000971 llvm::APSInt maxElements(elementIndex.getBitWidth(),
972 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000973 bool maxElementsKnown = false;
974 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000975 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000976 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000977 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000978 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000979 maxElementsKnown = true;
980 }
981
Chris Lattnerb0912a52009-02-24 22:50:46 +0000982 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000983 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000984 while (Index < IList->getNumInits()) {
985 Expr *Init = IList->getInit(Index);
986 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000987 // If we're not the subobject that matches up with the '{' for
988 // the designator, we shouldn't be handling the
989 // designator. Return immediately.
990 if (!SubobjectIsDesignatorContext)
991 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000992
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000993 // Handle this designated initializer. elementIndex will be
994 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000995 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000996 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000997 StructuredList, StructuredIndex, true,
998 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000999 hadError = true;
1000 continue;
1001 }
1002
Douglas Gregor033d1252009-01-23 16:54:12 +00001003 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1004 maxElements.extend(elementIndex.getBitWidth());
1005 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1006 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001007 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001008
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001009 // If the array is of incomplete type, keep track of the number of
1010 // elements in the initializer.
1011 if (!maxElementsKnown && elementIndex > maxElements)
1012 maxElements = elementIndex;
1013
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001014 continue;
1015 }
1016
1017 // If we know the maximum number of elements, and we've already
1018 // hit it, stop consuming elements in the initializer list.
1019 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001020 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001021
Anders Carlsson6cabf312010-01-23 23:23:01 +00001022 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001023 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001024 Entity);
1025 // Check this element.
1026 CheckSubElementType(ElementEntity, IList, elementType, Index,
1027 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001028 ++elementIndex;
1029
1030 // If the array is of incomplete type, keep track of the number of
1031 // elements in the initializer.
1032 if (!maxElementsKnown && elementIndex > maxElements)
1033 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001034 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001035 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001036 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001037 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001038 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001039 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001040 // Sizing an array implicitly to zero is not allowed by ISO C,
1041 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001042 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001043 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001044 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001045
Mike Stump11289f42009-09-09 15:08:12 +00001046 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001047 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001048 }
1049}
1050
Anders Carlsson6cabf312010-01-23 23:23:01 +00001051void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001052 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001053 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001054 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001055 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001056 unsigned &Index,
1057 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001058 unsigned &StructuredIndex,
1059 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001061
Eli Friedman23a9e312008-05-19 19:16:24 +00001062 // If the record is invalid, some of it's members are invalid. To avoid
1063 // confusion, we forgo checking the intializer for the entire record.
1064 if (structDecl->isInvalidDecl()) {
1065 hadError = true;
1066 return;
Mike Stump11289f42009-09-09 15:08:12 +00001067 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001068
1069 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1070 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001071 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001072 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001073 Field != FieldEnd; ++Field) {
1074 if (Field->getDeclName()) {
1075 StructuredList->setInitializedFieldInUnion(*Field);
1076 break;
1077 }
1078 }
1079 return;
1080 }
1081
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001082 // If structDecl is a forward declaration, this loop won't do
1083 // anything except look at designated initializers; That's okay,
1084 // because an error should get printed out elsewhere. It might be
1085 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001086 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001087 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001088 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001089 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001090 while (Index < IList->getNumInits()) {
1091 Expr *Init = IList->getInit(Index);
1092
1093 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001094 // If we're not the subobject that matches up with the '{' for
1095 // the designator, we shouldn't be handling the
1096 // designator. Return immediately.
1097 if (!SubobjectIsDesignatorContext)
1098 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001099
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001100 // Handle this designated initializer. Field will be updated to
1101 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001102 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001103 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001104 StructuredList, StructuredIndex,
1105 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001106 hadError = true;
1107
Douglas Gregora9add4e2009-02-12 19:00:39 +00001108 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001109
1110 // Disable check for missing fields when designators are used.
1111 // This matches gcc behaviour.
1112 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001113 continue;
1114 }
1115
1116 if (Field == FieldEnd) {
1117 // We've run out of fields. We're done.
1118 break;
1119 }
1120
Douglas Gregora9add4e2009-02-12 19:00:39 +00001121 // We've already initialized a member of a union. We're done.
1122 if (InitializedSomething && DeclType->isUnionType())
1123 break;
1124
Douglas Gregor91f84212008-12-11 16:49:14 +00001125 // If we've hit the flexible array member at the end, we're done.
1126 if (Field->getType()->isIncompleteArrayType())
1127 break;
1128
Douglas Gregor51695702009-01-29 16:53:55 +00001129 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001130 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001131 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001132 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001133 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001134
Anders Carlsson6cabf312010-01-23 23:23:01 +00001135 InitializedEntity MemberEntity =
1136 InitializedEntity::InitializeMember(*Field, &Entity);
1137 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1138 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001139 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001140
1141 if (DeclType->isUnionType()) {
1142 // Initialize the first field within the union.
1143 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001144 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001145
1146 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001147 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001148
John McCalle40b58e2010-03-11 19:32:38 +00001149 // Emit warnings for missing struct field initializers.
Douglas Gregor8fba4f22010-06-18 21:43:10 +00001150 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001151 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1152 // It is possible we have one or more unnamed bitfields remaining.
1153 // Find first (if any) named field and emit warning.
1154 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1155 it != end; ++it) {
1156 if (!it->isUnnamedBitfield()) {
1157 SemaRef.Diag(IList->getSourceRange().getEnd(),
1158 diag::warn_missing_field_initializers) << it->getName();
1159 break;
1160 }
1161 }
1162 }
1163
Mike Stump11289f42009-09-09 15:08:12 +00001164 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001165 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001166 return;
1167
1168 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001169 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001170 (!isa<InitListExpr>(IList->getInit(Index)) ||
1171 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001172 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001173 diag::err_flexible_array_init_nonempty)
1174 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001175 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001176 << *Field;
1177 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001178 ++Index;
1179 return;
1180 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001181 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001182 diag::ext_flexible_array_init)
1183 << IList->getInit(Index)->getSourceRange().getBegin();
1184 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1185 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001186 }
1187
Anders Carlsson6cabf312010-01-23 23:23:01 +00001188 InitializedEntity MemberEntity =
1189 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001190
Anders Carlsson6cabf312010-01-23 23:23:01 +00001191 if (isa<InitListExpr>(IList->getInit(Index)))
1192 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1193 StructuredList, StructuredIndex);
1194 else
1195 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001196 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001197}
Steve Narofff8ecff22008-05-01 22:18:59 +00001198
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001199/// \brief Similar to Sema::BuildAnonymousStructUnionMemberPath() but builds a
1200/// relative path and has strict checks.
1201static void BuildRelativeAnonymousStructUnionMemberPath(FieldDecl *Field,
1202 llvm::SmallVectorImpl<FieldDecl *> &Path,
1203 DeclContext *BaseDC) {
1204 Path.push_back(Field);
1205 for (DeclContext *Ctx = Field->getDeclContext();
1206 !Ctx->Equals(BaseDC);
1207 Ctx = Ctx->getParent()) {
1208 ValueDecl *AnonObject =
1209 cast<RecordDecl>(Ctx)->getAnonymousStructOrUnionObject();
1210 FieldDecl *AnonField = cast<FieldDecl>(AnonObject);
1211 Path.push_back(AnonField);
1212 }
1213}
1214
Douglas Gregord5846a12009-04-15 06:41:24 +00001215/// \brief Expand a field designator that refers to a member of an
1216/// anonymous struct or union into a series of field designators that
1217/// refers to the field within the appropriate subobject.
1218///
1219/// Field/FieldIndex will be updated to point to the (new)
1220/// currently-designated field.
1221static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001222 DesignatedInitExpr *DIE,
1223 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001224 FieldDecl *Field,
1225 RecordDecl::field_iterator &FieldIter,
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001226 unsigned &FieldIndex,
1227 DeclContext *BaseDC) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001228 typedef DesignatedInitExpr::Designator Designator;
1229
1230 // Build the path from the current object to the member of the
1231 // anonymous struct/union (backwards).
1232 llvm::SmallVector<FieldDecl *, 4> Path;
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001233 BuildRelativeAnonymousStructUnionMemberPath(Field, Path, BaseDC);
Mike Stump11289f42009-09-09 15:08:12 +00001234
Douglas Gregord5846a12009-04-15 06:41:24 +00001235 // Build the replacement designators.
1236 llvm::SmallVector<Designator, 4> Replacements;
1237 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1238 FI = Path.rbegin(), FIEnd = Path.rend();
1239 FI != FIEnd; ++FI) {
1240 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001241 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001242 DIE->getDesignator(DesigIdx)->getDotLoc(),
1243 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1244 else
1245 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1246 SourceLocation()));
1247 Replacements.back().setField(*FI);
1248 }
1249
1250 // Expand the current designator into the set of replacement
1251 // designators, so we have a full subobject path down to where the
1252 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001253 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001254 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001255
Douglas Gregord5846a12009-04-15 06:41:24 +00001256 // Update FieldIter/FieldIndex;
1257 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001258 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001259 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001260 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001261 FieldIter != FEnd; ++FieldIter) {
1262 if (FieldIter->isUnnamedBitfield())
1263 continue;
1264
1265 if (*FieldIter == Path.back())
1266 return;
1267
1268 ++FieldIndex;
1269 }
1270
1271 assert(false && "Unable to find anonymous struct/union field");
1272}
1273
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001274/// @brief Check the well-formedness of a C99 designated initializer.
1275///
1276/// Determines whether the designated initializer @p DIE, which
1277/// resides at the given @p Index within the initializer list @p
1278/// IList, is well-formed for a current object of type @p DeclType
1279/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001280/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001281/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001282///
1283/// @param IList The initializer list in which this designated
1284/// initializer occurs.
1285///
Douglas Gregora5324162009-04-15 04:56:10 +00001286/// @param DIE The designated initializer expression.
1287///
1288/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001289///
1290/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1291/// into which the designation in @p DIE should refer.
1292///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001293/// @param NextField If non-NULL and the first designator in @p DIE is
1294/// a field, this will be set to the field declaration corresponding
1295/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001296///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001297/// @param NextElementIndex If non-NULL and the first designator in @p
1298/// DIE is an array designator or GNU array-range designator, this
1299/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001300///
1301/// @param Index Index into @p IList where the designated initializer
1302/// @p DIE occurs.
1303///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001304/// @param StructuredList The initializer list expression that
1305/// describes all of the subobject initializers in the order they'll
1306/// actually be initialized.
1307///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001308/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001309bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001310InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001311 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001312 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001313 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001314 QualType &CurrentObjectType,
1315 RecordDecl::field_iterator *NextField,
1316 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001317 unsigned &Index,
1318 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001319 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001320 bool FinishSubobjectInit,
1321 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001322 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001323 // Check the actual initialization for the designated object type.
1324 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001325
1326 // Temporarily remove the designator expression from the
1327 // initializer list that the child calls see, so that we don't try
1328 // to re-process the designator.
1329 unsigned OldIndex = Index;
1330 IList->setInit(OldIndex, DIE->getInit());
1331
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001332 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001333 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001334
1335 // Restore the designated initializer expression in the syntactic
1336 // form of the initializer list.
1337 if (IList->getInit(OldIndex) != DIE->getInit())
1338 DIE->setInit(IList->getInit(OldIndex));
1339 IList->setInit(OldIndex, DIE);
1340
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001341 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001342 }
1343
Douglas Gregora5324162009-04-15 04:56:10 +00001344 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001345 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001346 "Need a non-designated initializer list to start from");
1347
Douglas Gregora5324162009-04-15 04:56:10 +00001348 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001349 // Determine the structural initializer list that corresponds to the
1350 // current subobject.
1351 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001352 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001353 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001354 SourceRange(D->getStartLocation(),
1355 DIE->getSourceRange().getEnd()));
1356 assert(StructuredList && "Expected a structured initializer list");
1357
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001358 if (D->isFieldDesignator()) {
1359 // C99 6.7.8p7:
1360 //
1361 // If a designator has the form
1362 //
1363 // . identifier
1364 //
1365 // then the current object (defined below) shall have
1366 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001367 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001368 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001369 if (!RT) {
1370 SourceLocation Loc = D->getDotLoc();
1371 if (Loc.isInvalid())
1372 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001373 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1374 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001375 ++Index;
1376 return true;
1377 }
1378
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001379 // Note: we perform a linear search of the fields here, despite
1380 // the fact that we have a faster lookup method, because we always
1381 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001382 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001383 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001384 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001385 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001386 Field = RT->getDecl()->field_begin(),
1387 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001388 for (; Field != FieldEnd; ++Field) {
1389 if (Field->isUnnamedBitfield())
1390 continue;
1391
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001392 if (KnownField && KnownField == *Field)
1393 break;
1394 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001395 break;
1396
1397 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001398 }
1399
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001400 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001401 // There was no normal field in the struct with the designated
1402 // name. Perform another lookup for this name, which may find
1403 // something that we can't designate (e.g., a member function),
1404 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001405 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001406 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001407 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001408 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001409 // Name lookup didn't find anything. Determine whether this
1410 // was a typo for another field name.
1411 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1412 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001413 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1414 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001415 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001416 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001417 ->Equals(RT->getDecl())) {
1418 SemaRef.Diag(D->getFieldLoc(),
1419 diag::err_field_designator_unknown_suggest)
1420 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001421 << FixItHint::CreateReplacement(D->getFieldLoc(),
1422 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001423 SemaRef.Diag(ReplacementField->getLocation(),
1424 diag::note_previous_decl)
1425 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001426 } else {
1427 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1428 << FieldName << CurrentObjectType;
1429 ++Index;
1430 return true;
1431 }
1432 } else if (!KnownField) {
1433 // Determine whether we found a field at all.
1434 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1435 }
1436
1437 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001438 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001439 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001440 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001441 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001442 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001443 ++Index;
1444 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001445 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001446
1447 if (!KnownField &&
1448 cast<RecordDecl>((ReplacementField)->getDeclContext())
1449 ->isAnonymousStructOrUnion()) {
1450 // Handle an field designator that refers to a member of an
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001451 // anonymous struct or union. This is a C1X feature.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001452 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1453 ReplacementField,
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001454 Field, FieldIndex, RT->getDecl());
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001455 D = DIE->getDesignator(DesigIdx);
1456 } else if (!KnownField) {
1457 // The replacement field comes from typo correction; find it
1458 // in the list of fields.
1459 FieldIndex = 0;
1460 Field = RT->getDecl()->field_begin();
1461 for (; Field != FieldEnd; ++Field) {
1462 if (Field->isUnnamedBitfield())
1463 continue;
1464
1465 if (ReplacementField == *Field ||
1466 Field->getIdentifier() == ReplacementField->getIdentifier())
1467 break;
1468
1469 ++FieldIndex;
1470 }
1471 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001472 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001473
1474 // All of the fields of a union are located at the same place in
1475 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001476 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001477 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001478 StructuredList->setInitializedFieldInUnion(*Field);
1479 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001480
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001481 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001482 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001483
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001484 // Make sure that our non-designated initializer list has space
1485 // for a subobject corresponding to this field.
1486 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001487 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001488
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001489 // This designator names a flexible array member.
1490 if (Field->getType()->isIncompleteArrayType()) {
1491 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001492 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001493 // We can't designate an object within the flexible array
1494 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001495 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001496 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001497 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001498 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001499 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001500 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001501 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001502 << *Field;
1503 Invalid = true;
1504 }
1505
Chris Lattner001b29c2010-10-10 17:49:49 +00001506 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1507 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001508 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001509 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001510 diag::err_flexible_array_init_needs_braces)
1511 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001512 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001513 << *Field;
1514 Invalid = true;
1515 }
1516
1517 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001518 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001519 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001520 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001521 diag::err_flexible_array_init_nonempty)
1522 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001523 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001524 << *Field;
1525 Invalid = true;
1526 }
1527
1528 if (Invalid) {
1529 ++Index;
1530 return true;
1531 }
1532
1533 // Initialize the array.
1534 bool prevHadError = hadError;
1535 unsigned newStructuredIndex = FieldIndex;
1536 unsigned OldIndex = Index;
1537 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001538
1539 InitializedEntity MemberEntity =
1540 InitializedEntity::InitializeMember(*Field, &Entity);
1541 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001542 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001543
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001544 IList->setInit(OldIndex, DIE);
1545 if (hadError && !prevHadError) {
1546 ++Field;
1547 ++FieldIndex;
1548 if (NextField)
1549 *NextField = Field;
1550 StructuredIndex = FieldIndex;
1551 return true;
1552 }
1553 } else {
1554 // Recurse to check later designated subobjects.
1555 QualType FieldType = (*Field)->getType();
1556 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001557
1558 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001559 InitializedEntity::InitializeMember(*Field, &Entity);
1560 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001561 FieldType, 0, 0, Index,
1562 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001563 true, false))
1564 return true;
1565 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001566
1567 // Find the position of the next field to be initialized in this
1568 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001569 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001570 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571
1572 // If this the first designator, our caller will continue checking
1573 // the rest of this struct/class/union subobject.
1574 if (IsFirstDesignator) {
1575 if (NextField)
1576 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001577 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001578 return false;
1579 }
1580
Douglas Gregor17bd0942009-01-28 23:36:17 +00001581 if (!FinishSubobjectInit)
1582 return false;
1583
Douglas Gregord5846a12009-04-15 06:41:24 +00001584 // We've already initialized something in the union; we're done.
1585 if (RT->getDecl()->isUnion())
1586 return hadError;
1587
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001588 // Check the remaining fields within this class/struct/union subobject.
1589 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001590
Anders Carlsson6cabf312010-01-23 23:23:01 +00001591 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001592 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001593 return hadError && !prevHadError;
1594 }
1595
1596 // C99 6.7.8p6:
1597 //
1598 // If a designator has the form
1599 //
1600 // [ constant-expression ]
1601 //
1602 // then the current object (defined below) shall have array
1603 // type and the expression shall be an integer constant
1604 // expression. If the array is of unknown size, any
1605 // nonnegative value is valid.
1606 //
1607 // Additionally, cope with the GNU extension that permits
1608 // designators of the form
1609 //
1610 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001611 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001612 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001613 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001614 << CurrentObjectType;
1615 ++Index;
1616 return true;
1617 }
1618
1619 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001620 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1621 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001623 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001624 DesignatedEndIndex = DesignatedStartIndex;
1625 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001626 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001627
Mike Stump11289f42009-09-09 15:08:12 +00001628
1629 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001630 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001631 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001632 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001633 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001634
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001635 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001636 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001637 }
1638
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001639 if (isa<ConstantArrayType>(AT)) {
1640 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001641 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1642 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1643 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1644 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1645 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001646 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001647 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001648 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001649 << IndexExpr->getSourceRange();
1650 ++Index;
1651 return true;
1652 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001653 } else {
1654 // Make sure the bit-widths and signedness match.
1655 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1656 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001657 else if (DesignatedStartIndex.getBitWidth() <
1658 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001659 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1660 DesignatedStartIndex.setIsUnsigned(true);
1661 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001662 }
Mike Stump11289f42009-09-09 15:08:12 +00001663
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001664 // Make sure that our non-designated initializer list has space
1665 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001666 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001667 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001668 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001669
Douglas Gregor17bd0942009-01-28 23:36:17 +00001670 // Repeatedly perform subobject initializations in the range
1671 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001672
Douglas Gregor17bd0942009-01-28 23:36:17 +00001673 // Move to the next designator
1674 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1675 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001676
1677 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001678 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001679
Douglas Gregor17bd0942009-01-28 23:36:17 +00001680 while (DesignatedStartIndex <= DesignatedEndIndex) {
1681 // Recurse to check later designated subobjects.
1682 QualType ElementType = AT->getElementType();
1683 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001684
1685 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001686 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001687 ElementType, 0, 0, Index,
1688 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001689 (DesignatedStartIndex == DesignatedEndIndex),
1690 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001691 return true;
1692
1693 // Move to the next index in the array that we'll be initializing.
1694 ++DesignatedStartIndex;
1695 ElementIndex = DesignatedStartIndex.getZExtValue();
1696 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001697
1698 // If this the first designator, our caller will continue checking
1699 // the rest of this array subobject.
1700 if (IsFirstDesignator) {
1701 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001702 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001703 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001704 return false;
1705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregor17bd0942009-01-28 23:36:17 +00001707 if (!FinishSubobjectInit)
1708 return false;
1709
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001710 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001711 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001712 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001713 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001714 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001715 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001716}
1717
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001718// Get the structured initializer list for a subobject of type
1719// @p CurrentObjectType.
1720InitListExpr *
1721InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1722 QualType CurrentObjectType,
1723 InitListExpr *StructuredList,
1724 unsigned StructuredIndex,
1725 SourceRange InitRange) {
1726 Expr *ExistingInit = 0;
1727 if (!StructuredList)
1728 ExistingInit = SyntacticToSemantic[IList];
1729 else if (StructuredIndex < StructuredList->getNumInits())
1730 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001731
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001732 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1733 return Result;
1734
1735 if (ExistingInit) {
1736 // We are creating an initializer list that initializes the
1737 // subobjects of the current object, but there was already an
1738 // initialization that completely initialized the current
1739 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001740 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 // struct X { int a, b; };
1742 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001743 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001744 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1745 // designated initializer re-initializes the whole
1746 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001747 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001748 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001749 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001750 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001751 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001752 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001753 << ExistingInit->getSourceRange();
1754 }
1755
Mike Stump11289f42009-09-09 15:08:12 +00001756 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001757 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1758 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001759 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001760
Douglas Gregora8a089b2010-07-13 18:40:04 +00001761 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001762
Douglas Gregor6d00c992009-03-20 23:58:33 +00001763 // Pre-allocate storage for the structured initializer list.
1764 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001765 unsigned NumInits = 0;
1766 if (!StructuredList)
1767 NumInits = IList->getNumInits();
1768 else if (Index < IList->getNumInits()) {
1769 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1770 NumInits = SubList->getNumInits();
1771 }
1772
Mike Stump11289f42009-09-09 15:08:12 +00001773 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001774 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1775 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1776 NumElements = CAType->getSize().getZExtValue();
1777 // Simple heuristic so that we don't allocate a very large
1778 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001779 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001780 NumElements = 0;
1781 }
John McCall9dd450b2009-09-21 23:43:11 +00001782 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001783 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001784 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001785 RecordDecl *RDecl = RType->getDecl();
1786 if (RDecl->isUnion())
1787 NumElements = 1;
1788 else
Mike Stump11289f42009-09-09 15:08:12 +00001789 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001790 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001791 }
1792
Douglas Gregor221c9a52009-03-21 18:13:52 +00001793 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001794 NumElements = IList->getNumInits();
1795
Ted Kremenekac034612010-04-13 23:39:13 +00001796 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001797
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001798 // Link this new initializer list into the structured initializer
1799 // lists.
1800 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001801 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001802 else {
1803 Result->setSyntacticForm(IList);
1804 SyntacticToSemantic[IList] = Result;
1805 }
1806
1807 return Result;
1808}
1809
1810/// Update the initializer at index @p StructuredIndex within the
1811/// structured initializer list to the value @p expr.
1812void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1813 unsigned &StructuredIndex,
1814 Expr *expr) {
1815 // No structured initializer list to update
1816 if (!StructuredList)
1817 return;
1818
Ted Kremenekac034612010-04-13 23:39:13 +00001819 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1820 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001821 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001822 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001823 diag::warn_initializer_overrides)
1824 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001825 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001826 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001827 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001828 << PrevInit->getSourceRange();
1829 }
Mike Stump11289f42009-09-09 15:08:12 +00001830
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001831 ++StructuredIndex;
1832}
1833
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001834/// Check that the given Index expression is a valid array designator
1835/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001836/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001837/// and produces a reasonable diagnostic if there is a
1838/// failure. Returns true if there was an error, false otherwise. If
1839/// everything went okay, Value will receive the value of the constant
1840/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001841static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001842CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001843 SourceLocation Loc = Index->getSourceRange().getBegin();
1844
1845 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001846 if (S.VerifyIntegerConstantExpression(Index, &Value))
1847 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001848
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001849 if (Value.isSigned() && Value.isNegative())
1850 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001851 << Value.toString(10) << Index->getSourceRange();
1852
Douglas Gregor51650d32009-01-23 21:04:18 +00001853 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001854 return false;
1855}
1856
John McCalldadc5752010-08-24 06:29:42 +00001857ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001858 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001859 bool GNUSyntax,
John McCalldadc5752010-08-24 06:29:42 +00001860 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001861 typedef DesignatedInitExpr::Designator ASTDesignator;
1862
1863 bool Invalid = false;
1864 llvm::SmallVector<ASTDesignator, 32> Designators;
1865 llvm::SmallVector<Expr *, 32> InitExpressions;
1866
1867 // Build designators and check array designator expressions.
1868 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1869 const Designator &D = Desig.getDesignator(Idx);
1870 switch (D.getKind()) {
1871 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001872 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001873 D.getFieldLoc()));
1874 break;
1875
1876 case Designator::ArrayDesignator: {
1877 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1878 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001879 if (!Index->isTypeDependent() &&
1880 !Index->isValueDependent() &&
1881 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001882 Invalid = true;
1883 else {
1884 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001885 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001886 D.getRBracketLoc()));
1887 InitExpressions.push_back(Index);
1888 }
1889 break;
1890 }
1891
1892 case Designator::ArrayRangeDesignator: {
1893 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1894 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1895 llvm::APSInt StartValue;
1896 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001897 bool StartDependent = StartIndex->isTypeDependent() ||
1898 StartIndex->isValueDependent();
1899 bool EndDependent = EndIndex->isTypeDependent() ||
1900 EndIndex->isValueDependent();
1901 if ((!StartDependent &&
1902 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1903 (!EndDependent &&
1904 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001906 else {
1907 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001908 if (StartDependent || EndDependent) {
1909 // Nothing to compute.
1910 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001911 EndValue.extend(StartValue.getBitWidth());
1912 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1913 StartValue.extend(EndValue.getBitWidth());
1914
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001915 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001916 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001917 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001918 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1919 Invalid = true;
1920 } else {
1921 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001922 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001923 D.getEllipsisLoc(),
1924 D.getRBracketLoc()));
1925 InitExpressions.push_back(StartIndex);
1926 InitExpressions.push_back(EndIndex);
1927 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001928 }
1929 break;
1930 }
1931 }
1932 }
1933
1934 if (Invalid || Init.isInvalid())
1935 return ExprError();
1936
1937 // Clear out the expressions within the designation.
1938 Desig.ClearExprs(*this);
1939
1940 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001941 = DesignatedInitExpr::Create(Context,
1942 Designators.data(), Designators.size(),
1943 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001944 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001945 return Owned(DIE);
1946}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001947
Douglas Gregor723796a2009-12-16 06:35:08 +00001948bool Sema::CheckInitList(const InitializedEntity &Entity,
1949 InitListExpr *&InitList, QualType &DeclType) {
1950 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001951 if (!CheckInitList.HadError())
1952 InitList = CheckInitList.getFullyStructuredList();
1953
1954 return CheckInitList.HadError();
1955}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001956
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001957//===----------------------------------------------------------------------===//
1958// Initialization entity
1959//===----------------------------------------------------------------------===//
1960
Douglas Gregor723796a2009-12-16 06:35:08 +00001961InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1962 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001963 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001964{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001965 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1966 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001967 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001968 } else {
1969 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001970 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001971 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001972}
1973
1974InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001975 CXXBaseSpecifier *Base,
1976 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001977{
1978 InitializedEntity Result;
1979 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001980 Result.Base = reinterpret_cast<uintptr_t>(Base);
1981 if (IsInheritedVirtualBase)
1982 Result.Base |= 0x01;
1983
Douglas Gregor1b303932009-12-22 15:35:07 +00001984 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001985 return Result;
1986}
1987
Douglas Gregor85dabae2009-12-16 01:38:02 +00001988DeclarationName InitializedEntity::getName() const {
1989 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001990 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001991 if (!VariableOrMember)
1992 return DeclarationName();
1993 // Fall through
1994
1995 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001996 case EK_Member:
1997 return VariableOrMember->getDeclName();
1998
1999 case EK_Result:
2000 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002001 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002002 case EK_Temporary:
2003 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002004 case EK_ArrayElement:
2005 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002006 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002007 return DeclarationName();
2008 }
2009
2010 // Silence GCC warning
2011 return DeclarationName();
2012}
2013
Douglas Gregora4b592a2009-12-19 03:01:41 +00002014DeclaratorDecl *InitializedEntity::getDecl() const {
2015 switch (getKind()) {
2016 case EK_Variable:
2017 case EK_Parameter:
2018 case EK_Member:
2019 return VariableOrMember;
2020
2021 case EK_Result:
2022 case EK_Exception:
2023 case EK_New:
2024 case EK_Temporary:
2025 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002026 case EK_ArrayElement:
2027 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002028 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002029 return 0;
2030 }
2031
2032 // Silence GCC warning
2033 return 0;
2034}
2035
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002036bool InitializedEntity::allowsNRVO() const {
2037 switch (getKind()) {
2038 case EK_Result:
2039 case EK_Exception:
2040 return LocAndNRVO.NRVO;
2041
2042 case EK_Variable:
2043 case EK_Parameter:
2044 case EK_Member:
2045 case EK_New:
2046 case EK_Temporary:
2047 case EK_Base:
2048 case EK_ArrayElement:
2049 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002050 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002051 break;
2052 }
2053
2054 return false;
2055}
2056
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002057//===----------------------------------------------------------------------===//
2058// Initialization sequence
2059//===----------------------------------------------------------------------===//
2060
2061void InitializationSequence::Step::Destroy() {
2062 switch (Kind) {
2063 case SK_ResolveAddressOfOverloadedFunction:
2064 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002065 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002066 case SK_CastDerivedToBaseLValue:
2067 case SK_BindReference:
2068 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002069 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002070 case SK_UserConversion:
2071 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002072 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002073 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002074 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002075 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002076 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002077 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002078 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002079 case SK_ObjCObjectConversion:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002080 break;
2081
2082 case SK_ConversionSequence:
2083 delete ICS;
2084 }
2085}
2086
Douglas Gregor838fcc32010-03-26 20:14:36 +00002087bool InitializationSequence::isDirectReferenceBinding() const {
2088 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2089}
2090
2091bool InitializationSequence::isAmbiguous() const {
2092 if (getKind() != FailedSequence)
2093 return false;
2094
2095 switch (getFailureKind()) {
2096 case FK_TooManyInitsForReference:
2097 case FK_ArrayNeedsInitList:
2098 case FK_ArrayNeedsInitListOrStringLiteral:
2099 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2100 case FK_NonConstLValueReferenceBindingToTemporary:
2101 case FK_NonConstLValueReferenceBindingToUnrelated:
2102 case FK_RValueReferenceBindingToLValue:
2103 case FK_ReferenceInitDropsQualifiers:
2104 case FK_ReferenceInitFailed:
2105 case FK_ConversionFailed:
2106 case FK_TooManyInitsForScalar:
2107 case FK_ReferenceBindingToInitList:
2108 case FK_InitListBadDestinationType:
2109 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002110 case FK_Incomplete:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002111 return false;
2112
2113 case FK_ReferenceInitOverloadFailed:
2114 case FK_UserConversionOverloadFailed:
2115 case FK_ConstructorOverloadFailed:
2116 return FailedOverloadResult == OR_Ambiguous;
2117 }
2118
2119 return false;
2120}
2121
Douglas Gregorb33eed02010-04-16 22:09:46 +00002122bool InitializationSequence::isConstructorInitialization() const {
2123 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2124}
2125
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002126void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002127 FunctionDecl *Function,
2128 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002129 Step S;
2130 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2131 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002132 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002133 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002134 Steps.push_back(S);
2135}
2136
2137void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002138 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002139 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002140 switch (VK) {
2141 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2142 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2143 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002144 default: llvm_unreachable("No such category");
2145 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002146 S.Type = BaseType;
2147 Steps.push_back(S);
2148}
2149
2150void InitializationSequence::AddReferenceBindingStep(QualType T,
2151 bool BindingTemporary) {
2152 Step S;
2153 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2154 S.Type = T;
2155 Steps.push_back(S);
2156}
2157
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002158void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2159 Step S;
2160 S.Kind = SK_ExtraneousCopyToTemporary;
2161 S.Type = T;
2162 Steps.push_back(S);
2163}
2164
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002165void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002166 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002167 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002168 Step S;
2169 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002170 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002171 S.Function.Function = Function;
2172 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002173 Steps.push_back(S);
2174}
2175
2176void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002177 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002178 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002179 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002180 switch (VK) {
2181 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002182 S.Kind = SK_QualificationConversionRValue;
2183 break;
John McCall2536c6d2010-08-25 10:28:54 +00002184 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002185 S.Kind = SK_QualificationConversionXValue;
2186 break;
John McCall2536c6d2010-08-25 10:28:54 +00002187 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002188 S.Kind = SK_QualificationConversionLValue;
2189 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002190 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002191 S.Type = Ty;
2192 Steps.push_back(S);
2193}
2194
2195void InitializationSequence::AddConversionSequenceStep(
2196 const ImplicitConversionSequence &ICS,
2197 QualType T) {
2198 Step S;
2199 S.Kind = SK_ConversionSequence;
2200 S.Type = T;
2201 S.ICS = new ImplicitConversionSequence(ICS);
2202 Steps.push_back(S);
2203}
2204
Douglas Gregor51e77d52009-12-10 17:56:55 +00002205void InitializationSequence::AddListInitializationStep(QualType T) {
2206 Step S;
2207 S.Kind = SK_ListInitialization;
2208 S.Type = T;
2209 Steps.push_back(S);
2210}
2211
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002212void
2213InitializationSequence::AddConstructorInitializationStep(
2214 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002215 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002216 QualType T) {
2217 Step S;
2218 S.Kind = SK_ConstructorInitialization;
2219 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002220 S.Function.Function = Constructor;
2221 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002222 Steps.push_back(S);
2223}
2224
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002225void InitializationSequence::AddZeroInitializationStep(QualType T) {
2226 Step S;
2227 S.Kind = SK_ZeroInitialization;
2228 S.Type = T;
2229 Steps.push_back(S);
2230}
2231
Douglas Gregore1314a62009-12-18 05:02:21 +00002232void InitializationSequence::AddCAssignmentStep(QualType T) {
2233 Step S;
2234 S.Kind = SK_CAssignment;
2235 S.Type = T;
2236 Steps.push_back(S);
2237}
2238
Eli Friedman78275202009-12-19 08:11:05 +00002239void InitializationSequence::AddStringInitStep(QualType T) {
2240 Step S;
2241 S.Kind = SK_StringInit;
2242 S.Type = T;
2243 Steps.push_back(S);
2244}
2245
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002246void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2247 Step S;
2248 S.Kind = SK_ObjCObjectConversion;
2249 S.Type = T;
2250 Steps.push_back(S);
2251}
2252
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002253void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2254 OverloadingResult Result) {
2255 SequenceKind = FailedSequence;
2256 this->Failure = Failure;
2257 this->FailedOverloadResult = Result;
2258}
2259
2260//===----------------------------------------------------------------------===//
2261// Attempt initialization
2262//===----------------------------------------------------------------------===//
2263
2264/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002265static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002266 const InitializedEntity &Entity,
2267 const InitializationKind &Kind,
2268 InitListExpr *InitList,
2269 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002270 // FIXME: We only perform rudimentary checking of list
2271 // initializations at this point, then assume that any list
2272 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002273 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002274 // do all of the necessary checking. C++0x initializer lists will
2275 // force us to perform more checking here.
2276 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2277
Douglas Gregor1b303932009-12-22 15:35:07 +00002278 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002279
2280 // C++ [dcl.init]p13:
2281 // If T is a scalar type, then a declaration of the form
2282 //
2283 // T x = { a };
2284 //
2285 // is equivalent to
2286 //
2287 // T x = a;
2288 if (DestType->isScalarType()) {
2289 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2290 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2291 return;
2292 }
2293
2294 // Assume scalar initialization from a single value works.
2295 } else if (DestType->isAggregateType()) {
2296 // Assume aggregate initialization works.
2297 } else if (DestType->isVectorType()) {
2298 // Assume vector initialization works.
2299 } else if (DestType->isReferenceType()) {
2300 // FIXME: C++0x defines behavior for this.
2301 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2302 return;
2303 } else if (DestType->isRecordType()) {
2304 // FIXME: C++0x defines behavior for this
2305 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2306 }
2307
2308 // Add a general "list initialization" step.
2309 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002310}
2311
2312/// \brief Try a reference initialization that involves calling a conversion
2313/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002314static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2315 const InitializedEntity &Entity,
2316 const InitializationKind &Kind,
2317 Expr *Initializer,
2318 bool AllowRValues,
2319 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002320 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002321 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2322 QualType T1 = cv1T1.getUnqualifiedType();
2323 QualType cv2T2 = Initializer->getType();
2324 QualType T2 = cv2T2.getUnqualifiedType();
2325
2326 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002327 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002328 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002329 T1, T2, DerivedToBase,
2330 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002331 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002332 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002333 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002334
2335 // Build the candidate set directly in the initialization sequence
2336 // structure, so that it will persist if we fail.
2337 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2338 CandidateSet.clear();
2339
2340 // Determine whether we are allowed to call explicit constructors or
2341 // explicit conversion operators.
2342 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2343
2344 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002345 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2346 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002347 // The type we're converting to is a class type. Enumerate its constructors
2348 // to see if there is a suitable conversion.
2349 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002350
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002351 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002352 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002353 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002354 NamedDecl *D = *Con;
2355 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2356
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002357 // Find the constructor (which may be a template).
2358 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002359 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002360 if (ConstructorTmpl)
2361 Constructor = cast<CXXConstructorDecl>(
2362 ConstructorTmpl->getTemplatedDecl());
2363 else
John McCalla0296f72010-03-19 07:35:19 +00002364 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002365
2366 if (!Constructor->isInvalidDecl() &&
2367 Constructor->isConvertingConstructor(AllowExplicit)) {
2368 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002369 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002370 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002371 &Initializer, 1, CandidateSet,
2372 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002373 else
John McCalla0296f72010-03-19 07:35:19 +00002374 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002375 &Initializer, 1, CandidateSet,
2376 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002377 }
2378 }
2379 }
John McCall3696dcb2010-08-17 07:23:57 +00002380 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2381 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002382
Douglas Gregor496e8b342010-05-07 19:42:26 +00002383 const RecordType *T2RecordType = 0;
2384 if ((T2RecordType = T2->getAs<RecordType>()) &&
2385 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002386 // The type we're converting from is a class type, enumerate its conversion
2387 // functions.
2388 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2389
2390 // Determine the type we are converting to. If we are allowed to
2391 // convert to an rvalue, take the type that the destination type
2392 // refers to.
2393 QualType ToType = AllowRValues? cv1T1 : DestType;
2394
John McCallad371252010-01-20 00:46:10 +00002395 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002397 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2398 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002399 NamedDecl *D = *I;
2400 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2401 if (isa<UsingShadowDecl>(D))
2402 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2403
2404 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2405 CXXConversionDecl *Conv;
2406 if (ConvTemplate)
2407 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2408 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002409 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002410
2411 // If the conversion function doesn't return a reference type,
2412 // it can't be considered for this conversion unless we're allowed to
2413 // consider rvalues.
2414 // FIXME: Do we need to make sure that we only consider conversion
2415 // candidates with reference-compatible results? That might be needed to
2416 // break recursion.
2417 if ((AllowExplicit || !Conv->isExplicit()) &&
2418 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2419 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002420 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002421 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002422 ToType, CandidateSet);
2423 else
John McCalla0296f72010-03-19 07:35:19 +00002424 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002425 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002426 }
2427 }
2428 }
John McCall3696dcb2010-08-17 07:23:57 +00002429 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2430 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002431
2432 SourceLocation DeclLoc = Initializer->getLocStart();
2433
2434 // Perform overload resolution. If it fails, return the failed result.
2435 OverloadCandidateSet::iterator Best;
2436 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002437 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002438 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002439
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002440 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002441
2442 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002443 if (isa<CXXConversionDecl>(Function))
2444 T2 = Function->getResultType();
2445 else
2446 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002447
2448 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002449 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002450 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002451
2452 // Determine whether we need to perform derived-to-base or
2453 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002454 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002455 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002456 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002457 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002458 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002459
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002460 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002461 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002462 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregora8a089b2010-07-13 18:40:04 +00002463 = S.CompareReferenceRelationship(DeclLoc, T1,
2464 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002465 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002466 if (NewRefRelationship == Sema::Ref_Incompatible) {
2467 // If the type we've converted to is not reference-related to the
2468 // type we're looking for, then there is another conversion step
2469 // we need to perform to produce a temporary of the right type
2470 // that we'll be binding to.
2471 ImplicitConversionSequence ICS;
2472 ICS.setStandard();
2473 ICS.Standard = Best->FinalConversion;
2474 T2 = ICS.Standard.getToType(2);
2475 Sequence.AddConversionSequenceStep(ICS, T2);
2476 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 Sequence.AddDerivedToBaseCastStep(
2478 S.Context.getQualifiedType(T1,
2479 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002480 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002481 else if (NewObjCConversion)
2482 Sequence.AddObjCObjectConversionStep(
2483 S.Context.getQualifiedType(T1,
2484 T2.getNonReferenceType().getQualifiers()));
2485
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002486 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002487 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488
2489 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2490 return OR_Success;
2491}
2492
Sebastian Redld92badf2010-06-30 18:13:39 +00002493/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002494static void TryReferenceInitialization(Sema &S,
2495 const InitializedEntity &Entity,
2496 const InitializationKind &Kind,
2497 Expr *Initializer,
2498 InitializationSequence &Sequence) {
2499 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002500
Douglas Gregor1b303932009-12-22 15:35:07 +00002501 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002502 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002503 Qualifiers T1Quals;
2504 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002505 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002506 Qualifiers T2Quals;
2507 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002508 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002509
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002510 // If the initializer is the address of an overloaded function, try
2511 // to resolve the overloaded function. If all goes well, T2 is the
2512 // type of the resulting function.
2513 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002514 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002515 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2516 T1,
John McCall16df1e52010-03-30 21:47:33 +00002517 false,
2518 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002519 if (!Fn) {
2520 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2521 return;
2522 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002523
John McCall16df1e52010-03-30 21:47:33 +00002524 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002525 cv2T2 = Fn->getType();
2526 T2 = cv2T2.getUnqualifiedType();
2527 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002528
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002529 // Compute some basic properties of the types and the initializer.
2530 bool isLValueRef = DestType->isLValueReferenceType();
2531 bool isRValueRef = !isLValueRef;
2532 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002533 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002534 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002535 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002536 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2537 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002538
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002539 // C++0x [dcl.init.ref]p5:
2540 // A reference to type "cv1 T1" is initialized by an expression of type
2541 // "cv2 T2" as follows:
2542 //
2543 // - If the reference is an lvalue reference and the initializer
2544 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002545 // Note the analogous bullet points for rvlaue refs to functions. Because
2546 // there are no function rvalues in C++, rvalue refs to functions are treated
2547 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002548 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002549 bool T1Function = T1->isFunctionType();
2550 if (isLValueRef || T1Function) {
2551 if (InitCategory.isLValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002552 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2553 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2554 // reference-compatible with "cv2 T2," or
2555 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002556 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002557 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002558 // can occur. However, we do pay attention to whether it is a bit-field
2559 // to decide whether we're actually binding to a temporary created from
2560 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002561 if (DerivedToBase)
2562 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002563 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002564 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002565 else if (ObjCConversion)
2566 Sequence.AddObjCObjectConversionStep(
2567 S.Context.getQualifiedType(T1, T2Quals));
2568
Chandler Carruth04bdce62010-01-12 20:32:25 +00002569 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002570 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002571 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002572 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002573 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002574 return;
2575 }
2576
2577 // - has a class type (i.e., T2 is a class type), where T1 is not
2578 // reference-related to T2, and can be implicitly converted to an
2579 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2580 // with "cv3 T3" (this conversion is selected by enumerating the
2581 // applicable conversion functions (13.3.1.6) and choosing the best
2582 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002583 // If we have an rvalue ref to function type here, the rhs must be
2584 // an rvalue.
2585 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2586 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002587 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2588 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002589 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002590 Sequence);
2591 if (ConvOvlResult == OR_Success)
2592 return;
John McCall0d1da222010-01-12 00:44:57 +00002593 if (ConvOvlResult != OR_No_Viable_Function) {
2594 Sequence.SetOverloadFailure(
2595 InitializationSequence::FK_ReferenceInitOverloadFailed,
2596 ConvOvlResult);
2597 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002598 }
2599 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002600
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002601 // - Otherwise, the reference shall be an lvalue reference to a
2602 // non-volatile const type (i.e., cv1 shall be const), or the reference
2603 // shall be an rvalue reference and the initializer expression shall
Sebastian Redld92badf2010-06-30 18:13:39 +00002604 // be an rvalue or have a function type.
2605 // We handled the function type stuff above.
Douglas Gregord1e08642010-01-29 19:39:15 +00002606 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redld92badf2010-06-30 18:13:39 +00002607 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002608 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2609 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);
2710 else
2711 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002712 return;
2713 }
2714
2715 // [...] If T1 is reference-related to T2, cv1 must be the
2716 // same cv-qualification as, or greater cv-qualification
2717 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002718 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2719 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002720 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002721 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002722 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2723 return;
2724 }
2725
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2727 return;
2728}
2729
2730/// \brief Attempt character array initialization from a string literal
2731/// (C++ [dcl.init.string], C99 6.7.8).
2732static void TryStringLiteralInitialization(Sema &S,
2733 const InitializedEntity &Entity,
2734 const InitializationKind &Kind,
2735 Expr *Initializer,
2736 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002737 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002738 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002739}
2740
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002741/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2742/// enumerates the constructors of the initialized entity and performs overload
2743/// resolution to select the best.
2744static void TryConstructorInitialization(Sema &S,
2745 const InitializedEntity &Entity,
2746 const InitializationKind &Kind,
2747 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002748 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002749 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002750 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002751
2752 // Build the candidate set directly in the initialization sequence
2753 // structure, so that it will persist if we fail.
2754 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2755 CandidateSet.clear();
2756
2757 // Determine whether we are allowed to call explicit constructors or
2758 // explicit conversion operators.
2759 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2760 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002761 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002762
2763 // The type we're constructing needs to be complete.
2764 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002765 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002766 return;
2767 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002768
2769 // The type we're converting to is a class type. Enumerate its constructors
2770 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002771 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2772 assert(DestRecordType && "Constructor initialization requires record type");
2773 CXXRecordDecl *DestRecordDecl
2774 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2775
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002776 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002777 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002778 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002779 NamedDecl *D = *Con;
2780 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002781 bool SuppressUserConversions = false;
2782
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002783 // Find the constructor (which may be a template).
2784 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002785 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002786 if (ConstructorTmpl)
2787 Constructor = cast<CXXConstructorDecl>(
2788 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002789 else {
John McCalla0296f72010-03-19 07:35:19 +00002790 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002791
2792 // If we're performing copy initialization using a copy constructor, we
2793 // suppress user-defined conversions on the arguments.
2794 // FIXME: Move constructors?
2795 if (Kind.getKind() == InitializationKind::IK_Copy &&
2796 Constructor->isCopyConstructor())
2797 SuppressUserConversions = true;
2798 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002799
2800 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002801 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002802 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002803 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002804 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002805 Args, NumArgs, CandidateSet,
2806 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002807 else
John McCalla0296f72010-03-19 07:35:19 +00002808 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002809 Args, NumArgs, CandidateSet,
2810 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002811 }
2812 }
2813
2814 SourceLocation DeclLoc = Kind.getLocation();
2815
2816 // Perform overload resolution. If it fails, return the failed result.
2817 OverloadCandidateSet::iterator Best;
2818 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002819 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002820 Sequence.SetOverloadFailure(
2821 InitializationSequence::FK_ConstructorOverloadFailed,
2822 Result);
2823 return;
2824 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002825
2826 // C++0x [dcl.init]p6:
2827 // If a program calls for the default initialization of an object
2828 // of a const-qualified type T, T shall be a class type with a
2829 // user-provided default constructor.
2830 if (Kind.getKind() == InitializationKind::IK_Default &&
2831 Entity.getType().isConstQualified() &&
2832 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2833 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2834 return;
2835 }
2836
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002837 // Add the constructor initialization step. Any cv-qualification conversion is
2838 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002839 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002840 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002841 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002842 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002843}
2844
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002845/// \brief Attempt value initialization (C++ [dcl.init]p7).
2846static void TryValueInitialization(Sema &S,
2847 const InitializedEntity &Entity,
2848 const InitializationKind &Kind,
2849 InitializationSequence &Sequence) {
2850 // C++ [dcl.init]p5:
2851 //
2852 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002853 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002854
2855 // -- if T is an array type, then each element is value-initialized;
2856 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2857 T = AT->getElementType();
2858
2859 if (const RecordType *RT = T->getAs<RecordType>()) {
2860 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2861 // -- if T is a class type (clause 9) with a user-declared
2862 // constructor (12.1), then the default constructor for T is
2863 // called (and the initialization is ill-formed if T has no
2864 // accessible default constructor);
2865 //
2866 // FIXME: we really want to refer to a single subobject of the array,
2867 // but Entity doesn't have a way to capture that (yet).
2868 if (ClassDecl->hasUserDeclaredConstructor())
2869 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2870
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002871 // -- if T is a (possibly cv-qualified) non-union class type
2872 // without a user-provided constructor, then the object is
2873 // zero-initialized and, if T’s implicitly-declared default
2874 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002875 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002876 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002877 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002878 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2879 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002880 }
2881 }
2882
Douglas Gregor1b303932009-12-22 15:35:07 +00002883 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002884 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2885}
2886
Douglas Gregor85dabae2009-12-16 01:38:02 +00002887/// \brief Attempt default initialization (C++ [dcl.init]p6).
2888static void TryDefaultInitialization(Sema &S,
2889 const InitializedEntity &Entity,
2890 const InitializationKind &Kind,
2891 InitializationSequence &Sequence) {
2892 assert(Kind.getKind() == InitializationKind::IK_Default);
2893
2894 // C++ [dcl.init]p6:
2895 // To default-initialize an object of type T means:
2896 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002897 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002898 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2899 DestType = Array->getElementType();
2900
2901 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2902 // constructor for T is called (and the initialization is ill-formed if
2903 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002904 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002905 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2906 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002907 }
2908
2909 // - otherwise, no initialization is performed.
2910 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2911
2912 // If a program calls for the default initialization of an object of
2913 // a const-qualified type T, T shall be a class type with a user-provided
2914 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002915 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002916 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2917}
2918
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002919/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2920/// which enumerates all conversion functions and performs overload resolution
2921/// to select the best.
2922static void TryUserDefinedConversion(Sema &S,
2923 const InitializedEntity &Entity,
2924 const InitializationKind &Kind,
2925 Expr *Initializer,
2926 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002927 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2928
Douglas Gregor1b303932009-12-22 15:35:07 +00002929 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002930 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2931 QualType SourceType = Initializer->getType();
2932 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2933 "Must have a class type to perform a user-defined conversion");
2934
2935 // Build the candidate set directly in the initialization sequence
2936 // structure, so that it will persist if we fail.
2937 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2938 CandidateSet.clear();
2939
2940 // Determine whether we are allowed to call explicit constructors or
2941 // explicit conversion operators.
2942 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2943
2944 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2945 // The type we're converting to is a class type. Enumerate its constructors
2946 // to see if there is a suitable conversion.
2947 CXXRecordDecl *DestRecordDecl
2948 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2949
Douglas Gregord9848152010-04-26 14:36:57 +00002950 // Try to complete the type we're converting to.
2951 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002952 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002953 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002954 Con != ConEnd; ++Con) {
2955 NamedDecl *D = *Con;
2956 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002957
Douglas Gregord9848152010-04-26 14:36:57 +00002958 // Find the constructor (which may be a template).
2959 CXXConstructorDecl *Constructor = 0;
2960 FunctionTemplateDecl *ConstructorTmpl
2961 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002962 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002963 Constructor = cast<CXXConstructorDecl>(
2964 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002965 else
Douglas Gregord9848152010-04-26 14:36:57 +00002966 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord9848152010-04-26 14:36:57 +00002967
2968 if (!Constructor->isInvalidDecl() &&
2969 Constructor->isConvertingConstructor(AllowExplicit)) {
2970 if (ConstructorTmpl)
2971 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2972 /*ExplicitArgs*/ 0,
2973 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002974 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002975 else
2976 S.AddOverloadCandidate(Constructor, FoundDecl,
2977 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002978 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002979 }
2980 }
2981 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002982 }
Eli Friedman78275202009-12-19 08:11:05 +00002983
2984 SourceLocation DeclLoc = Initializer->getLocStart();
2985
Douglas Gregor540c3b02009-12-14 17:27:33 +00002986 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2987 // The type we're converting from is a class type, enumerate its conversion
2988 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002989
Eli Friedman4afe9a32009-12-20 22:12:03 +00002990 // We can only enumerate the conversion functions for a complete type; if
2991 // the type isn't complete, simply skip this step.
2992 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2993 CXXRecordDecl *SourceRecordDecl
2994 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002995
John McCallad371252010-01-20 00:46:10 +00002996 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002997 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002998 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002999 E = Conversions->end();
3000 I != E; ++I) {
3001 NamedDecl *D = *I;
3002 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3003 if (isa<UsingShadowDecl>(D))
3004 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3005
3006 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3007 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003008 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003009 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003010 else
John McCallda4458e2010-03-31 01:36:47 +00003011 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003012
3013 if (AllowExplicit || !Conv->isExplicit()) {
3014 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003015 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003016 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003017 CandidateSet);
3018 else
John McCalla0296f72010-03-19 07:35:19 +00003019 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003020 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003021 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003022 }
3023 }
3024 }
3025
Douglas Gregor540c3b02009-12-14 17:27:33 +00003026 // Perform overload resolution. If it fails, return the failed result.
3027 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003028 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003029 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003030 Sequence.SetOverloadFailure(
3031 InitializationSequence::FK_UserConversionOverloadFailed,
3032 Result);
3033 return;
3034 }
John McCall0d1da222010-01-12 00:44:57 +00003035
Douglas Gregor540c3b02009-12-14 17:27:33 +00003036 FunctionDecl *Function = Best->Function;
3037
3038 if (isa<CXXConstructorDecl>(Function)) {
3039 // Add the user-defined conversion step. Any cv-qualification conversion is
3040 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003041 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003042 return;
3043 }
3044
3045 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003046 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003047 if (ConvType->getAs<RecordType>()) {
3048 // If we're converting to a class type, there may be an copy if
3049 // the resulting temporary object (possible to create an object of
3050 // a base class type). That copy is not a separate conversion, so
3051 // we just make a note of the actual destination type (possibly a
3052 // base class of the type returned by the conversion function) and
3053 // let the user-defined conversion step handle the conversion.
3054 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3055 return;
3056 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003057
Douglas Gregor5ab11652010-04-17 22:01:05 +00003058 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3059
3060 // If the conversion following the call to the conversion function
3061 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003062 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3063 Best->FinalConversion.Third) {
3064 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003065 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003066 ICS.Standard = Best->FinalConversion;
3067 Sequence.AddConversionSequenceStep(ICS, DestType);
3068 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003069}
3070
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003071InitializationSequence::InitializationSequence(Sema &S,
3072 const InitializedEntity &Entity,
3073 const InitializationKind &Kind,
3074 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003075 unsigned NumArgs)
3076 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003077 ASTContext &Context = S.Context;
3078
3079 // C++0x [dcl.init]p16:
3080 // The semantics of initializers are as follows. The destination type is
3081 // the type of the object or reference being initialized and the source
3082 // type is the type of the initializer expression. The source type is not
3083 // defined when the initializer is a braced-init-list or when it is a
3084 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003085 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003086
3087 if (DestType->isDependentType() ||
3088 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3089 SequenceKind = DependentSequence;
3090 return;
3091 }
3092
3093 QualType SourceType;
3094 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003095 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003096 Initializer = Args[0];
3097 if (!isa<InitListExpr>(Initializer))
3098 SourceType = Initializer->getType();
3099 }
3100
3101 // - If the initializer is a braced-init-list, the object is
3102 // list-initialized (8.5.4).
3103 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3104 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003105 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003106 }
3107
3108 // - If the destination type is a reference type, see 8.5.3.
3109 if (DestType->isReferenceType()) {
3110 // C++0x [dcl.init.ref]p1:
3111 // A variable declared to be a T& or T&&, that is, "reference to type T"
3112 // (8.3.2), shall be initialized by an object, or function, of type T or
3113 // by an object that can be converted into a T.
3114 // (Therefore, multiple arguments are not permitted.)
3115 if (NumArgs != 1)
3116 SetFailed(FK_TooManyInitsForReference);
3117 else
3118 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3119 return;
3120 }
3121
3122 // - If the destination type is an array of characters, an array of
3123 // char16_t, an array of char32_t, or an array of wchar_t, and the
3124 // initializer is a string literal, see 8.5.2.
3125 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3126 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3127 return;
3128 }
3129
3130 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003131 if (Kind.getKind() == InitializationKind::IK_Value ||
3132 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003133 TryValueInitialization(S, Entity, Kind, *this);
3134 return;
3135 }
3136
Douglas Gregor85dabae2009-12-16 01:38:02 +00003137 // Handle default initialization.
3138 if (Kind.getKind() == InitializationKind::IK_Default){
3139 TryDefaultInitialization(S, Entity, Kind, *this);
3140 return;
3141 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003142
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003143 // - Otherwise, if the destination type is an array, the program is
3144 // ill-formed.
3145 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3146 if (AT->getElementType()->isAnyCharacterType())
3147 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3148 else
3149 SetFailed(FK_ArrayNeedsInitList);
3150
3151 return;
3152 }
Eli Friedman78275202009-12-19 08:11:05 +00003153
3154 // Handle initialization in C
3155 if (!S.getLangOptions().CPlusPlus) {
3156 setSequenceKind(CAssignment);
3157 AddCAssignmentStep(DestType);
3158 return;
3159 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003160
3161 // - If the destination type is a (possibly cv-qualified) class type:
3162 if (DestType->isRecordType()) {
3163 // - If the initialization is direct-initialization, or if it is
3164 // copy-initialization where the cv-unqualified version of the
3165 // source type is the same class as, or a derived class of, the
3166 // class of the destination, constructors are considered. [...]
3167 if (Kind.getKind() == InitializationKind::IK_Direct ||
3168 (Kind.getKind() == InitializationKind::IK_Copy &&
3169 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3170 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003171 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003172 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003173 // - Otherwise (i.e., for the remaining copy-initialization cases),
3174 // user-defined conversion sequences that can convert from the source
3175 // type to the destination type or (when a conversion function is
3176 // used) to a derived class thereof are enumerated as described in
3177 // 13.3.1.4, and the best one is chosen through overload resolution
3178 // (13.3).
3179 else
3180 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3181 return;
3182 }
3183
Douglas Gregor85dabae2009-12-16 01:38:02 +00003184 if (NumArgs > 1) {
3185 SetFailed(FK_TooManyInitsForScalar);
3186 return;
3187 }
3188 assert(NumArgs == 1 && "Zero-argument case handled above");
3189
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003190 // - Otherwise, if the source type is a (possibly cv-qualified) class
3191 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003192 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003193 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3194 return;
3195 }
3196
3197 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003198 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003199 // conversions (Clause 4) will be used, if necessary, to convert the
3200 // initializer expression to the cv-unqualified version of the
3201 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003202 if (S.TryImplicitConversion(*this, Entity, Initializer,
3203 /*SuppressUserConversions*/ true,
3204 /*AllowExplicitConversions*/ false,
3205 /*InOverloadResolution*/ false))
3206 SetFailed(InitializationSequence::FK_ConversionFailed);
3207 else
3208 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003209}
3210
3211InitializationSequence::~InitializationSequence() {
3212 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3213 StepEnd = Steps.end();
3214 Step != StepEnd; ++Step)
3215 Step->Destroy();
3216}
3217
3218//===----------------------------------------------------------------------===//
3219// Perform initialization
3220//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003221static Sema::AssignmentAction
3222getAssignmentAction(const InitializedEntity &Entity) {
3223 switch(Entity.getKind()) {
3224 case InitializedEntity::EK_Variable:
3225 case InitializedEntity::EK_New:
3226 return Sema::AA_Initializing;
3227
3228 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003229 if (Entity.getDecl() &&
3230 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3231 return Sema::AA_Sending;
3232
Douglas Gregore1314a62009-12-18 05:02:21 +00003233 return Sema::AA_Passing;
3234
3235 case InitializedEntity::EK_Result:
3236 return Sema::AA_Returning;
3237
3238 case InitializedEntity::EK_Exception:
3239 case InitializedEntity::EK_Base:
3240 llvm_unreachable("No assignment action for C++-specific initialization");
3241 break;
3242
3243 case InitializedEntity::EK_Temporary:
3244 // FIXME: Can we tell apart casting vs. converting?
3245 return Sema::AA_Casting;
3246
3247 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003248 case InitializedEntity::EK_ArrayElement:
3249 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003250 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003251 return Sema::AA_Initializing;
3252 }
3253
3254 return Sema::AA_Converting;
3255}
3256
Douglas Gregor95562572010-04-24 23:45:46 +00003257/// \brief Whether we should binding a created object as a temporary when
3258/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003259static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003260 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003261 case InitializedEntity::EK_ArrayElement:
3262 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003263 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003264 case InitializedEntity::EK_New:
3265 case InitializedEntity::EK_Variable:
3266 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003267 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003268 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003269 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003270 return false;
3271
3272 case InitializedEntity::EK_Parameter:
3273 case InitializedEntity::EK_Temporary:
3274 return true;
3275 }
3276
3277 llvm_unreachable("missed an InitializedEntity kind?");
3278}
3279
Douglas Gregor95562572010-04-24 23:45:46 +00003280/// \brief Whether the given entity, when initialized with an object
3281/// created for that initialization, requires destruction.
3282static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3283 switch (Entity.getKind()) {
3284 case InitializedEntity::EK_Member:
3285 case InitializedEntity::EK_Result:
3286 case InitializedEntity::EK_New:
3287 case InitializedEntity::EK_Base:
3288 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003289 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003290 return false;
3291
3292 case InitializedEntity::EK_Variable:
3293 case InitializedEntity::EK_Parameter:
3294 case InitializedEntity::EK_Temporary:
3295 case InitializedEntity::EK_ArrayElement:
3296 case InitializedEntity::EK_Exception:
3297 return true;
3298 }
3299
3300 llvm_unreachable("missed an InitializedEntity kind?");
3301}
3302
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003303/// \brief Make a (potentially elidable) temporary copy of the object
3304/// provided by the given initializer by calling the appropriate copy
3305/// constructor.
3306///
3307/// \param S The Sema object used for type-checking.
3308///
3309/// \param T The type of the temporary object, which must either by
3310/// the type of the initializer expression or a superclass thereof.
3311///
3312/// \param Enter The entity being initialized.
3313///
3314/// \param CurInit The initializer expression.
3315///
3316/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3317/// is permitted in C++03 (but not C++0x) when binding a reference to
3318/// an rvalue.
3319///
3320/// \returns An expression that copies the initializer expression into
3321/// a temporary object, or an error expression if a copy could not be
3322/// created.
John McCalldadc5752010-08-24 06:29:42 +00003323static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003324 QualType T,
3325 const InitializedEntity &Entity,
3326 ExprResult CurInit,
3327 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003328 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003329 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003330 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003331 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003332 Class = cast<CXXRecordDecl>(Record->getDecl());
3333 if (!Class)
3334 return move(CurInit);
3335
3336 // C++0x [class.copy]p34:
3337 // When certain criteria are met, an implementation is allowed to
3338 // omit the copy/move construction of a class object, even if the
3339 // copy/move constructor and/or destructor for the object have
3340 // side effects. [...]
3341 // - when a temporary class object that has not been bound to a
3342 // reference (12.2) would be copied/moved to a class object
3343 // with the same cv-unqualified type, the copy/move operation
3344 // can be omitted by constructing the temporary object
3345 // directly into the target of the omitted copy/move
3346 //
3347 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003348 // elision for return statements and throw expressions are handled as part
3349 // of constructor initialization, while copy elision for exception handlers
3350 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003351 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003352 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003353 switch (Entity.getKind()) {
3354 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003355 Loc = Entity.getReturnLoc();
3356 break;
3357
3358 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003359 Loc = Entity.getThrowLoc();
3360 break;
3361
3362 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003363 Loc = Entity.getDecl()->getLocation();
3364 break;
3365
Anders Carlsson0bd52402010-01-24 00:19:41 +00003366 case InitializedEntity::EK_ArrayElement:
3367 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003368 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003369 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003370 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003371 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003372 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003373 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003374 Loc = CurInitExpr->getLocStart();
3375 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003376 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003377
3378 // Make sure that the type we are copying is complete.
3379 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3380 return move(CurInit);
3381
Douglas Gregore1314a62009-12-18 05:02:21 +00003382 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003383 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003384 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003385 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003386 Con != ConEnd; ++Con) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003387 // Only consider copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003388 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3389 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor7566e4a2010-04-18 02:16:12 +00003390 !Constructor->isCopyConstructor() ||
3391 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregore1314a62009-12-18 05:02:21 +00003392 continue;
John McCalla0296f72010-03-19 07:35:19 +00003393
3394 DeclAccessPair FoundDecl
3395 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3396 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003397 &CurInitExpr, 1, CandidateSet);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003398 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003399
3400 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00003401 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003402 case OR_Success:
3403 break;
3404
3405 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003406 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3407 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3408 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003409 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003410 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003411 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003412 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003413 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003414 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003415
3416 case OR_Ambiguous:
3417 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003418 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003419 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003420 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003421 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003422
3423 case OR_Deleted:
3424 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003425 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003426 << CurInitExpr->getSourceRange();
3427 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3428 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003429 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003430 }
3431
Douglas Gregor5ab11652010-04-17 22:01:05 +00003432 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003433 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003434 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003435
Anders Carlssona01874b2010-04-21 18:47:17 +00003436 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003437 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003438
3439 if (IsExtraneousCopy) {
3440 // If this is a totally extraneous copy for C++03 reference
3441 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003442 // expression. We don't generate an (elided) copy operation here
3443 // because doing so would require us to pass down a flag to avoid
3444 // infinite recursion, where each step adds another extraneous,
3445 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003446
Douglas Gregor30b52772010-04-18 07:57:34 +00003447 // Instantiate the default arguments of any extra parameters in
3448 // the selected copy constructor, as if we were going to create a
3449 // proper call to the copy constructor.
3450 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3451 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3452 if (S.RequireCompleteType(Loc, Parm->getType(),
3453 S.PDiag(diag::err_call_incomplete_argument)))
3454 break;
3455
3456 // Build the default argument expression; we don't actually care
3457 // if this succeeds or not, because this routine will complain
3458 // if there was a problem.
3459 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3460 }
3461
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003462 return S.Owned(CurInitExpr);
3463 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003464
3465 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003466 // constructor call (we might have derived-to-base conversions, or
3467 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003468 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003469 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003470 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003471
Douglas Gregord0ace022010-04-25 00:55:24 +00003472 // Actually perform the constructor call.
3473 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003474 move_arg(ConstructorArgs),
3475 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003476 CXXConstructExpr::CK_Complete,
3477 SourceRange());
Douglas Gregord0ace022010-04-25 00:55:24 +00003478
3479 // If we're supposed to bind temporaries, do so.
3480 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3481 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3482 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003483}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003484
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003485void InitializationSequence::PrintInitLocationNote(Sema &S,
3486 const InitializedEntity &Entity) {
3487 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3488 if (Entity.getDecl()->getLocation().isInvalid())
3489 return;
3490
3491 if (Entity.getDecl()->getDeclName())
3492 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3493 << Entity.getDecl()->getDeclName();
3494 else
3495 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3496 }
3497}
3498
John McCalldadc5752010-08-24 06:29:42 +00003499ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003500InitializationSequence::Perform(Sema &S,
3501 const InitializedEntity &Entity,
3502 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003503 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003504 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003505 if (SequenceKind == FailedSequence) {
3506 unsigned NumArgs = Args.size();
3507 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003508 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003509 }
3510
3511 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003512 // If the declaration is a non-dependent, incomplete array type
3513 // that has an initializer, then its type will be completed once
3514 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003515 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003516 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003517 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003518 if (const IncompleteArrayType *ArrayT
3519 = S.Context.getAsIncompleteArrayType(DeclType)) {
3520 // FIXME: We don't currently have the ability to accurately
3521 // compute the length of an initializer list without
3522 // performing full type-checking of the initializer list
3523 // (since we have to determine where braces are implicitly
3524 // introduced and such). So, we fall back to making the array
3525 // type a dependently-sized array type with no specified
3526 // bound.
3527 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3528 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003529
Douglas Gregor51e77d52009-12-10 17:56:55 +00003530 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003531 if (DeclaratorDecl *DD = Entity.getDecl()) {
3532 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3533 TypeLoc TL = TInfo->getTypeLoc();
3534 if (IncompleteArrayTypeLoc *ArrayLoc
3535 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3536 Brackets = ArrayLoc->getBracketsRange();
3537 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003538 }
3539
3540 *ResultType
3541 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3542 /*NumElts=*/0,
3543 ArrayT->getSizeModifier(),
3544 ArrayT->getIndexTypeCVRQualifiers(),
3545 Brackets);
3546 }
3547
3548 }
3549 }
3550
Eli Friedmana553d4a2009-12-22 02:35:53 +00003551 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003552 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003553
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003554 if (Args.size() == 0)
3555 return S.Owned((Expr *)0);
3556
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003557 unsigned NumArgs = Args.size();
3558 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3559 SourceLocation(),
3560 (Expr **)Args.release(),
3561 NumArgs,
3562 SourceLocation()));
3563 }
3564
Douglas Gregor85dabae2009-12-16 01:38:02 +00003565 if (SequenceKind == NoInitialization)
3566 return S.Owned((Expr *)0);
3567
Douglas Gregor1b303932009-12-22 15:35:07 +00003568 QualType DestType = Entity.getType().getNonReferenceType();
3569 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003570 // the same as Entity.getDecl()->getType() in cases involving type merging,
3571 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003572 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003573 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003574 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003575
John McCalldadc5752010-08-24 06:29:42 +00003576 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003577
3578 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3579
3580 // For initialization steps that start with a single initializer,
3581 // grab the only argument out the Args and place it into the "current"
3582 // initializer.
3583 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003584 case SK_ResolveAddressOfOverloadedFunction:
3585 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003586 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003587 case SK_CastDerivedToBaseLValue:
3588 case SK_BindReference:
3589 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003590 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003591 case SK_UserConversion:
3592 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003593 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003594 case SK_QualificationConversionRValue:
3595 case SK_ConversionSequence:
3596 case SK_ListInitialization:
3597 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003598 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003599 case SK_ObjCObjectConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00003600 assert(Args.size() == 1);
John McCallc3007a22010-10-26 07:05:15 +00003601 CurInit = ExprResult(Args.get()[0]);
Douglas Gregore1314a62009-12-18 05:02:21 +00003602 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003603 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003604 break;
3605
3606 case SK_ConstructorInitialization:
3607 case SK_ZeroInitialization:
3608 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003609 }
3610
3611 // Walk through the computed steps for the initialization sequence,
3612 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003613 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003614 for (step_iterator Step = step_begin(), StepEnd = step_end();
3615 Step != StepEnd; ++Step) {
3616 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003617 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618
3619 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003620 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621
3622 switch (Step->Kind) {
3623 case SK_ResolveAddressOfOverloadedFunction:
3624 // Overload resolution determined which function invoke; update the
3625 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003626 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003627 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003628 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003629 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003630 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003631 break;
3632
3633 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003634 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003635 case SK_CastDerivedToBaseLValue: {
3636 // We have a derived-to-base cast that produces either an rvalue or an
3637 // lvalue. Perform that cast.
3638
John McCallcf142162010-08-07 06:22:56 +00003639 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003640
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003641 // Casts to inaccessible base classes are allowed with C-style casts.
3642 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3643 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3644 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003645 CurInitExpr->getSourceRange(),
3646 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003647 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648
Douglas Gregor88d292c2010-05-13 16:44:06 +00003649 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3650 QualType T = SourceType;
3651 if (const PointerType *Pointer = T->getAs<PointerType>())
3652 T = Pointer->getPointeeType();
3653 if (const RecordType *RecordTy = T->getAs<RecordType>())
3654 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3655 cast<CXXRecordDecl>(RecordTy->getDecl()));
3656 }
3657
John McCall2536c6d2010-08-25 10:28:54 +00003658 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003659 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003660 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003661 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003662 VK_XValue :
3663 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003664 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3665 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003666 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003667 CurInit.get(),
3668 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003669 break;
3670 }
3671
3672 case SK_BindReference:
3673 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3674 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3675 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003676 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003677 << BitField->getDeclName()
3678 << CurInitExpr->getSourceRange();
3679 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003680 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003681 }
Anders Carlssona91be642010-01-29 02:47:33 +00003682
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003683 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003684 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003685 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3686 << Entity.getType().isVolatileQualified()
3687 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003688 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003689 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003690 }
3691
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003692 // Reference binding does not have any corresponding ASTs.
3693
3694 // Check exception specifications
3695 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003696 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003697
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003698 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003699
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003700 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003701 // Reference binding does not have any corresponding ASTs.
3702
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003703 // Check exception specifications
3704 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003705 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003706
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003707 break;
3708
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003709 case SK_ExtraneousCopyToTemporary:
3710 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3711 /*IsExtraneousCopy=*/true);
3712 break;
3713
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003714 case SK_UserConversion: {
3715 // We have a user-defined conversion that invokes either a constructor
3716 // or a conversion function.
John McCalle3027922010-08-25 11:45:40 +00003717 CastKind CastKind = CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003718 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003719 FunctionDecl *Fn = Step->Function.Function;
3720 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003721 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003722 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003723 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003724 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003725 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003726 SourceLocation Loc = CurInitExpr->getLocStart();
3727 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003728
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003729 // Determine the arguments required to actually perform the constructor
3730 // call.
3731 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00003732 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003733 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003734 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003735
3736 // Build the an expression that constructs a temporary.
3737 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003738 move_arg(ConstructorArgs),
3739 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003740 CXXConstructExpr::CK_Complete,
3741 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003742 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003743 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003744
Anders Carlssona01874b2010-04-21 18:47:17 +00003745 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003746 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003747 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003748
John McCalle3027922010-08-25 11:45:40 +00003749 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003750 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3751 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3752 S.IsDerivedFrom(SourceType, Class))
3753 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003754
3755 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003756 } else {
3757 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003758 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003759 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003760 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003761 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003762 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003763
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003764 // FIXME: Should we move this initialization into a separate
3765 // derived-to-base conversion? I believe the answer is "no", because
3766 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003767 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003768 FoundFn, Conversion))
John McCallfaf5fb42010-08-26 23:41:50 +00003769 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003770
3771 // Do a little dance to make sure that CurInit has the proper
3772 // pointer.
3773 CurInit.release();
3774
3775 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003776 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3777 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003778 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003779 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003780
John McCalle3027922010-08-25 11:45:40 +00003781 CastKind = CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003782
3783 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003784 }
3785
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003786 bool RequiresCopy = !IsCopy &&
3787 getKind() != InitializationSequence::ReferenceBinding;
3788 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003789 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003790 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3791 CurInitExpr = static_cast<Expr *>(CurInit.get());
3792 QualType T = CurInitExpr->getType();
3793 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003794 CXXDestructorDecl *Destructor
3795 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003796 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3797 S.PDiag(diag::err_access_dtor_temp) << T);
3798 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003799 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00003800 }
3801 }
3802
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003803 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003804 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003805 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3806 CurInitExpr->getType(),
3807 CastKind, CurInitExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00003808 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003809
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003810 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003811 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3812 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003813
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003814 break;
3815 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003816
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003817 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003818 case SK_QualificationConversionXValue:
3819 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003820 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003821 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003822 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003823 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003824 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003825 VK_XValue :
3826 VK_RValue);
John McCalle3027922010-08-25 11:45:40 +00003827 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003828 CurInit.release();
3829 CurInit = S.Owned(CurInitExpr);
3830 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003831 }
3832
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003833 case SK_ConversionSequence: {
3834 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3835
3836 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3837 Sema::AA_Converting, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003838 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003839
3840 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003841 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003842 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003843 }
3844
Douglas Gregor51e77d52009-12-10 17:56:55 +00003845 case SK_ListInitialization: {
3846 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3847 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003848 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003849 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003850
3851 CurInit.release();
3852 CurInit = S.Owned(InitList);
3853 break;
3854 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003855
3856 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003857 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003858 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003859 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003860
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003861 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003862 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003863 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3864 ? Kind.getEqualLoc()
3865 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003866
3867 if (Kind.getKind() == InitializationKind::IK_Default) {
3868 // Force even a trivial, implicit default constructor to be
3869 // semantically checked. We do this explicitly because we don't build
3870 // the definition for completely trivial constructors.
3871 CXXRecordDecl *ClassDecl = Constructor->getParent();
3872 assert(ClassDecl && "No parent class for constructor.");
3873 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3874 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3875 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3876 }
3877
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003878 // Determine the arguments required to actually perform the constructor
3879 // call.
3880 if (S.CompleteConstructorCall(Constructor, move(Args),
3881 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003882 return ExprError();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003883
Chandler Carruthc9262402010-08-23 07:55:51 +00003884
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003885 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003886 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003887 (Kind.getKind() == InitializationKind::IK_Direct ||
3888 Kind.getKind() == InitializationKind::IK_Value)) {
3889 // An explicitly-constructed temporary, e.g., X(1, 2).
3890 unsigned NumExprs = ConstructorArgs.size();
3891 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003892 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003893 S.DiagnoseUseOfDecl(Constructor, Loc);
3894
Douglas Gregor2b88c112010-09-08 00:15:04 +00003895 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3896 if (!TSInfo)
3897 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3898
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003899 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3900 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00003901 TSInfo,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003902 Exprs,
3903 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00003904 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00003905 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003906 } else {
3907 CXXConstructExpr::ConstructionKind ConstructKind =
3908 CXXConstructExpr::CK_Complete;
3909
3910 if (Entity.getKind() == InitializedEntity::EK_Base) {
3911 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3912 CXXConstructExpr::CK_VirtualBase :
3913 CXXConstructExpr::CK_NonVirtualBase;
3914 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003915
Chandler Carruth01718152010-10-25 08:47:36 +00003916 // Only get the parenthesis range if it is a direct construction.
3917 SourceRange parenRange =
3918 Kind.getKind() == InitializationKind::IK_Direct ?
3919 Kind.getParenRange() : SourceRange();
3920
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003921 // If the entity allows NRVO, mark the construction as elidable
3922 // unconditionally.
3923 if (Entity.allowsNRVO())
3924 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3925 Constructor, /*Elidable=*/true,
3926 move_arg(ConstructorArgs),
3927 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00003928 ConstructKind,
3929 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003930 else
3931 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3932 Constructor,
3933 move_arg(ConstructorArgs),
3934 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00003935 ConstructKind,
3936 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003937 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003938 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003939 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003940
3941 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003942 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003943 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003944 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003945
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003946 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003947 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003948
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003949 break;
3950 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003951
3952 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003953 step_iterator NextStep = Step;
3954 ++NextStep;
3955 if (NextStep != StepEnd &&
3956 NextStep->Kind == SK_ConstructorInitialization) {
3957 // The need for zero-initialization is recorded directly into
3958 // the call to the object's constructor within the next step.
3959 ConstructorInitRequiresZeroInit = true;
3960 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3961 S.getLangOptions().CPlusPlus &&
3962 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00003963 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3964 if (!TSInfo)
3965 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
3966 Kind.getRange().getBegin());
3967
3968 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
3969 TSInfo->getType().getNonLValueExprType(S.Context),
3970 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003971 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003972 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003973 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003974 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003975 break;
3976 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003977
3978 case SK_CAssignment: {
3979 QualType SourceType = CurInitExpr->getType();
3980 Sema::AssignConvertType ConvTy =
3981 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003982
3983 // If this is a call, allow conversion to a transparent union.
3984 if (ConvTy != Sema::Compatible &&
3985 Entity.getKind() == InitializedEntity::EK_Parameter &&
3986 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3987 == Sema::Compatible)
3988 ConvTy = Sema::Compatible;
3989
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003990 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00003991 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3992 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003993 CurInitExpr,
3994 getAssignmentAction(Entity),
3995 &Complained)) {
3996 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003997 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003998 } else if (Complained)
3999 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004000
4001 CurInit.release();
4002 CurInit = S.Owned(CurInitExpr);
4003 break;
4004 }
Eli Friedman78275202009-12-19 08:11:05 +00004005
4006 case SK_StringInit: {
4007 QualType Ty = Step->Type;
4008 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
4009 break;
4010 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004011
4012 case SK_ObjCObjectConversion:
4013 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004014 CK_ObjCObjectLValueCast,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004015 S.CastCategory(CurInitExpr));
4016 CurInit.release();
4017 CurInit = S.Owned(CurInitExpr);
4018 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004019 }
4020 }
4021
4022 return move(CurInit);
4023}
4024
4025//===----------------------------------------------------------------------===//
4026// Diagnose initialization failures
4027//===----------------------------------------------------------------------===//
4028bool InitializationSequence::Diagnose(Sema &S,
4029 const InitializedEntity &Entity,
4030 const InitializationKind &Kind,
4031 Expr **Args, unsigned NumArgs) {
4032 if (SequenceKind != FailedSequence)
4033 return false;
4034
Douglas Gregor1b303932009-12-22 15:35:07 +00004035 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004036 switch (Failure) {
4037 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004038 // FIXME: Customize for the initialized entity?
4039 if (NumArgs == 0)
4040 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4041 << DestType.getNonReferenceType();
4042 else // FIXME: diagnostic below could be better!
4043 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4044 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004045 break;
4046
4047 case FK_ArrayNeedsInitList:
4048 case FK_ArrayNeedsInitListOrStringLiteral:
4049 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4050 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4051 break;
4052
John McCall16df1e52010-03-30 21:47:33 +00004053 case FK_AddressOfOverloadFailed: {
4054 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004055 S.ResolveAddressOfOverloadedFunction(Args[0],
4056 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004057 true,
4058 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004059 break;
John McCall16df1e52010-03-30 21:47:33 +00004060 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004061
4062 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004063 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004064 switch (FailedOverloadResult) {
4065 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004066 if (Failure == FK_UserConversionOverloadFailed)
4067 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4068 << Args[0]->getType() << DestType
4069 << Args[0]->getSourceRange();
4070 else
4071 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4072 << DestType << Args[0]->getType()
4073 << Args[0]->getSourceRange();
4074
John McCall5c32be02010-08-24 20:38:10 +00004075 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004076 break;
4077
4078 case OR_No_Viable_Function:
4079 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4080 << Args[0]->getType() << DestType.getNonReferenceType()
4081 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004082 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004083 break;
4084
4085 case OR_Deleted: {
4086 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4087 << Args[0]->getType() << DestType.getNonReferenceType()
4088 << Args[0]->getSourceRange();
4089 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004090 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004091 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4092 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004093 if (Ovl == OR_Deleted) {
4094 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4095 << Best->Function->isDeleted();
4096 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004097 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004098 }
4099 break;
4100 }
4101
4102 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004103 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004104 break;
4105 }
4106 break;
4107
4108 case FK_NonConstLValueReferenceBindingToTemporary:
4109 case FK_NonConstLValueReferenceBindingToUnrelated:
4110 S.Diag(Kind.getLocation(),
4111 Failure == FK_NonConstLValueReferenceBindingToTemporary
4112 ? diag::err_lvalue_reference_bind_to_temporary
4113 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004114 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004115 << DestType.getNonReferenceType()
4116 << Args[0]->getType()
4117 << Args[0]->getSourceRange();
4118 break;
4119
4120 case FK_RValueReferenceBindingToLValue:
4121 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4122 << Args[0]->getSourceRange();
4123 break;
4124
4125 case FK_ReferenceInitDropsQualifiers:
4126 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4127 << DestType.getNonReferenceType()
4128 << Args[0]->getType()
4129 << Args[0]->getSourceRange();
4130 break;
4131
4132 case FK_ReferenceInitFailed:
4133 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4134 << DestType.getNonReferenceType()
4135 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4136 << Args[0]->getType()
4137 << Args[0]->getSourceRange();
4138 break;
4139
4140 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004141 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4142 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004143 << DestType
4144 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4145 << Args[0]->getType()
4146 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004147 break;
4148
4149 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004150 SourceRange R;
4151
4152 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004153 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004154 InitList->getLocEnd());
Douglas Gregor8ec51732010-09-08 21:40:08 +00004155 else
4156 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004157
Douglas Gregor8ec51732010-09-08 21:40:08 +00004158 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4159 if (Kind.isCStyleOrFunctionalCast())
4160 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4161 << R;
4162 else
4163 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4164 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004165 break;
4166 }
4167
4168 case FK_ReferenceBindingToInitList:
4169 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4170 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4171 break;
4172
4173 case FK_InitListBadDestinationType:
4174 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4175 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4176 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004177
4178 case FK_ConstructorOverloadFailed: {
4179 SourceRange ArgsRange;
4180 if (NumArgs)
4181 ArgsRange = SourceRange(Args[0]->getLocStart(),
4182 Args[NumArgs - 1]->getLocEnd());
4183
4184 // FIXME: Using "DestType" for the entity we're printing is probably
4185 // bad.
4186 switch (FailedOverloadResult) {
4187 case OR_Ambiguous:
4188 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4189 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004190 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4191 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004192 break;
4193
4194 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004195 if (Kind.getKind() == InitializationKind::IK_Default &&
4196 (Entity.getKind() == InitializedEntity::EK_Base ||
4197 Entity.getKind() == InitializedEntity::EK_Member) &&
4198 isa<CXXConstructorDecl>(S.CurContext)) {
4199 // This is implicit default initialization of a member or
4200 // base within a constructor. If no viable function was
4201 // found, notify the user that she needs to explicitly
4202 // initialize this base/member.
4203 CXXConstructorDecl *Constructor
4204 = cast<CXXConstructorDecl>(S.CurContext);
4205 if (Entity.getKind() == InitializedEntity::EK_Base) {
4206 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4207 << Constructor->isImplicit()
4208 << S.Context.getTypeDeclType(Constructor->getParent())
4209 << /*base=*/0
4210 << Entity.getType();
4211
4212 RecordDecl *BaseDecl
4213 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4214 ->getDecl();
4215 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4216 << S.Context.getTagDeclType(BaseDecl);
4217 } else {
4218 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4219 << Constructor->isImplicit()
4220 << S.Context.getTypeDeclType(Constructor->getParent())
4221 << /*member=*/1
4222 << Entity.getName();
4223 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4224
4225 if (const RecordType *Record
4226 = Entity.getType()->getAs<RecordType>())
4227 S.Diag(Record->getDecl()->getLocation(),
4228 diag::note_previous_decl)
4229 << S.Context.getTagDeclType(Record->getDecl());
4230 }
4231 break;
4232 }
4233
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004234 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4235 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004236 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004237 break;
4238
4239 case OR_Deleted: {
4240 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4241 << true << DestType << ArgsRange;
4242 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004243 OverloadingResult Ovl
4244 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004245 if (Ovl == OR_Deleted) {
4246 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4247 << Best->Function->isDeleted();
4248 } else {
4249 llvm_unreachable("Inconsistent overload resolution?");
4250 }
4251 break;
4252 }
4253
4254 case OR_Success:
4255 llvm_unreachable("Conversion did not fail!");
4256 break;
4257 }
4258 break;
4259 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004260
4261 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004262 if (Entity.getKind() == InitializedEntity::EK_Member &&
4263 isa<CXXConstructorDecl>(S.CurContext)) {
4264 // This is implicit default-initialization of a const member in
4265 // a constructor. Complain that it needs to be explicitly
4266 // initialized.
4267 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4268 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4269 << Constructor->isImplicit()
4270 << S.Context.getTypeDeclType(Constructor->getParent())
4271 << /*const=*/1
4272 << Entity.getName();
4273 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4274 << Entity.getName();
4275 } else {
4276 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4277 << DestType << (bool)DestType->getAs<RecordType>();
4278 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004279 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004280
4281 case FK_Incomplete:
4282 S.RequireCompleteType(Kind.getLocation(), DestType,
4283 diag::err_init_incomplete_type);
4284 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 }
4286
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004287 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004288 return true;
4289}
Douglas Gregore1314a62009-12-18 05:02:21 +00004290
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004291void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4292 switch (SequenceKind) {
4293 case FailedSequence: {
4294 OS << "Failed sequence: ";
4295 switch (Failure) {
4296 case FK_TooManyInitsForReference:
4297 OS << "too many initializers for reference";
4298 break;
4299
4300 case FK_ArrayNeedsInitList:
4301 OS << "array requires initializer list";
4302 break;
4303
4304 case FK_ArrayNeedsInitListOrStringLiteral:
4305 OS << "array requires initializer list or string literal";
4306 break;
4307
4308 case FK_AddressOfOverloadFailed:
4309 OS << "address of overloaded function failed";
4310 break;
4311
4312 case FK_ReferenceInitOverloadFailed:
4313 OS << "overload resolution for reference initialization failed";
4314 break;
4315
4316 case FK_NonConstLValueReferenceBindingToTemporary:
4317 OS << "non-const lvalue reference bound to temporary";
4318 break;
4319
4320 case FK_NonConstLValueReferenceBindingToUnrelated:
4321 OS << "non-const lvalue reference bound to unrelated type";
4322 break;
4323
4324 case FK_RValueReferenceBindingToLValue:
4325 OS << "rvalue reference bound to an lvalue";
4326 break;
4327
4328 case FK_ReferenceInitDropsQualifiers:
4329 OS << "reference initialization drops qualifiers";
4330 break;
4331
4332 case FK_ReferenceInitFailed:
4333 OS << "reference initialization failed";
4334 break;
4335
4336 case FK_ConversionFailed:
4337 OS << "conversion failed";
4338 break;
4339
4340 case FK_TooManyInitsForScalar:
4341 OS << "too many initializers for scalar";
4342 break;
4343
4344 case FK_ReferenceBindingToInitList:
4345 OS << "referencing binding to initializer list";
4346 break;
4347
4348 case FK_InitListBadDestinationType:
4349 OS << "initializer list for non-aggregate, non-scalar type";
4350 break;
4351
4352 case FK_UserConversionOverloadFailed:
4353 OS << "overloading failed for user-defined conversion";
4354 break;
4355
4356 case FK_ConstructorOverloadFailed:
4357 OS << "constructor overloading failed";
4358 break;
4359
4360 case FK_DefaultInitOfConst:
4361 OS << "default initialization of a const variable";
4362 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004363
4364 case FK_Incomplete:
4365 OS << "initialization of incomplete type";
4366 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004367 }
4368 OS << '\n';
4369 return;
4370 }
4371
4372 case DependentSequence:
4373 OS << "Dependent sequence: ";
4374 return;
4375
4376 case UserDefinedConversion:
4377 OS << "User-defined conversion sequence: ";
4378 break;
4379
4380 case ConstructorInitialization:
4381 OS << "Constructor initialization sequence: ";
4382 break;
4383
4384 case ReferenceBinding:
4385 OS << "Reference binding: ";
4386 break;
4387
4388 case ListInitialization:
4389 OS << "List initialization: ";
4390 break;
4391
4392 case ZeroInitialization:
4393 OS << "Zero initialization\n";
4394 return;
4395
4396 case NoInitialization:
4397 OS << "No initialization\n";
4398 return;
4399
4400 case StandardConversion:
4401 OS << "Standard conversion: ";
4402 break;
4403
4404 case CAssignment:
4405 OS << "C assignment: ";
4406 break;
4407
4408 case StringInit:
4409 OS << "String initialization: ";
4410 break;
4411 }
4412
4413 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4414 if (S != step_begin()) {
4415 OS << " -> ";
4416 }
4417
4418 switch (S->Kind) {
4419 case SK_ResolveAddressOfOverloadedFunction:
4420 OS << "resolve address of overloaded function";
4421 break;
4422
4423 case SK_CastDerivedToBaseRValue:
4424 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4425 break;
4426
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004427 case SK_CastDerivedToBaseXValue:
4428 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4429 break;
4430
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004431 case SK_CastDerivedToBaseLValue:
4432 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4433 break;
4434
4435 case SK_BindReference:
4436 OS << "bind reference to lvalue";
4437 break;
4438
4439 case SK_BindReferenceToTemporary:
4440 OS << "bind reference to a temporary";
4441 break;
4442
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004443 case SK_ExtraneousCopyToTemporary:
4444 OS << "extraneous C++03 copy to temporary";
4445 break;
4446
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004447 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004448 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004449 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004450
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004451 case SK_QualificationConversionRValue:
4452 OS << "qualification conversion (rvalue)";
4453
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004454 case SK_QualificationConversionXValue:
4455 OS << "qualification conversion (xvalue)";
4456
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004457 case SK_QualificationConversionLValue:
4458 OS << "qualification conversion (lvalue)";
4459 break;
4460
4461 case SK_ConversionSequence:
4462 OS << "implicit conversion sequence (";
4463 S->ICS->DebugPrint(); // FIXME: use OS
4464 OS << ")";
4465 break;
4466
4467 case SK_ListInitialization:
4468 OS << "list initialization";
4469 break;
4470
4471 case SK_ConstructorInitialization:
4472 OS << "constructor initialization";
4473 break;
4474
4475 case SK_ZeroInitialization:
4476 OS << "zero initialization";
4477 break;
4478
4479 case SK_CAssignment:
4480 OS << "C assignment";
4481 break;
4482
4483 case SK_StringInit:
4484 OS << "string initialization";
4485 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004486
4487 case SK_ObjCObjectConversion:
4488 OS << "Objective-C object conversion";
4489 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004490 }
4491 }
4492}
4493
4494void InitializationSequence::dump() const {
4495 dump(llvm::errs());
4496}
4497
Douglas Gregore1314a62009-12-18 05:02:21 +00004498//===----------------------------------------------------------------------===//
4499// Initialization helper functions
4500//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004501ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004502Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4503 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004504 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004505 if (Init.isInvalid())
4506 return ExprError();
4507
4508 Expr *InitE = (Expr *)Init.get();
4509 assert(InitE && "No initialization expression?");
4510
4511 if (EqualLoc.isInvalid())
4512 EqualLoc = InitE->getLocStart();
4513
4514 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4515 EqualLoc);
4516 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4517 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004518 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004519}