blob: bac9f8fa7556a249af8ad582f1da25a7b2237928 [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) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000842 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000843 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000844 unsigned maxElements = VT->getNumElements();
845 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000846 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000847
Nate Begeman5ec4b312009-08-10 23:49:36 +0000848 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000849 InitializedEntity ElementEntity =
850 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000851
Anders Carlsson6cabf312010-01-23 23:23:01 +0000852 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
853 // Don't attempt to go past the end of the init list
854 if (Index >= IList->getNumInits())
855 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000856
Anders Carlsson6cabf312010-01-23 23:23:01 +0000857 ElementEntity.setElementIndex(Index);
858 CheckSubElementType(ElementEntity, IList, elementType, Index,
859 StructuredList, StructuredIndex);
860 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000861 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000862 InitializedEntity ElementEntity =
863 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
864
Nate Begeman5ec4b312009-08-10 23:49:36 +0000865 // OpenCL initializers allows vectors to be constructed from vectors.
866 for (unsigned i = 0; i < maxElements; ++i) {
867 // Don't attempt to go past the end of the init list
868 if (Index >= IList->getNumInits())
869 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000870
871 ElementEntity.setElementIndex(Index);
872
Nate Begeman5ec4b312009-08-10 23:49:36 +0000873 QualType IType = IList->getInit(Index)->getType();
874 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000875 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000876 StructuredList, StructuredIndex);
877 ++numEltsInit;
878 } else {
Nate Begeman5da51d32010-07-07 22:26:56 +0000879 QualType VecType;
John McCall9dd450b2009-09-21 23:43:11 +0000880 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000881 unsigned numIElts = IVT->getNumElements();
Nate Begeman5da51d32010-07-07 22:26:56 +0000882
883 if (IType->isExtVectorType())
884 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
885 else
886 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
887 IVT->getAltiVecSpecific());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000888 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000889 StructuredList, StructuredIndex);
890 numEltsInit += numIElts;
891 }
892 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
John Thompson7bc797b2010-04-20 23:21:17 +0000895 // OpenCL requires all elements to be initialized.
Nate Begeman5ec4b312009-08-10 23:49:36 +0000896 if (numEltsInit != maxElements)
Chris Lattnerb596ac72010-04-20 05:19:10 +0000897 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman5ec4b312009-08-10 23:49:36 +0000898 SemaRef.Diag(IList->getSourceRange().getBegin(),
899 diag::err_vector_incorrect_num_initializers)
900 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000901 }
902}
903
Anders Carlsson6cabf312010-01-23 23:23:01 +0000904void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000905 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000906 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000907 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000908 unsigned &Index,
909 InitListExpr *StructuredList,
910 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000911 // Check for the special-case of initializing an array with a string.
912 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000913 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
914 SemaRef.Context)) {
915 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000916 // We place the string literal directly into the resulting
917 // initializer list. This is the only place where the structure
918 // of the structured initializer list doesn't match exactly,
919 // because doing so would involve allocating one character
920 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000921 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000922 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000923 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000924 return;
925 }
926 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000927 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000928 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000929 // Check for VLAs; in standard C it would be possible to check this
930 // earlier, but I don't know where clang accepts VLAs (gcc accepts
931 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000932 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000933 diag::err_variable_object_no_init)
934 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000935 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000936 ++Index;
937 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000938 return;
939 }
940
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000941 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000942 llvm::APSInt maxElements(elementIndex.getBitWidth(),
943 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000944 bool maxElementsKnown = false;
945 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000946 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000947 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000948 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000949 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000950 maxElementsKnown = true;
951 }
952
Chris Lattnerb0912a52009-02-24 22:50:46 +0000953 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000954 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000955 while (Index < IList->getNumInits()) {
956 Expr *Init = IList->getInit(Index);
957 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000958 // If we're not the subobject that matches up with the '{' for
959 // the designator, we shouldn't be handling the
960 // designator. Return immediately.
961 if (!SubobjectIsDesignatorContext)
962 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000963
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000964 // Handle this designated initializer. elementIndex will be
965 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000966 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000967 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000968 StructuredList, StructuredIndex, true,
969 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000970 hadError = true;
971 continue;
972 }
973
Douglas Gregor033d1252009-01-23 16:54:12 +0000974 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
975 maxElements.extend(elementIndex.getBitWidth());
976 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
977 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000978 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000979
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000980 // If the array is of incomplete type, keep track of the number of
981 // elements in the initializer.
982 if (!maxElementsKnown && elementIndex > maxElements)
983 maxElements = elementIndex;
984
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000985 continue;
986 }
987
988 // If we know the maximum number of elements, and we've already
989 // hit it, stop consuming elements in the initializer list.
990 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000991 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000992
Anders Carlsson6cabf312010-01-23 23:23:01 +0000993 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000994 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000995 Entity);
996 // Check this element.
997 CheckSubElementType(ElementEntity, IList, elementType, Index,
998 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000999 ++elementIndex;
1000
1001 // If the array is of incomplete type, keep track of the number of
1002 // elements in the initializer.
1003 if (!maxElementsKnown && elementIndex > maxElements)
1004 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001005 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001006 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001007 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001008 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001009 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001010 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001011 // Sizing an array implicitly to zero is not allowed by ISO C,
1012 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001013 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001014 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001015 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001016
Mike Stump11289f42009-09-09 15:08:12 +00001017 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001018 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001019 }
1020}
1021
Anders Carlsson6cabf312010-01-23 23:23:01 +00001022void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001023 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001024 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001025 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001026 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001027 unsigned &Index,
1028 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001029 unsigned &StructuredIndex,
1030 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001031 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001032
Eli Friedman23a9e312008-05-19 19:16:24 +00001033 // If the record is invalid, some of it's members are invalid. To avoid
1034 // confusion, we forgo checking the intializer for the entire record.
1035 if (structDecl->isInvalidDecl()) {
1036 hadError = true;
1037 return;
Mike Stump11289f42009-09-09 15:08:12 +00001038 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001039
1040 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1041 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001042 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001043 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001044 Field != FieldEnd; ++Field) {
1045 if (Field->getDeclName()) {
1046 StructuredList->setInitializedFieldInUnion(*Field);
1047 break;
1048 }
1049 }
1050 return;
1051 }
1052
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001053 // If structDecl is a forward declaration, this loop won't do
1054 // anything except look at designated initializers; That's okay,
1055 // because an error should get printed out elsewhere. It might be
1056 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001057 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001058 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001059 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001060 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001061 while (Index < IList->getNumInits()) {
1062 Expr *Init = IList->getInit(Index);
1063
1064 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001065 // If we're not the subobject that matches up with the '{' for
1066 // the designator, we shouldn't be handling the
1067 // designator. Return immediately.
1068 if (!SubobjectIsDesignatorContext)
1069 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001070
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001071 // Handle this designated initializer. Field will be updated to
1072 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001073 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001074 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001075 StructuredList, StructuredIndex,
1076 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001077 hadError = true;
1078
Douglas Gregora9add4e2009-02-12 19:00:39 +00001079 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001080
1081 // Disable check for missing fields when designators are used.
1082 // This matches gcc behaviour.
1083 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001084 continue;
1085 }
1086
1087 if (Field == FieldEnd) {
1088 // We've run out of fields. We're done.
1089 break;
1090 }
1091
Douglas Gregora9add4e2009-02-12 19:00:39 +00001092 // We've already initialized a member of a union. We're done.
1093 if (InitializedSomething && DeclType->isUnionType())
1094 break;
1095
Douglas Gregor91f84212008-12-11 16:49:14 +00001096 // If we've hit the flexible array member at the end, we're done.
1097 if (Field->getType()->isIncompleteArrayType())
1098 break;
1099
Douglas Gregor51695702009-01-29 16:53:55 +00001100 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001101 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001102 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001103 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001104 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001105
Anders Carlsson6cabf312010-01-23 23:23:01 +00001106 InitializedEntity MemberEntity =
1107 InitializedEntity::InitializeMember(*Field, &Entity);
1108 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1109 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001110 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001111
1112 if (DeclType->isUnionType()) {
1113 // Initialize the first field within the union.
1114 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001115 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001116
1117 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001118 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001119
John McCalle40b58e2010-03-11 19:32:38 +00001120 // Emit warnings for missing struct field initializers.
Douglas Gregor8fba4f22010-06-18 21:43:10 +00001121 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001122 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1123 // It is possible we have one or more unnamed bitfields remaining.
1124 // Find first (if any) named field and emit warning.
1125 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1126 it != end; ++it) {
1127 if (!it->isUnnamedBitfield()) {
1128 SemaRef.Diag(IList->getSourceRange().getEnd(),
1129 diag::warn_missing_field_initializers) << it->getName();
1130 break;
1131 }
1132 }
1133 }
1134
Mike Stump11289f42009-09-09 15:08:12 +00001135 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001136 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001137 return;
1138
1139 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001140 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001141 (!isa<InitListExpr>(IList->getInit(Index)) ||
1142 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001143 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001144 diag::err_flexible_array_init_nonempty)
1145 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001146 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001147 << *Field;
1148 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001149 ++Index;
1150 return;
1151 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001152 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001153 diag::ext_flexible_array_init)
1154 << IList->getInit(Index)->getSourceRange().getBegin();
1155 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1156 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001157 }
1158
Anders Carlsson6cabf312010-01-23 23:23:01 +00001159 InitializedEntity MemberEntity =
1160 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001161
Anders Carlsson6cabf312010-01-23 23:23:01 +00001162 if (isa<InitListExpr>(IList->getInit(Index)))
1163 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1164 StructuredList, StructuredIndex);
1165 else
1166 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001167 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001168}
Steve Narofff8ecff22008-05-01 22:18:59 +00001169
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001170/// \brief Similar to Sema::BuildAnonymousStructUnionMemberPath() but builds a
1171/// relative path and has strict checks.
1172static void BuildRelativeAnonymousStructUnionMemberPath(FieldDecl *Field,
1173 llvm::SmallVectorImpl<FieldDecl *> &Path,
1174 DeclContext *BaseDC) {
1175 Path.push_back(Field);
1176 for (DeclContext *Ctx = Field->getDeclContext();
1177 !Ctx->Equals(BaseDC);
1178 Ctx = Ctx->getParent()) {
1179 ValueDecl *AnonObject =
1180 cast<RecordDecl>(Ctx)->getAnonymousStructOrUnionObject();
1181 FieldDecl *AnonField = cast<FieldDecl>(AnonObject);
1182 Path.push_back(AnonField);
1183 }
1184}
1185
Douglas Gregord5846a12009-04-15 06:41:24 +00001186/// \brief Expand a field designator that refers to a member of an
1187/// anonymous struct or union into a series of field designators that
1188/// refers to the field within the appropriate subobject.
1189///
1190/// Field/FieldIndex will be updated to point to the (new)
1191/// currently-designated field.
1192static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001193 DesignatedInitExpr *DIE,
1194 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001195 FieldDecl *Field,
1196 RecordDecl::field_iterator &FieldIter,
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001197 unsigned &FieldIndex,
1198 DeclContext *BaseDC) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001199 typedef DesignatedInitExpr::Designator Designator;
1200
1201 // Build the path from the current object to the member of the
1202 // anonymous struct/union (backwards).
1203 llvm::SmallVector<FieldDecl *, 4> Path;
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001204 BuildRelativeAnonymousStructUnionMemberPath(Field, Path, BaseDC);
Mike Stump11289f42009-09-09 15:08:12 +00001205
Douglas Gregord5846a12009-04-15 06:41:24 +00001206 // Build the replacement designators.
1207 llvm::SmallVector<Designator, 4> Replacements;
1208 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1209 FI = Path.rbegin(), FIEnd = Path.rend();
1210 FI != FIEnd; ++FI) {
1211 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001212 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001213 DIE->getDesignator(DesigIdx)->getDotLoc(),
1214 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1215 else
1216 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1217 SourceLocation()));
1218 Replacements.back().setField(*FI);
1219 }
1220
1221 // Expand the current designator into the set of replacement
1222 // designators, so we have a full subobject path down to where the
1223 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001224 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001225 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001226
Douglas Gregord5846a12009-04-15 06:41:24 +00001227 // Update FieldIter/FieldIndex;
1228 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001229 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001230 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001231 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001232 FieldIter != FEnd; ++FieldIter) {
1233 if (FieldIter->isUnnamedBitfield())
1234 continue;
1235
1236 if (*FieldIter == Path.back())
1237 return;
1238
1239 ++FieldIndex;
1240 }
1241
1242 assert(false && "Unable to find anonymous struct/union field");
1243}
1244
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001245/// @brief Check the well-formedness of a C99 designated initializer.
1246///
1247/// Determines whether the designated initializer @p DIE, which
1248/// resides at the given @p Index within the initializer list @p
1249/// IList, is well-formed for a current object of type @p DeclType
1250/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001251/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001252/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001253///
1254/// @param IList The initializer list in which this designated
1255/// initializer occurs.
1256///
Douglas Gregora5324162009-04-15 04:56:10 +00001257/// @param DIE The designated initializer expression.
1258///
1259/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001260///
1261/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1262/// into which the designation in @p DIE should refer.
1263///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001264/// @param NextField If non-NULL and the first designator in @p DIE is
1265/// a field, this will be set to the field declaration corresponding
1266/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001267///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001268/// @param NextElementIndex If non-NULL and the first designator in @p
1269/// DIE is an array designator or GNU array-range designator, this
1270/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001271///
1272/// @param Index Index into @p IList where the designated initializer
1273/// @p DIE occurs.
1274///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001275/// @param StructuredList The initializer list expression that
1276/// describes all of the subobject initializers in the order they'll
1277/// actually be initialized.
1278///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001279/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001280bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001281InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001282 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001283 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001284 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001285 QualType &CurrentObjectType,
1286 RecordDecl::field_iterator *NextField,
1287 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001288 unsigned &Index,
1289 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001290 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001291 bool FinishSubobjectInit,
1292 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001293 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001294 // Check the actual initialization for the designated object type.
1295 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001296
1297 // Temporarily remove the designator expression from the
1298 // initializer list that the child calls see, so that we don't try
1299 // to re-process the designator.
1300 unsigned OldIndex = Index;
1301 IList->setInit(OldIndex, DIE->getInit());
1302
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001303 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001304 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001305
1306 // Restore the designated initializer expression in the syntactic
1307 // form of the initializer list.
1308 if (IList->getInit(OldIndex) != DIE->getInit())
1309 DIE->setInit(IList->getInit(OldIndex));
1310 IList->setInit(OldIndex, DIE);
1311
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001312 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001313 }
1314
Douglas Gregora5324162009-04-15 04:56:10 +00001315 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001316 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001317 "Need a non-designated initializer list to start from");
1318
Douglas Gregora5324162009-04-15 04:56:10 +00001319 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001320 // Determine the structural initializer list that corresponds to the
1321 // current subobject.
1322 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001323 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001324 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001325 SourceRange(D->getStartLocation(),
1326 DIE->getSourceRange().getEnd()));
1327 assert(StructuredList && "Expected a structured initializer list");
1328
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001329 if (D->isFieldDesignator()) {
1330 // C99 6.7.8p7:
1331 //
1332 // If a designator has the form
1333 //
1334 // . identifier
1335 //
1336 // then the current object (defined below) shall have
1337 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001338 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001339 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001340 if (!RT) {
1341 SourceLocation Loc = D->getDotLoc();
1342 if (Loc.isInvalid())
1343 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001344 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1345 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001346 ++Index;
1347 return true;
1348 }
1349
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001350 // Note: we perform a linear search of the fields here, despite
1351 // the fact that we have a faster lookup method, because we always
1352 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001353 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001354 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001355 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001356 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001357 Field = RT->getDecl()->field_begin(),
1358 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001359 for (; Field != FieldEnd; ++Field) {
1360 if (Field->isUnnamedBitfield())
1361 continue;
1362
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001363 if (KnownField && KnownField == *Field)
1364 break;
1365 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001366 break;
1367
1368 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001369 }
1370
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001371 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001372 // There was no normal field in the struct with the designated
1373 // name. Perform another lookup for this name, which may find
1374 // something that we can't designate (e.g., a member function),
1375 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001376 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001377 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001378 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001379 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001380 // Name lookup didn't find anything. Determine whether this
1381 // was a typo for another field name.
1382 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1383 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001384 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1385 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001386 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001387 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001388 ->Equals(RT->getDecl())) {
1389 SemaRef.Diag(D->getFieldLoc(),
1390 diag::err_field_designator_unknown_suggest)
1391 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001392 << FixItHint::CreateReplacement(D->getFieldLoc(),
1393 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001394 SemaRef.Diag(ReplacementField->getLocation(),
1395 diag::note_previous_decl)
1396 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001397 } else {
1398 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1399 << FieldName << CurrentObjectType;
1400 ++Index;
1401 return true;
1402 }
1403 } else if (!KnownField) {
1404 // Determine whether we found a field at all.
1405 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1406 }
1407
1408 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001409 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001410 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001411 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001412 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001413 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001414 ++Index;
1415 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001416 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001417
1418 if (!KnownField &&
1419 cast<RecordDecl>((ReplacementField)->getDeclContext())
1420 ->isAnonymousStructOrUnion()) {
1421 // Handle an field designator that refers to a member of an
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001422 // anonymous struct or union. This is a C1X feature.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001423 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1424 ReplacementField,
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001425 Field, FieldIndex, RT->getDecl());
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001426 D = DIE->getDesignator(DesigIdx);
1427 } else if (!KnownField) {
1428 // The replacement field comes from typo correction; find it
1429 // in the list of fields.
1430 FieldIndex = 0;
1431 Field = RT->getDecl()->field_begin();
1432 for (; Field != FieldEnd; ++Field) {
1433 if (Field->isUnnamedBitfield())
1434 continue;
1435
1436 if (ReplacementField == *Field ||
1437 Field->getIdentifier() == ReplacementField->getIdentifier())
1438 break;
1439
1440 ++FieldIndex;
1441 }
1442 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001443 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001444
1445 // All of the fields of a union are located at the same place in
1446 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001447 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001448 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001449 StructuredList->setInitializedFieldInUnion(*Field);
1450 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001451
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001452 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001453 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001454
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001455 // Make sure that our non-designated initializer list has space
1456 // for a subobject corresponding to this field.
1457 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001458 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001459
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 // This designator names a flexible array member.
1461 if (Field->getType()->isIncompleteArrayType()) {
1462 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001463 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001464 // We can't designate an object within the flexible array
1465 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001466 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001467 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001468 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001469 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001470 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001471 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001472 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001473 << *Field;
1474 Invalid = true;
1475 }
1476
1477 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1478 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001479 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001480 diag::err_flexible_array_init_needs_braces)
1481 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001482 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001483 << *Field;
1484 Invalid = true;
1485 }
1486
1487 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001488 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001489 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001490 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001491 diag::err_flexible_array_init_nonempty)
1492 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001493 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001494 << *Field;
1495 Invalid = true;
1496 }
1497
1498 if (Invalid) {
1499 ++Index;
1500 return true;
1501 }
1502
1503 // Initialize the array.
1504 bool prevHadError = hadError;
1505 unsigned newStructuredIndex = FieldIndex;
1506 unsigned OldIndex = Index;
1507 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001508
1509 InitializedEntity MemberEntity =
1510 InitializedEntity::InitializeMember(*Field, &Entity);
1511 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001512 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001513
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001514 IList->setInit(OldIndex, DIE);
1515 if (hadError && !prevHadError) {
1516 ++Field;
1517 ++FieldIndex;
1518 if (NextField)
1519 *NextField = Field;
1520 StructuredIndex = FieldIndex;
1521 return true;
1522 }
1523 } else {
1524 // Recurse to check later designated subobjects.
1525 QualType FieldType = (*Field)->getType();
1526 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001527
1528 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001529 InitializedEntity::InitializeMember(*Field, &Entity);
1530 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001531 FieldType, 0, 0, Index,
1532 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001533 true, false))
1534 return true;
1535 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001536
1537 // Find the position of the next field to be initialized in this
1538 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001539 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001540 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001541
1542 // If this the first designator, our caller will continue checking
1543 // the rest of this struct/class/union subobject.
1544 if (IsFirstDesignator) {
1545 if (NextField)
1546 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001547 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001548 return false;
1549 }
1550
Douglas Gregor17bd0942009-01-28 23:36:17 +00001551 if (!FinishSubobjectInit)
1552 return false;
1553
Douglas Gregord5846a12009-04-15 06:41:24 +00001554 // We've already initialized something in the union; we're done.
1555 if (RT->getDecl()->isUnion())
1556 return hadError;
1557
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001558 // Check the remaining fields within this class/struct/union subobject.
1559 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001560
Anders Carlsson6cabf312010-01-23 23:23:01 +00001561 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001562 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001563 return hadError && !prevHadError;
1564 }
1565
1566 // C99 6.7.8p6:
1567 //
1568 // If a designator has the form
1569 //
1570 // [ constant-expression ]
1571 //
1572 // then the current object (defined below) shall have array
1573 // type and the expression shall be an integer constant
1574 // expression. If the array is of unknown size, any
1575 // nonnegative value is valid.
1576 //
1577 // Additionally, cope with the GNU extension that permits
1578 // designators of the form
1579 //
1580 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001581 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001582 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001583 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001584 << CurrentObjectType;
1585 ++Index;
1586 return true;
1587 }
1588
1589 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001590 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1591 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001592 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001593 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001594 DesignatedEndIndex = DesignatedStartIndex;
1595 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001596 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001597
Mike Stump11289f42009-09-09 15:08:12 +00001598
1599 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001600 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001601 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001602 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001603 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001604
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001605 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001606 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001607 }
1608
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001609 if (isa<ConstantArrayType>(AT)) {
1610 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001611 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1612 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1613 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1614 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1615 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001616 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001617 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001618 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001619 << IndexExpr->getSourceRange();
1620 ++Index;
1621 return true;
1622 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001623 } else {
1624 // Make sure the bit-widths and signedness match.
1625 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1626 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001627 else if (DesignatedStartIndex.getBitWidth() <
1628 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001629 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1630 DesignatedStartIndex.setIsUnsigned(true);
1631 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001632 }
Mike Stump11289f42009-09-09 15:08:12 +00001633
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001634 // Make sure that our non-designated initializer list has space
1635 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001636 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001637 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001638 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001639
Douglas Gregor17bd0942009-01-28 23:36:17 +00001640 // Repeatedly perform subobject initializations in the range
1641 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001642
Douglas Gregor17bd0942009-01-28 23:36:17 +00001643 // Move to the next designator
1644 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1645 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001646
1647 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001648 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001649
Douglas Gregor17bd0942009-01-28 23:36:17 +00001650 while (DesignatedStartIndex <= DesignatedEndIndex) {
1651 // Recurse to check later designated subobjects.
1652 QualType ElementType = AT->getElementType();
1653 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001654
1655 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001656 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001657 ElementType, 0, 0, Index,
1658 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001659 (DesignatedStartIndex == DesignatedEndIndex),
1660 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001661 return true;
1662
1663 // Move to the next index in the array that we'll be initializing.
1664 ++DesignatedStartIndex;
1665 ElementIndex = DesignatedStartIndex.getZExtValue();
1666 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001667
1668 // If this the first designator, our caller will continue checking
1669 // the rest of this array subobject.
1670 if (IsFirstDesignator) {
1671 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001672 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001673 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001674 return false;
1675 }
Mike Stump11289f42009-09-09 15:08:12 +00001676
Douglas Gregor17bd0942009-01-28 23:36:17 +00001677 if (!FinishSubobjectInit)
1678 return false;
1679
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001680 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001681 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001682 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001683 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001684 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001685 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001686}
1687
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001688// Get the structured initializer list for a subobject of type
1689// @p CurrentObjectType.
1690InitListExpr *
1691InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1692 QualType CurrentObjectType,
1693 InitListExpr *StructuredList,
1694 unsigned StructuredIndex,
1695 SourceRange InitRange) {
1696 Expr *ExistingInit = 0;
1697 if (!StructuredList)
1698 ExistingInit = SyntacticToSemantic[IList];
1699 else if (StructuredIndex < StructuredList->getNumInits())
1700 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001701
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001702 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1703 return Result;
1704
1705 if (ExistingInit) {
1706 // We are creating an initializer list that initializes the
1707 // subobjects of the current object, but there was already an
1708 // initialization that completely initialized the current
1709 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001710 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711 // struct X { int a, b; };
1712 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001713 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001714 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1715 // designated initializer re-initializes the whole
1716 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001717 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001718 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001719 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001720 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001721 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001722 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001723 << ExistingInit->getSourceRange();
1724 }
1725
Mike Stump11289f42009-09-09 15:08:12 +00001726 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001727 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1728 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001729 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001730
Douglas Gregora8a089b2010-07-13 18:40:04 +00001731 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001732
Douglas Gregor6d00c992009-03-20 23:58:33 +00001733 // Pre-allocate storage for the structured initializer list.
1734 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001735 unsigned NumInits = 0;
1736 if (!StructuredList)
1737 NumInits = IList->getNumInits();
1738 else if (Index < IList->getNumInits()) {
1739 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1740 NumInits = SubList->getNumInits();
1741 }
1742
Mike Stump11289f42009-09-09 15:08:12 +00001743 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001744 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1745 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1746 NumElements = CAType->getSize().getZExtValue();
1747 // Simple heuristic so that we don't allocate a very large
1748 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001749 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001750 NumElements = 0;
1751 }
John McCall9dd450b2009-09-21 23:43:11 +00001752 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001753 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001754 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001755 RecordDecl *RDecl = RType->getDecl();
1756 if (RDecl->isUnion())
1757 NumElements = 1;
1758 else
Mike Stump11289f42009-09-09 15:08:12 +00001759 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001760 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001761 }
1762
Douglas Gregor221c9a52009-03-21 18:13:52 +00001763 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001764 NumElements = IList->getNumInits();
1765
Ted Kremenekac034612010-04-13 23:39:13 +00001766 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001767
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001768 // Link this new initializer list into the structured initializer
1769 // lists.
1770 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001771 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001772 else {
1773 Result->setSyntacticForm(IList);
1774 SyntacticToSemantic[IList] = Result;
1775 }
1776
1777 return Result;
1778}
1779
1780/// Update the initializer at index @p StructuredIndex within the
1781/// structured initializer list to the value @p expr.
1782void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1783 unsigned &StructuredIndex,
1784 Expr *expr) {
1785 // No structured initializer list to update
1786 if (!StructuredList)
1787 return;
1788
Ted Kremenekac034612010-04-13 23:39:13 +00001789 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1790 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001791 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001792 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001793 diag::warn_initializer_overrides)
1794 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001795 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001796 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001797 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001798 << PrevInit->getSourceRange();
1799 }
Mike Stump11289f42009-09-09 15:08:12 +00001800
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001801 ++StructuredIndex;
1802}
1803
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001804/// Check that the given Index expression is a valid array designator
1805/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001806/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001807/// and produces a reasonable diagnostic if there is a
1808/// failure. Returns true if there was an error, false otherwise. If
1809/// everything went okay, Value will receive the value of the constant
1810/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001811static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001812CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001813 SourceLocation Loc = Index->getSourceRange().getBegin();
1814
1815 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001816 if (S.VerifyIntegerConstantExpression(Index, &Value))
1817 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001818
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001819 if (Value.isSigned() && Value.isNegative())
1820 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001821 << Value.toString(10) << Index->getSourceRange();
1822
Douglas Gregor51650d32009-01-23 21:04:18 +00001823 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001824 return false;
1825}
1826
John McCalldadc5752010-08-24 06:29:42 +00001827ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001828 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001829 bool GNUSyntax,
John McCalldadc5752010-08-24 06:29:42 +00001830 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001831 typedef DesignatedInitExpr::Designator ASTDesignator;
1832
1833 bool Invalid = false;
1834 llvm::SmallVector<ASTDesignator, 32> Designators;
1835 llvm::SmallVector<Expr *, 32> InitExpressions;
1836
1837 // Build designators and check array designator expressions.
1838 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1839 const Designator &D = Desig.getDesignator(Idx);
1840 switch (D.getKind()) {
1841 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001842 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001843 D.getFieldLoc()));
1844 break;
1845
1846 case Designator::ArrayDesignator: {
1847 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1848 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001849 if (!Index->isTypeDependent() &&
1850 !Index->isValueDependent() &&
1851 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001852 Invalid = true;
1853 else {
1854 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001855 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001856 D.getRBracketLoc()));
1857 InitExpressions.push_back(Index);
1858 }
1859 break;
1860 }
1861
1862 case Designator::ArrayRangeDesignator: {
1863 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1864 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1865 llvm::APSInt StartValue;
1866 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001867 bool StartDependent = StartIndex->isTypeDependent() ||
1868 StartIndex->isValueDependent();
1869 bool EndDependent = EndIndex->isTypeDependent() ||
1870 EndIndex->isValueDependent();
1871 if ((!StartDependent &&
1872 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1873 (!EndDependent &&
1874 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001875 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001876 else {
1877 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001878 if (StartDependent || EndDependent) {
1879 // Nothing to compute.
1880 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001881 EndValue.extend(StartValue.getBitWidth());
1882 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1883 StartValue.extend(EndValue.getBitWidth());
1884
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001885 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001886 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001887 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001888 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1889 Invalid = true;
1890 } else {
1891 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001892 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001893 D.getEllipsisLoc(),
1894 D.getRBracketLoc()));
1895 InitExpressions.push_back(StartIndex);
1896 InitExpressions.push_back(EndIndex);
1897 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001898 }
1899 break;
1900 }
1901 }
1902 }
1903
1904 if (Invalid || Init.isInvalid())
1905 return ExprError();
1906
1907 // Clear out the expressions within the designation.
1908 Desig.ClearExprs(*this);
1909
1910 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001911 = DesignatedInitExpr::Create(Context,
1912 Designators.data(), Designators.size(),
1913 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001914 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001915 return Owned(DIE);
1916}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001917
Douglas Gregor723796a2009-12-16 06:35:08 +00001918bool Sema::CheckInitList(const InitializedEntity &Entity,
1919 InitListExpr *&InitList, QualType &DeclType) {
1920 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001921 if (!CheckInitList.HadError())
1922 InitList = CheckInitList.getFullyStructuredList();
1923
1924 return CheckInitList.HadError();
1925}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001926
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001927//===----------------------------------------------------------------------===//
1928// Initialization entity
1929//===----------------------------------------------------------------------===//
1930
Douglas Gregor723796a2009-12-16 06:35:08 +00001931InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1932 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001933 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001934{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001935 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1936 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001937 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001938 } else {
1939 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001940 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001941 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001942}
1943
1944InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001945 CXXBaseSpecifier *Base,
1946 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001947{
1948 InitializedEntity Result;
1949 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001950 Result.Base = reinterpret_cast<uintptr_t>(Base);
1951 if (IsInheritedVirtualBase)
1952 Result.Base |= 0x01;
1953
Douglas Gregor1b303932009-12-22 15:35:07 +00001954 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001955 return Result;
1956}
1957
Douglas Gregor85dabae2009-12-16 01:38:02 +00001958DeclarationName InitializedEntity::getName() const {
1959 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001960 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001961 if (!VariableOrMember)
1962 return DeclarationName();
1963 // Fall through
1964
1965 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001966 case EK_Member:
1967 return VariableOrMember->getDeclName();
1968
1969 case EK_Result:
1970 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001971 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001972 case EK_Temporary:
1973 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001974 case EK_ArrayElement:
1975 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001976 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001977 return DeclarationName();
1978 }
1979
1980 // Silence GCC warning
1981 return DeclarationName();
1982}
1983
Douglas Gregora4b592a2009-12-19 03:01:41 +00001984DeclaratorDecl *InitializedEntity::getDecl() const {
1985 switch (getKind()) {
1986 case EK_Variable:
1987 case EK_Parameter:
1988 case EK_Member:
1989 return VariableOrMember;
1990
1991 case EK_Result:
1992 case EK_Exception:
1993 case EK_New:
1994 case EK_Temporary:
1995 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001996 case EK_ArrayElement:
1997 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001998 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001999 return 0;
2000 }
2001
2002 // Silence GCC warning
2003 return 0;
2004}
2005
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002006bool InitializedEntity::allowsNRVO() const {
2007 switch (getKind()) {
2008 case EK_Result:
2009 case EK_Exception:
2010 return LocAndNRVO.NRVO;
2011
2012 case EK_Variable:
2013 case EK_Parameter:
2014 case EK_Member:
2015 case EK_New:
2016 case EK_Temporary:
2017 case EK_Base:
2018 case EK_ArrayElement:
2019 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002020 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002021 break;
2022 }
2023
2024 return false;
2025}
2026
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002027//===----------------------------------------------------------------------===//
2028// Initialization sequence
2029//===----------------------------------------------------------------------===//
2030
2031void InitializationSequence::Step::Destroy() {
2032 switch (Kind) {
2033 case SK_ResolveAddressOfOverloadedFunction:
2034 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002035 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002036 case SK_CastDerivedToBaseLValue:
2037 case SK_BindReference:
2038 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002039 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002040 case SK_UserConversion:
2041 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002042 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002043 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002044 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002045 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002046 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002047 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002048 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002049 case SK_ObjCObjectConversion:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002050 break;
2051
2052 case SK_ConversionSequence:
2053 delete ICS;
2054 }
2055}
2056
Douglas Gregor838fcc32010-03-26 20:14:36 +00002057bool InitializationSequence::isDirectReferenceBinding() const {
2058 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2059}
2060
2061bool InitializationSequence::isAmbiguous() const {
2062 if (getKind() != FailedSequence)
2063 return false;
2064
2065 switch (getFailureKind()) {
2066 case FK_TooManyInitsForReference:
2067 case FK_ArrayNeedsInitList:
2068 case FK_ArrayNeedsInitListOrStringLiteral:
2069 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2070 case FK_NonConstLValueReferenceBindingToTemporary:
2071 case FK_NonConstLValueReferenceBindingToUnrelated:
2072 case FK_RValueReferenceBindingToLValue:
2073 case FK_ReferenceInitDropsQualifiers:
2074 case FK_ReferenceInitFailed:
2075 case FK_ConversionFailed:
2076 case FK_TooManyInitsForScalar:
2077 case FK_ReferenceBindingToInitList:
2078 case FK_InitListBadDestinationType:
2079 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002080 case FK_Incomplete:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002081 return false;
2082
2083 case FK_ReferenceInitOverloadFailed:
2084 case FK_UserConversionOverloadFailed:
2085 case FK_ConstructorOverloadFailed:
2086 return FailedOverloadResult == OR_Ambiguous;
2087 }
2088
2089 return false;
2090}
2091
Douglas Gregorb33eed02010-04-16 22:09:46 +00002092bool InitializationSequence::isConstructorInitialization() const {
2093 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2094}
2095
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002096void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002097 FunctionDecl *Function,
2098 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002099 Step S;
2100 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2101 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002102 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002103 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002104 Steps.push_back(S);
2105}
2106
2107void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002108 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002109 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002110 switch (VK) {
2111 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2112 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2113 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002114 default: llvm_unreachable("No such category");
2115 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002116 S.Type = BaseType;
2117 Steps.push_back(S);
2118}
2119
2120void InitializationSequence::AddReferenceBindingStep(QualType T,
2121 bool BindingTemporary) {
2122 Step S;
2123 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2124 S.Type = T;
2125 Steps.push_back(S);
2126}
2127
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002128void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2129 Step S;
2130 S.Kind = SK_ExtraneousCopyToTemporary;
2131 S.Type = T;
2132 Steps.push_back(S);
2133}
2134
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002135void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002136 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002137 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002138 Step S;
2139 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002140 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002141 S.Function.Function = Function;
2142 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002143 Steps.push_back(S);
2144}
2145
2146void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002147 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002148 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002149 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002150 switch (VK) {
2151 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002152 S.Kind = SK_QualificationConversionRValue;
2153 break;
John McCall2536c6d2010-08-25 10:28:54 +00002154 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002155 S.Kind = SK_QualificationConversionXValue;
2156 break;
John McCall2536c6d2010-08-25 10:28:54 +00002157 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002158 S.Kind = SK_QualificationConversionLValue;
2159 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002160 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002161 S.Type = Ty;
2162 Steps.push_back(S);
2163}
2164
2165void InitializationSequence::AddConversionSequenceStep(
2166 const ImplicitConversionSequence &ICS,
2167 QualType T) {
2168 Step S;
2169 S.Kind = SK_ConversionSequence;
2170 S.Type = T;
2171 S.ICS = new ImplicitConversionSequence(ICS);
2172 Steps.push_back(S);
2173}
2174
Douglas Gregor51e77d52009-12-10 17:56:55 +00002175void InitializationSequence::AddListInitializationStep(QualType T) {
2176 Step S;
2177 S.Kind = SK_ListInitialization;
2178 S.Type = T;
2179 Steps.push_back(S);
2180}
2181
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002182void
2183InitializationSequence::AddConstructorInitializationStep(
2184 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002185 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002186 QualType T) {
2187 Step S;
2188 S.Kind = SK_ConstructorInitialization;
2189 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002190 S.Function.Function = Constructor;
2191 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002192 Steps.push_back(S);
2193}
2194
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002195void InitializationSequence::AddZeroInitializationStep(QualType T) {
2196 Step S;
2197 S.Kind = SK_ZeroInitialization;
2198 S.Type = T;
2199 Steps.push_back(S);
2200}
2201
Douglas Gregore1314a62009-12-18 05:02:21 +00002202void InitializationSequence::AddCAssignmentStep(QualType T) {
2203 Step S;
2204 S.Kind = SK_CAssignment;
2205 S.Type = T;
2206 Steps.push_back(S);
2207}
2208
Eli Friedman78275202009-12-19 08:11:05 +00002209void InitializationSequence::AddStringInitStep(QualType T) {
2210 Step S;
2211 S.Kind = SK_StringInit;
2212 S.Type = T;
2213 Steps.push_back(S);
2214}
2215
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002216void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2217 Step S;
2218 S.Kind = SK_ObjCObjectConversion;
2219 S.Type = T;
2220 Steps.push_back(S);
2221}
2222
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002223void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2224 OverloadingResult Result) {
2225 SequenceKind = FailedSequence;
2226 this->Failure = Failure;
2227 this->FailedOverloadResult = Result;
2228}
2229
2230//===----------------------------------------------------------------------===//
2231// Attempt initialization
2232//===----------------------------------------------------------------------===//
2233
2234/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002235static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002236 const InitializedEntity &Entity,
2237 const InitializationKind &Kind,
2238 InitListExpr *InitList,
2239 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002240 // FIXME: We only perform rudimentary checking of list
2241 // initializations at this point, then assume that any list
2242 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002243 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002244 // do all of the necessary checking. C++0x initializer lists will
2245 // force us to perform more checking here.
2246 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2247
Douglas Gregor1b303932009-12-22 15:35:07 +00002248 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002249
2250 // C++ [dcl.init]p13:
2251 // If T is a scalar type, then a declaration of the form
2252 //
2253 // T x = { a };
2254 //
2255 // is equivalent to
2256 //
2257 // T x = a;
2258 if (DestType->isScalarType()) {
2259 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2260 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2261 return;
2262 }
2263
2264 // Assume scalar initialization from a single value works.
2265 } else if (DestType->isAggregateType()) {
2266 // Assume aggregate initialization works.
2267 } else if (DestType->isVectorType()) {
2268 // Assume vector initialization works.
2269 } else if (DestType->isReferenceType()) {
2270 // FIXME: C++0x defines behavior for this.
2271 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2272 return;
2273 } else if (DestType->isRecordType()) {
2274 // FIXME: C++0x defines behavior for this
2275 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2276 }
2277
2278 // Add a general "list initialization" step.
2279 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002280}
2281
2282/// \brief Try a reference initialization that involves calling a conversion
2283/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002284static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2285 const InitializedEntity &Entity,
2286 const InitializationKind &Kind,
2287 Expr *Initializer,
2288 bool AllowRValues,
2289 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002290 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002291 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2292 QualType T1 = cv1T1.getUnqualifiedType();
2293 QualType cv2T2 = Initializer->getType();
2294 QualType T2 = cv2T2.getUnqualifiedType();
2295
2296 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002297 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002298 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002299 T1, T2, DerivedToBase,
2300 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002301 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002302 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002303 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002304
2305 // Build the candidate set directly in the initialization sequence
2306 // structure, so that it will persist if we fail.
2307 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2308 CandidateSet.clear();
2309
2310 // Determine whether we are allowed to call explicit constructors or
2311 // explicit conversion operators.
2312 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2313
2314 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002315 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2316 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 // The type we're converting to is a class type. Enumerate its constructors
2318 // to see if there is a suitable conversion.
2319 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002320
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002321 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002322 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002323 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002324 NamedDecl *D = *Con;
2325 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2326
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002327 // Find the constructor (which may be a template).
2328 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002329 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002330 if (ConstructorTmpl)
2331 Constructor = cast<CXXConstructorDecl>(
2332 ConstructorTmpl->getTemplatedDecl());
2333 else
John McCalla0296f72010-03-19 07:35:19 +00002334 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002335
2336 if (!Constructor->isInvalidDecl() &&
2337 Constructor->isConvertingConstructor(AllowExplicit)) {
2338 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002339 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002340 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002341 &Initializer, 1, CandidateSet,
2342 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002343 else
John McCalla0296f72010-03-19 07:35:19 +00002344 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002345 &Initializer, 1, CandidateSet,
2346 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002347 }
2348 }
2349 }
John McCall3696dcb2010-08-17 07:23:57 +00002350 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2351 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002352
Douglas Gregor496e8b342010-05-07 19:42:26 +00002353 const RecordType *T2RecordType = 0;
2354 if ((T2RecordType = T2->getAs<RecordType>()) &&
2355 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002356 // The type we're converting from is a class type, enumerate its conversion
2357 // functions.
2358 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2359
2360 // Determine the type we are converting to. If we are allowed to
2361 // convert to an rvalue, take the type that the destination type
2362 // refers to.
2363 QualType ToType = AllowRValues? cv1T1 : DestType;
2364
John McCallad371252010-01-20 00:46:10 +00002365 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002366 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002367 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2368 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002369 NamedDecl *D = *I;
2370 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2371 if (isa<UsingShadowDecl>(D))
2372 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2373
2374 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2375 CXXConversionDecl *Conv;
2376 if (ConvTemplate)
2377 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2378 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002379 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002380
2381 // If the conversion function doesn't return a reference type,
2382 // it can't be considered for this conversion unless we're allowed to
2383 // consider rvalues.
2384 // FIXME: Do we need to make sure that we only consider conversion
2385 // candidates with reference-compatible results? That might be needed to
2386 // break recursion.
2387 if ((AllowExplicit || !Conv->isExplicit()) &&
2388 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2389 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002390 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002391 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002392 ToType, CandidateSet);
2393 else
John McCalla0296f72010-03-19 07:35:19 +00002394 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002395 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 }
2397 }
2398 }
John McCall3696dcb2010-08-17 07:23:57 +00002399 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2400 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002401
2402 SourceLocation DeclLoc = Initializer->getLocStart();
2403
2404 // Perform overload resolution. If it fails, return the failed result.
2405 OverloadCandidateSet::iterator Best;
2406 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002407 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002408 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002409
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002410 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002411
2412 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002413 if (isa<CXXConversionDecl>(Function))
2414 T2 = Function->getResultType();
2415 else
2416 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002417
2418 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002419 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002420 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002421
2422 // Determine whether we need to perform derived-to-base or
2423 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002424 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002425 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002426 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002427 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002428 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002429
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002430 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002431 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002432 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregora8a089b2010-07-13 18:40:04 +00002433 = S.CompareReferenceRelationship(DeclLoc, T1,
2434 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002435 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002436 if (NewRefRelationship == Sema::Ref_Incompatible) {
2437 // If the type we've converted to is not reference-related to the
2438 // type we're looking for, then there is another conversion step
2439 // we need to perform to produce a temporary of the right type
2440 // that we'll be binding to.
2441 ImplicitConversionSequence ICS;
2442 ICS.setStandard();
2443 ICS.Standard = Best->FinalConversion;
2444 T2 = ICS.Standard.getToType(2);
2445 Sequence.AddConversionSequenceStep(ICS, T2);
2446 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002447 Sequence.AddDerivedToBaseCastStep(
2448 S.Context.getQualifiedType(T1,
2449 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002450 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002451 else if (NewObjCConversion)
2452 Sequence.AddObjCObjectConversionStep(
2453 S.Context.getQualifiedType(T1,
2454 T2.getNonReferenceType().getQualifiers()));
2455
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002456 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002457 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002458
2459 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2460 return OR_Success;
2461}
2462
Sebastian Redld92badf2010-06-30 18:13:39 +00002463/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002464static void TryReferenceInitialization(Sema &S,
2465 const InitializedEntity &Entity,
2466 const InitializationKind &Kind,
2467 Expr *Initializer,
2468 InitializationSequence &Sequence) {
2469 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002470
Douglas Gregor1b303932009-12-22 15:35:07 +00002471 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002472 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002473 Qualifiers T1Quals;
2474 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002475 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002476 Qualifiers T2Quals;
2477 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002478 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002479
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002480 // If the initializer is the address of an overloaded function, try
2481 // to resolve the overloaded function. If all goes well, T2 is the
2482 // type of the resulting function.
2483 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002484 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002485 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2486 T1,
John McCall16df1e52010-03-30 21:47:33 +00002487 false,
2488 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002489 if (!Fn) {
2490 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2491 return;
2492 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002493
John McCall16df1e52010-03-30 21:47:33 +00002494 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002495 cv2T2 = Fn->getType();
2496 T2 = cv2T2.getUnqualifiedType();
2497 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002498
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 // Compute some basic properties of the types and the initializer.
2500 bool isLValueRef = DestType->isLValueReferenceType();
2501 bool isRValueRef = !isLValueRef;
2502 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002503 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002504 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002505 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002506 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2507 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002508
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002509 // C++0x [dcl.init.ref]p5:
2510 // A reference to type "cv1 T1" is initialized by an expression of type
2511 // "cv2 T2" as follows:
2512 //
2513 // - If the reference is an lvalue reference and the initializer
2514 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002515 // Note the analogous bullet points for rvlaue refs to functions. Because
2516 // there are no function rvalues in C++, rvalue refs to functions are treated
2517 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002518 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002519 bool T1Function = T1->isFunctionType();
2520 if (isLValueRef || T1Function) {
2521 if (InitCategory.isLValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002522 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2523 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2524 // reference-compatible with "cv2 T2," or
2525 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002526 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002527 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002528 // can occur. However, we do pay attention to whether it is a bit-field
2529 // to decide whether we're actually binding to a temporary created from
2530 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002531 if (DerivedToBase)
2532 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002533 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002534 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002535 else if (ObjCConversion)
2536 Sequence.AddObjCObjectConversionStep(
2537 S.Context.getQualifiedType(T1, T2Quals));
2538
Chandler Carruth04bdce62010-01-12 20:32:25 +00002539 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002540 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002541 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002542 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002543 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002544 return;
2545 }
2546
2547 // - has a class type (i.e., T2 is a class type), where T1 is not
2548 // reference-related to T2, and can be implicitly converted to an
2549 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2550 // with "cv3 T3" (this conversion is selected by enumerating the
2551 // applicable conversion functions (13.3.1.6) and choosing the best
2552 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002553 // If we have an rvalue ref to function type here, the rhs must be
2554 // an rvalue.
2555 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2556 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002557 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2558 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002559 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002560 Sequence);
2561 if (ConvOvlResult == OR_Success)
2562 return;
John McCall0d1da222010-01-12 00:44:57 +00002563 if (ConvOvlResult != OR_No_Viable_Function) {
2564 Sequence.SetOverloadFailure(
2565 InitializationSequence::FK_ReferenceInitOverloadFailed,
2566 ConvOvlResult);
2567 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002568 }
2569 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002570
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002571 // - Otherwise, the reference shall be an lvalue reference to a
2572 // non-volatile const type (i.e., cv1 shall be const), or the reference
2573 // shall be an rvalue reference and the initializer expression shall
Sebastian Redld92badf2010-06-30 18:13:39 +00002574 // be an rvalue or have a function type.
2575 // We handled the function type stuff above.
Douglas Gregord1e08642010-01-29 19:39:15 +00002576 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redld92badf2010-06-30 18:13:39 +00002577 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002578 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2579 Sequence.SetOverloadFailure(
2580 InitializationSequence::FK_ReferenceInitOverloadFailed,
2581 ConvOvlResult);
2582 else if (isLValueRef)
Sebastian Redld92badf2010-06-30 18:13:39 +00002583 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002584 ? (RefRelationship == Sema::Ref_Related
2585 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2586 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2587 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2588 else
2589 Sequence.SetFailed(
2590 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redld92badf2010-06-30 18:13:39 +00002591
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002592 return;
2593 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002594
2595 // - [If T1 is not a function type], if T2 is a class type and
2596 if (!T1Function && T2->isRecordType()) {
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002597 bool isXValue = InitCategory.isXValue();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002598 // - the initializer expression is an rvalue and "cv1 T1" is
2599 // reference-compatible with "cv2 T2", or
Sebastian Redld92badf2010-06-30 18:13:39 +00002600 if (InitCategory.isRValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002601 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002602 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2603 // compiler the freedom to perform a copy here or bind to the
2604 // object, while C++0x requires that we bind directly to the
2605 // object. Hence, we always bind to the object without making an
2606 // extra copy. However, in C++03 requires that we check for the
2607 // presence of a suitable copy constructor:
2608 //
2609 // The constructor that would be used to make the copy shall
2610 // be callable whether or not the copy is actually done.
2611 if (!S.getLangOptions().CPlusPlus0x)
2612 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2613
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002614 if (DerivedToBase)
2615 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002616 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002617 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002618 else if (ObjCConversion)
2619 Sequence.AddObjCObjectConversionStep(
2620 S.Context.getQualifiedType(T1, T2Quals));
2621
Chandler Carruth04bdce62010-01-12 20:32:25 +00002622 if (T1Quals != T2Quals)
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002623 Sequence.AddQualificationConversionStep(cv1T1,
John McCall2536c6d2010-08-25 10:28:54 +00002624 isXValue ? VK_XValue : VK_RValue);
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002625 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002626 return;
2627 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002628
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002629 // - T1 is not reference-related to T2 and the initializer expression
2630 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2631 // conversion is selected by enumerating the applicable conversion
2632 // functions (13.3.1.6) and choosing the best one through overload
2633 // resolution (13.3)),
2634 if (RefRelationship == Sema::Ref_Incompatible) {
2635 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2636 Kind, Initializer,
2637 /*AllowRValues=*/true,
2638 Sequence);
2639 if (ConvOvlResult)
2640 Sequence.SetOverloadFailure(
2641 InitializationSequence::FK_ReferenceInitOverloadFailed,
2642 ConvOvlResult);
2643
2644 return;
2645 }
2646
2647 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2648 return;
2649 }
2650
2651 // - If the initializer expression is an rvalue, with T2 an array type,
2652 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2653 // is bound to the object represented by the rvalue (see 3.10).
2654 // FIXME: How can an array type be reference-compatible with anything?
2655 // Don't we mean the element types of T1 and T2?
2656
2657 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2658 // from the initializer expression using the rules for a non-reference
2659 // copy initialization (8.5). The reference is then bound to the
2660 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002661
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002662 // Determine whether we are allowed to call explicit constructors or
2663 // explicit conversion operators.
2664 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002665
2666 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2667
2668 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2669 /*SuppressUserConversions*/ false,
2670 AllowExplicit,
2671 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002672 // FIXME: Use the conversion function set stored in ICS to turn
2673 // this into an overloading ambiguity diagnostic. However, we need
2674 // to keep that set as an OverloadCandidateSet rather than as some
2675 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002676 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2677 Sequence.SetOverloadFailure(
2678 InitializationSequence::FK_ReferenceInitOverloadFailed,
2679 ConvOvlResult);
2680 else
2681 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 return;
2683 }
2684
2685 // [...] If T1 is reference-related to T2, cv1 must be the
2686 // same cv-qualification as, or greater cv-qualification
2687 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002688 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2689 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002690 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002691 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002692 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2693 return;
2694 }
2695
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002696 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2697 return;
2698}
2699
2700/// \brief Attempt character array initialization from a string literal
2701/// (C++ [dcl.init.string], C99 6.7.8).
2702static void TryStringLiteralInitialization(Sema &S,
2703 const InitializedEntity &Entity,
2704 const InitializationKind &Kind,
2705 Expr *Initializer,
2706 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002707 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002708 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002709}
2710
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002711/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2712/// enumerates the constructors of the initialized entity and performs overload
2713/// resolution to select the best.
2714static void TryConstructorInitialization(Sema &S,
2715 const InitializedEntity &Entity,
2716 const InitializationKind &Kind,
2717 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002718 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002719 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002720 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002721
2722 // Build the candidate set directly in the initialization sequence
2723 // structure, so that it will persist if we fail.
2724 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2725 CandidateSet.clear();
2726
2727 // Determine whether we are allowed to call explicit constructors or
2728 // explicit conversion operators.
2729 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2730 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002731 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002732
2733 // The type we're constructing needs to be complete.
2734 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002735 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002736 return;
2737 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002738
2739 // The type we're converting to is a class type. Enumerate its constructors
2740 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002741 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2742 assert(DestRecordType && "Constructor initialization requires record type");
2743 CXXRecordDecl *DestRecordDecl
2744 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2745
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002746 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002747 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002748 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002749 NamedDecl *D = *Con;
2750 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002751 bool SuppressUserConversions = false;
2752
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002753 // Find the constructor (which may be a template).
2754 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002755 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002756 if (ConstructorTmpl)
2757 Constructor = cast<CXXConstructorDecl>(
2758 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002759 else {
John McCalla0296f72010-03-19 07:35:19 +00002760 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002761
2762 // If we're performing copy initialization using a copy constructor, we
2763 // suppress user-defined conversions on the arguments.
2764 // FIXME: Move constructors?
2765 if (Kind.getKind() == InitializationKind::IK_Copy &&
2766 Constructor->isCopyConstructor())
2767 SuppressUserConversions = true;
2768 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002769
2770 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002771 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002772 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002773 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002774 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002775 Args, NumArgs, CandidateSet,
2776 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002777 else
John McCalla0296f72010-03-19 07:35:19 +00002778 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002779 Args, NumArgs, CandidateSet,
2780 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002781 }
2782 }
2783
2784 SourceLocation DeclLoc = Kind.getLocation();
2785
2786 // Perform overload resolution. If it fails, return the failed result.
2787 OverloadCandidateSet::iterator Best;
2788 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002789 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002790 Sequence.SetOverloadFailure(
2791 InitializationSequence::FK_ConstructorOverloadFailed,
2792 Result);
2793 return;
2794 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002795
2796 // C++0x [dcl.init]p6:
2797 // If a program calls for the default initialization of an object
2798 // of a const-qualified type T, T shall be a class type with a
2799 // user-provided default constructor.
2800 if (Kind.getKind() == InitializationKind::IK_Default &&
2801 Entity.getType().isConstQualified() &&
2802 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2803 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2804 return;
2805 }
2806
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002807 // Add the constructor initialization step. Any cv-qualification conversion is
2808 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002809 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002810 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002811 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002812 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002813}
2814
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002815/// \brief Attempt value initialization (C++ [dcl.init]p7).
2816static void TryValueInitialization(Sema &S,
2817 const InitializedEntity &Entity,
2818 const InitializationKind &Kind,
2819 InitializationSequence &Sequence) {
2820 // C++ [dcl.init]p5:
2821 //
2822 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002823 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002824
2825 // -- if T is an array type, then each element is value-initialized;
2826 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2827 T = AT->getElementType();
2828
2829 if (const RecordType *RT = T->getAs<RecordType>()) {
2830 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2831 // -- if T is a class type (clause 9) with a user-declared
2832 // constructor (12.1), then the default constructor for T is
2833 // called (and the initialization is ill-formed if T has no
2834 // accessible default constructor);
2835 //
2836 // FIXME: we really want to refer to a single subobject of the array,
2837 // but Entity doesn't have a way to capture that (yet).
2838 if (ClassDecl->hasUserDeclaredConstructor())
2839 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2840
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002841 // -- if T is a (possibly cv-qualified) non-union class type
2842 // without a user-provided constructor, then the object is
2843 // zero-initialized and, if T’s implicitly-declared default
2844 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002845 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002846 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002847 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002848 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2849 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002850 }
2851 }
2852
Douglas Gregor1b303932009-12-22 15:35:07 +00002853 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002854 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2855}
2856
Douglas Gregor85dabae2009-12-16 01:38:02 +00002857/// \brief Attempt default initialization (C++ [dcl.init]p6).
2858static void TryDefaultInitialization(Sema &S,
2859 const InitializedEntity &Entity,
2860 const InitializationKind &Kind,
2861 InitializationSequence &Sequence) {
2862 assert(Kind.getKind() == InitializationKind::IK_Default);
2863
2864 // C++ [dcl.init]p6:
2865 // To default-initialize an object of type T means:
2866 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002867 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002868 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2869 DestType = Array->getElementType();
2870
2871 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2872 // constructor for T is called (and the initialization is ill-formed if
2873 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002874 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002875 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2876 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002877 }
2878
2879 // - otherwise, no initialization is performed.
2880 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2881
2882 // If a program calls for the default initialization of an object of
2883 // a const-qualified type T, T shall be a class type with a user-provided
2884 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002885 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002886 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2887}
2888
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002889/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2890/// which enumerates all conversion functions and performs overload resolution
2891/// to select the best.
2892static void TryUserDefinedConversion(Sema &S,
2893 const InitializedEntity &Entity,
2894 const InitializationKind &Kind,
2895 Expr *Initializer,
2896 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002897 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2898
Douglas Gregor1b303932009-12-22 15:35:07 +00002899 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002900 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2901 QualType SourceType = Initializer->getType();
2902 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2903 "Must have a class type to perform a user-defined conversion");
2904
2905 // Build the candidate set directly in the initialization sequence
2906 // structure, so that it will persist if we fail.
2907 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2908 CandidateSet.clear();
2909
2910 // Determine whether we are allowed to call explicit constructors or
2911 // explicit conversion operators.
2912 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2913
2914 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2915 // The type we're converting to is a class type. Enumerate its constructors
2916 // to see if there is a suitable conversion.
2917 CXXRecordDecl *DestRecordDecl
2918 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2919
Douglas Gregord9848152010-04-26 14:36:57 +00002920 // Try to complete the type we're converting to.
2921 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002922 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002923 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002924 Con != ConEnd; ++Con) {
2925 NamedDecl *D = *Con;
2926 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002927
Douglas Gregord9848152010-04-26 14:36:57 +00002928 // Find the constructor (which may be a template).
2929 CXXConstructorDecl *Constructor = 0;
2930 FunctionTemplateDecl *ConstructorTmpl
2931 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002932 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002933 Constructor = cast<CXXConstructorDecl>(
2934 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002935 else
Douglas Gregord9848152010-04-26 14:36:57 +00002936 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord9848152010-04-26 14:36:57 +00002937
2938 if (!Constructor->isInvalidDecl() &&
2939 Constructor->isConvertingConstructor(AllowExplicit)) {
2940 if (ConstructorTmpl)
2941 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2942 /*ExplicitArgs*/ 0,
2943 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002944 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002945 else
2946 S.AddOverloadCandidate(Constructor, FoundDecl,
2947 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002948 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002949 }
2950 }
2951 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002952 }
Eli Friedman78275202009-12-19 08:11:05 +00002953
2954 SourceLocation DeclLoc = Initializer->getLocStart();
2955
Douglas Gregor540c3b02009-12-14 17:27:33 +00002956 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2957 // The type we're converting from is a class type, enumerate its conversion
2958 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002959
Eli Friedman4afe9a32009-12-20 22:12:03 +00002960 // We can only enumerate the conversion functions for a complete type; if
2961 // the type isn't complete, simply skip this step.
2962 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2963 CXXRecordDecl *SourceRecordDecl
2964 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002965
John McCallad371252010-01-20 00:46:10 +00002966 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002967 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002968 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002969 E = Conversions->end();
2970 I != E; ++I) {
2971 NamedDecl *D = *I;
2972 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2973 if (isa<UsingShadowDecl>(D))
2974 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2975
2976 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2977 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002978 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002979 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002980 else
John McCallda4458e2010-03-31 01:36:47 +00002981 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002982
2983 if (AllowExplicit || !Conv->isExplicit()) {
2984 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002985 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002986 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002987 CandidateSet);
2988 else
John McCalla0296f72010-03-19 07:35:19 +00002989 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00002990 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002991 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002992 }
2993 }
2994 }
2995
Douglas Gregor540c3b02009-12-14 17:27:33 +00002996 // Perform overload resolution. If it fails, return the failed result.
2997 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002998 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002999 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003000 Sequence.SetOverloadFailure(
3001 InitializationSequence::FK_UserConversionOverloadFailed,
3002 Result);
3003 return;
3004 }
John McCall0d1da222010-01-12 00:44:57 +00003005
Douglas Gregor540c3b02009-12-14 17:27:33 +00003006 FunctionDecl *Function = Best->Function;
3007
3008 if (isa<CXXConstructorDecl>(Function)) {
3009 // Add the user-defined conversion step. Any cv-qualification conversion is
3010 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003011 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003012 return;
3013 }
3014
3015 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003016 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003017 if (ConvType->getAs<RecordType>()) {
3018 // If we're converting to a class type, there may be an copy if
3019 // the resulting temporary object (possible to create an object of
3020 // a base class type). That copy is not a separate conversion, so
3021 // we just make a note of the actual destination type (possibly a
3022 // base class of the type returned by the conversion function) and
3023 // let the user-defined conversion step handle the conversion.
3024 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3025 return;
3026 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003027
Douglas Gregor5ab11652010-04-17 22:01:05 +00003028 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3029
3030 // If the conversion following the call to the conversion function
3031 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003032 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3033 Best->FinalConversion.Third) {
3034 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003035 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003036 ICS.Standard = Best->FinalConversion;
3037 Sequence.AddConversionSequenceStep(ICS, DestType);
3038 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003039}
3040
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003041InitializationSequence::InitializationSequence(Sema &S,
3042 const InitializedEntity &Entity,
3043 const InitializationKind &Kind,
3044 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003045 unsigned NumArgs)
3046 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003047 ASTContext &Context = S.Context;
3048
3049 // C++0x [dcl.init]p16:
3050 // The semantics of initializers are as follows. The destination type is
3051 // the type of the object or reference being initialized and the source
3052 // type is the type of the initializer expression. The source type is not
3053 // defined when the initializer is a braced-init-list or when it is a
3054 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003055 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003056
3057 if (DestType->isDependentType() ||
3058 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3059 SequenceKind = DependentSequence;
3060 return;
3061 }
3062
3063 QualType SourceType;
3064 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003065 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003066 Initializer = Args[0];
3067 if (!isa<InitListExpr>(Initializer))
3068 SourceType = Initializer->getType();
3069 }
3070
3071 // - If the initializer is a braced-init-list, the object is
3072 // list-initialized (8.5.4).
3073 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3074 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003075 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003076 }
3077
3078 // - If the destination type is a reference type, see 8.5.3.
3079 if (DestType->isReferenceType()) {
3080 // C++0x [dcl.init.ref]p1:
3081 // A variable declared to be a T& or T&&, that is, "reference to type T"
3082 // (8.3.2), shall be initialized by an object, or function, of type T or
3083 // by an object that can be converted into a T.
3084 // (Therefore, multiple arguments are not permitted.)
3085 if (NumArgs != 1)
3086 SetFailed(FK_TooManyInitsForReference);
3087 else
3088 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3089 return;
3090 }
3091
3092 // - If the destination type is an array of characters, an array of
3093 // char16_t, an array of char32_t, or an array of wchar_t, and the
3094 // initializer is a string literal, see 8.5.2.
3095 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3096 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3097 return;
3098 }
3099
3100 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003101 if (Kind.getKind() == InitializationKind::IK_Value ||
3102 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003103 TryValueInitialization(S, Entity, Kind, *this);
3104 return;
3105 }
3106
Douglas Gregor85dabae2009-12-16 01:38:02 +00003107 // Handle default initialization.
3108 if (Kind.getKind() == InitializationKind::IK_Default){
3109 TryDefaultInitialization(S, Entity, Kind, *this);
3110 return;
3111 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003112
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003113 // - Otherwise, if the destination type is an array, the program is
3114 // ill-formed.
3115 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3116 if (AT->getElementType()->isAnyCharacterType())
3117 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3118 else
3119 SetFailed(FK_ArrayNeedsInitList);
3120
3121 return;
3122 }
Eli Friedman78275202009-12-19 08:11:05 +00003123
3124 // Handle initialization in C
3125 if (!S.getLangOptions().CPlusPlus) {
3126 setSequenceKind(CAssignment);
3127 AddCAssignmentStep(DestType);
3128 return;
3129 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003130
3131 // - If the destination type is a (possibly cv-qualified) class type:
3132 if (DestType->isRecordType()) {
3133 // - If the initialization is direct-initialization, or if it is
3134 // copy-initialization where the cv-unqualified version of the
3135 // source type is the same class as, or a derived class of, the
3136 // class of the destination, constructors are considered. [...]
3137 if (Kind.getKind() == InitializationKind::IK_Direct ||
3138 (Kind.getKind() == InitializationKind::IK_Copy &&
3139 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3140 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003141 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003142 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003143 // - Otherwise (i.e., for the remaining copy-initialization cases),
3144 // user-defined conversion sequences that can convert from the source
3145 // type to the destination type or (when a conversion function is
3146 // used) to a derived class thereof are enumerated as described in
3147 // 13.3.1.4, and the best one is chosen through overload resolution
3148 // (13.3).
3149 else
3150 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3151 return;
3152 }
3153
Douglas Gregor85dabae2009-12-16 01:38:02 +00003154 if (NumArgs > 1) {
3155 SetFailed(FK_TooManyInitsForScalar);
3156 return;
3157 }
3158 assert(NumArgs == 1 && "Zero-argument case handled above");
3159
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003160 // - Otherwise, if the source type is a (possibly cv-qualified) class
3161 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003162 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003163 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3164 return;
3165 }
3166
3167 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003168 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003169 // conversions (Clause 4) will be used, if necessary, to convert the
3170 // initializer expression to the cv-unqualified version of the
3171 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003172 if (S.TryImplicitConversion(*this, Entity, Initializer,
3173 /*SuppressUserConversions*/ true,
3174 /*AllowExplicitConversions*/ false,
3175 /*InOverloadResolution*/ false))
3176 SetFailed(InitializationSequence::FK_ConversionFailed);
3177 else
3178 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003179}
3180
3181InitializationSequence::~InitializationSequence() {
3182 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3183 StepEnd = Steps.end();
3184 Step != StepEnd; ++Step)
3185 Step->Destroy();
3186}
3187
3188//===----------------------------------------------------------------------===//
3189// Perform initialization
3190//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003191static Sema::AssignmentAction
3192getAssignmentAction(const InitializedEntity &Entity) {
3193 switch(Entity.getKind()) {
3194 case InitializedEntity::EK_Variable:
3195 case InitializedEntity::EK_New:
3196 return Sema::AA_Initializing;
3197
3198 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003199 if (Entity.getDecl() &&
3200 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3201 return Sema::AA_Sending;
3202
Douglas Gregore1314a62009-12-18 05:02:21 +00003203 return Sema::AA_Passing;
3204
3205 case InitializedEntity::EK_Result:
3206 return Sema::AA_Returning;
3207
3208 case InitializedEntity::EK_Exception:
3209 case InitializedEntity::EK_Base:
3210 llvm_unreachable("No assignment action for C++-specific initialization");
3211 break;
3212
3213 case InitializedEntity::EK_Temporary:
3214 // FIXME: Can we tell apart casting vs. converting?
3215 return Sema::AA_Casting;
3216
3217 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003218 case InitializedEntity::EK_ArrayElement:
3219 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003220 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003221 return Sema::AA_Initializing;
3222 }
3223
3224 return Sema::AA_Converting;
3225}
3226
Douglas Gregor95562572010-04-24 23:45:46 +00003227/// \brief Whether we should binding a created object as a temporary when
3228/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003229static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003230 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003231 case InitializedEntity::EK_ArrayElement:
3232 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003233 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003234 case InitializedEntity::EK_New:
3235 case InitializedEntity::EK_Variable:
3236 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003237 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003238 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003239 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003240 return false;
3241
3242 case InitializedEntity::EK_Parameter:
3243 case InitializedEntity::EK_Temporary:
3244 return true;
3245 }
3246
3247 llvm_unreachable("missed an InitializedEntity kind?");
3248}
3249
Douglas Gregor95562572010-04-24 23:45:46 +00003250/// \brief Whether the given entity, when initialized with an object
3251/// created for that initialization, requires destruction.
3252static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3253 switch (Entity.getKind()) {
3254 case InitializedEntity::EK_Member:
3255 case InitializedEntity::EK_Result:
3256 case InitializedEntity::EK_New:
3257 case InitializedEntity::EK_Base:
3258 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003259 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003260 return false;
3261
3262 case InitializedEntity::EK_Variable:
3263 case InitializedEntity::EK_Parameter:
3264 case InitializedEntity::EK_Temporary:
3265 case InitializedEntity::EK_ArrayElement:
3266 case InitializedEntity::EK_Exception:
3267 return true;
3268 }
3269
3270 llvm_unreachable("missed an InitializedEntity kind?");
3271}
3272
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003273/// \brief Make a (potentially elidable) temporary copy of the object
3274/// provided by the given initializer by calling the appropriate copy
3275/// constructor.
3276///
3277/// \param S The Sema object used for type-checking.
3278///
3279/// \param T The type of the temporary object, which must either by
3280/// the type of the initializer expression or a superclass thereof.
3281///
3282/// \param Enter The entity being initialized.
3283///
3284/// \param CurInit The initializer expression.
3285///
3286/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3287/// is permitted in C++03 (but not C++0x) when binding a reference to
3288/// an rvalue.
3289///
3290/// \returns An expression that copies the initializer expression into
3291/// a temporary object, or an error expression if a copy could not be
3292/// created.
John McCalldadc5752010-08-24 06:29:42 +00003293static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003294 QualType T,
3295 const InitializedEntity &Entity,
3296 ExprResult CurInit,
3297 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003298 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003299 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003300 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003301 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003302 Class = cast<CXXRecordDecl>(Record->getDecl());
3303 if (!Class)
3304 return move(CurInit);
3305
3306 // C++0x [class.copy]p34:
3307 // When certain criteria are met, an implementation is allowed to
3308 // omit the copy/move construction of a class object, even if the
3309 // copy/move constructor and/or destructor for the object have
3310 // side effects. [...]
3311 // - when a temporary class object that has not been bound to a
3312 // reference (12.2) would be copied/moved to a class object
3313 // with the same cv-unqualified type, the copy/move operation
3314 // can be omitted by constructing the temporary object
3315 // directly into the target of the omitted copy/move
3316 //
3317 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003318 // elision for return statements and throw expressions are handled as part
3319 // of constructor initialization, while copy elision for exception handlers
3320 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003321 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003322 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003323 switch (Entity.getKind()) {
3324 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003325 Loc = Entity.getReturnLoc();
3326 break;
3327
3328 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003329 Loc = Entity.getThrowLoc();
3330 break;
3331
3332 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003333 Loc = Entity.getDecl()->getLocation();
3334 break;
3335
Anders Carlsson0bd52402010-01-24 00:19:41 +00003336 case InitializedEntity::EK_ArrayElement:
3337 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003338 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003339 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003340 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003341 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003342 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003343 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003344 Loc = CurInitExpr->getLocStart();
3345 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003346 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003347
3348 // Make sure that the type we are copying is complete.
3349 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3350 return move(CurInit);
3351
Douglas Gregore1314a62009-12-18 05:02:21 +00003352 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003353 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003354 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003355 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003356 Con != ConEnd; ++Con) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003357 // Only consider copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003358 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3359 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor7566e4a2010-04-18 02:16:12 +00003360 !Constructor->isCopyConstructor() ||
3361 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregore1314a62009-12-18 05:02:21 +00003362 continue;
John McCalla0296f72010-03-19 07:35:19 +00003363
3364 DeclAccessPair FoundDecl
3365 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3366 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003367 &CurInitExpr, 1, CandidateSet);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003368 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003369
3370 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00003371 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003372 case OR_Success:
3373 break;
3374
3375 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003376 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3377 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3378 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003379 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003380 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003381 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003382 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003383 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003384 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003385
3386 case OR_Ambiguous:
3387 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003388 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003389 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003390 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003391 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003392
3393 case OR_Deleted:
3394 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003395 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003396 << CurInitExpr->getSourceRange();
3397 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3398 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003399 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003400 }
3401
Douglas Gregor5ab11652010-04-17 22:01:05 +00003402 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003403 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003404 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003405
Anders Carlssona01874b2010-04-21 18:47:17 +00003406 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003407 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003408
3409 if (IsExtraneousCopy) {
3410 // If this is a totally extraneous copy for C++03 reference
3411 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003412 // expression. We don't generate an (elided) copy operation here
3413 // because doing so would require us to pass down a flag to avoid
3414 // infinite recursion, where each step adds another extraneous,
3415 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003416
Douglas Gregor30b52772010-04-18 07:57:34 +00003417 // Instantiate the default arguments of any extra parameters in
3418 // the selected copy constructor, as if we were going to create a
3419 // proper call to the copy constructor.
3420 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3421 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3422 if (S.RequireCompleteType(Loc, Parm->getType(),
3423 S.PDiag(diag::err_call_incomplete_argument)))
3424 break;
3425
3426 // Build the default argument expression; we don't actually care
3427 // if this succeeds or not, because this routine will complain
3428 // if there was a problem.
3429 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3430 }
3431
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003432 return S.Owned(CurInitExpr);
3433 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003434
3435 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003436 // constructor call (we might have derived-to-base conversions, or
3437 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003438 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003439 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003440 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003441
Douglas Gregord0ace022010-04-25 00:55:24 +00003442 // Actually perform the constructor call.
3443 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003444 move_arg(ConstructorArgs),
3445 /*ZeroInit*/ false,
3446 CXXConstructExpr::CK_Complete);
Douglas Gregord0ace022010-04-25 00:55:24 +00003447
3448 // If we're supposed to bind temporaries, do so.
3449 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3450 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3451 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003452}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003453
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003454void InitializationSequence::PrintInitLocationNote(Sema &S,
3455 const InitializedEntity &Entity) {
3456 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3457 if (Entity.getDecl()->getLocation().isInvalid())
3458 return;
3459
3460 if (Entity.getDecl()->getDeclName())
3461 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3462 << Entity.getDecl()->getDeclName();
3463 else
3464 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3465 }
3466}
3467
John McCalldadc5752010-08-24 06:29:42 +00003468ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003469InitializationSequence::Perform(Sema &S,
3470 const InitializedEntity &Entity,
3471 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003472 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003473 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003474 if (SequenceKind == FailedSequence) {
3475 unsigned NumArgs = Args.size();
3476 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003477 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003478 }
3479
3480 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003481 // If the declaration is a non-dependent, incomplete array type
3482 // that has an initializer, then its type will be completed once
3483 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003484 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003485 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003486 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003487 if (const IncompleteArrayType *ArrayT
3488 = S.Context.getAsIncompleteArrayType(DeclType)) {
3489 // FIXME: We don't currently have the ability to accurately
3490 // compute the length of an initializer list without
3491 // performing full type-checking of the initializer list
3492 // (since we have to determine where braces are implicitly
3493 // introduced and such). So, we fall back to making the array
3494 // type a dependently-sized array type with no specified
3495 // bound.
3496 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3497 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003498
Douglas Gregor51e77d52009-12-10 17:56:55 +00003499 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003500 if (DeclaratorDecl *DD = Entity.getDecl()) {
3501 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3502 TypeLoc TL = TInfo->getTypeLoc();
3503 if (IncompleteArrayTypeLoc *ArrayLoc
3504 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3505 Brackets = ArrayLoc->getBracketsRange();
3506 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003507 }
3508
3509 *ResultType
3510 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3511 /*NumElts=*/0,
3512 ArrayT->getSizeModifier(),
3513 ArrayT->getIndexTypeCVRQualifiers(),
3514 Brackets);
3515 }
3516
3517 }
3518 }
3519
Eli Friedmana553d4a2009-12-22 02:35:53 +00003520 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003521 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003522
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003523 if (Args.size() == 0)
3524 return S.Owned((Expr *)0);
3525
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003526 unsigned NumArgs = Args.size();
3527 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3528 SourceLocation(),
3529 (Expr **)Args.release(),
3530 NumArgs,
3531 SourceLocation()));
3532 }
3533
Douglas Gregor85dabae2009-12-16 01:38:02 +00003534 if (SequenceKind == NoInitialization)
3535 return S.Owned((Expr *)0);
3536
Douglas Gregor1b303932009-12-22 15:35:07 +00003537 QualType DestType = Entity.getType().getNonReferenceType();
3538 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003539 // the same as Entity.getDecl()->getType() in cases involving type merging,
3540 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003541 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003542 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003543 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003544
John McCalldadc5752010-08-24 06:29:42 +00003545 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003546
3547 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3548
3549 // For initialization steps that start with a single initializer,
3550 // grab the only argument out the Args and place it into the "current"
3551 // initializer.
3552 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003553 case SK_ResolveAddressOfOverloadedFunction:
3554 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003555 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003556 case SK_CastDerivedToBaseLValue:
3557 case SK_BindReference:
3558 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003559 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003560 case SK_UserConversion:
3561 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003562 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003563 case SK_QualificationConversionRValue:
3564 case SK_ConversionSequence:
3565 case SK_ListInitialization:
3566 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003567 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003568 case SK_ObjCObjectConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00003569 assert(Args.size() == 1);
John McCalldadc5752010-08-24 06:29:42 +00003570 CurInit = ExprResult(((Expr **)(Args.get()))[0]->Retain());
Douglas Gregore1314a62009-12-18 05:02:21 +00003571 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003572 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003573 break;
3574
3575 case SK_ConstructorInitialization:
3576 case SK_ZeroInitialization:
3577 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003578 }
3579
3580 // Walk through the computed steps for the initialization sequence,
3581 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003582 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003583 for (step_iterator Step = step_begin(), StepEnd = step_end();
3584 Step != StepEnd; ++Step) {
3585 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003586 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003587
3588 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003589 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003590
3591 switch (Step->Kind) {
3592 case SK_ResolveAddressOfOverloadedFunction:
3593 // Overload resolution determined which function invoke; update the
3594 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003595 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003596 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003597 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003598 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003599 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003600 break;
3601
3602 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003603 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604 case SK_CastDerivedToBaseLValue: {
3605 // We have a derived-to-base cast that produces either an rvalue or an
3606 // lvalue. Perform that cast.
3607
John McCallcf142162010-08-07 06:22:56 +00003608 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003609
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003610 // Casts to inaccessible base classes are allowed with C-style casts.
3611 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3612 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3613 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003614 CurInitExpr->getSourceRange(),
3615 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003616 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003617
Douglas Gregor88d292c2010-05-13 16:44:06 +00003618 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3619 QualType T = SourceType;
3620 if (const PointerType *Pointer = T->getAs<PointerType>())
3621 T = Pointer->getPointeeType();
3622 if (const RecordType *RecordTy = T->getAs<RecordType>())
3623 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3624 cast<CXXRecordDecl>(RecordTy->getDecl()));
3625 }
3626
John McCall2536c6d2010-08-25 10:28:54 +00003627 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003628 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003629 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003630 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003631 VK_XValue :
3632 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003633 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3634 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003635 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003636 CurInit.get(),
3637 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003638 break;
3639 }
3640
3641 case SK_BindReference:
3642 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3643 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3644 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003645 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003646 << BitField->getDeclName()
3647 << CurInitExpr->getSourceRange();
3648 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003649 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003650 }
Anders Carlssona91be642010-01-29 02:47:33 +00003651
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003652 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003653 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003654 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3655 << Entity.getType().isVolatileQualified()
3656 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003657 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003658 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003659 }
3660
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003661 // Reference binding does not have any corresponding ASTs.
3662
3663 // Check exception specifications
3664 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003665 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003666
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003667 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003668
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003669 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003670 // Reference binding does not have any corresponding ASTs.
3671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003672 // Check exception specifications
3673 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003674 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003675
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003676 break;
3677
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003678 case SK_ExtraneousCopyToTemporary:
3679 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3680 /*IsExtraneousCopy=*/true);
3681 break;
3682
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003683 case SK_UserConversion: {
3684 // We have a user-defined conversion that invokes either a constructor
3685 // or a conversion function.
John McCalle3027922010-08-25 11:45:40 +00003686 CastKind CastKind = CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003687 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003688 FunctionDecl *Fn = Step->Function.Function;
3689 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003690 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003691 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003692 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003693 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003694 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003695 SourceLocation Loc = CurInitExpr->getLocStart();
3696 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003697
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003698 // Determine the arguments required to actually perform the constructor
3699 // call.
3700 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00003701 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003702 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003703 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003704
3705 // Build the an expression that constructs a temporary.
3706 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003707 move_arg(ConstructorArgs),
3708 /*ZeroInit*/ false,
3709 CXXConstructExpr::CK_Complete);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003710 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003711 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003712
Anders Carlssona01874b2010-04-21 18:47:17 +00003713 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003714 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003715 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003716
John McCalle3027922010-08-25 11:45:40 +00003717 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003718 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3719 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3720 S.IsDerivedFrom(SourceType, Class))
3721 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003722
3723 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003724 } else {
3725 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003726 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003727 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003728 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003729 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003730 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003731
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003732 // FIXME: Should we move this initialization into a separate
3733 // derived-to-base conversion? I believe the answer is "no", because
3734 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003735 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003736 FoundFn, Conversion))
John McCallfaf5fb42010-08-26 23:41:50 +00003737 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003738
3739 // Do a little dance to make sure that CurInit has the proper
3740 // pointer.
3741 CurInit.release();
3742
3743 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003744 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3745 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003746 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003747 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003748
John McCalle3027922010-08-25 11:45:40 +00003749 CastKind = CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003750
3751 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752 }
3753
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003754 bool RequiresCopy = !IsCopy &&
3755 getKind() != InitializationSequence::ReferenceBinding;
3756 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003757 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003758 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3759 CurInitExpr = static_cast<Expr *>(CurInit.get());
3760 QualType T = CurInitExpr->getType();
3761 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003762 CXXDestructorDecl *Destructor
3763 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003764 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3765 S.PDiag(diag::err_access_dtor_temp) << T);
3766 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3767 }
3768 }
3769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003770 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003771 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003772 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3773 CurInitExpr->getType(),
3774 CastKind, CurInitExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00003775 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003776
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003777 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003778 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3779 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003780
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003781 break;
3782 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003783
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003784 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003785 case SK_QualificationConversionXValue:
3786 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003787 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003788 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003789 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003790 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003791 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003792 VK_XValue :
3793 VK_RValue);
John McCalle3027922010-08-25 11:45:40 +00003794 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003795 CurInit.release();
3796 CurInit = S.Owned(CurInitExpr);
3797 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003798 }
3799
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003800 case SK_ConversionSequence: {
3801 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3802
3803 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3804 Sema::AA_Converting, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003805 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003806
3807 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003808 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003809 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003810 }
3811
Douglas Gregor51e77d52009-12-10 17:56:55 +00003812 case SK_ListInitialization: {
3813 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3814 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003815 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003816 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003817
3818 CurInit.release();
3819 CurInit = S.Owned(InitList);
3820 break;
3821 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003822
3823 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003824 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003825 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003826 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003827
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003828 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003829 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003830 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3831 ? Kind.getEqualLoc()
3832 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003833
3834 if (Kind.getKind() == InitializationKind::IK_Default) {
3835 // Force even a trivial, implicit default constructor to be
3836 // semantically checked. We do this explicitly because we don't build
3837 // the definition for completely trivial constructors.
3838 CXXRecordDecl *ClassDecl = Constructor->getParent();
3839 assert(ClassDecl && "No parent class for constructor.");
3840 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3841 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3842 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3843 }
3844
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003845 // Determine the arguments required to actually perform the constructor
3846 // call.
3847 if (S.CompleteConstructorCall(Constructor, move(Args),
3848 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003849 return ExprError();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003850
Chandler Carruthc9262402010-08-23 07:55:51 +00003851
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003852 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003853 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003854 (Kind.getKind() == InitializationKind::IK_Direct ||
3855 Kind.getKind() == InitializationKind::IK_Value)) {
3856 // An explicitly-constructed temporary, e.g., X(1, 2).
3857 unsigned NumExprs = ConstructorArgs.size();
3858 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003859 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor2b88c112010-09-08 00:15:04 +00003860
3861 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3862 if (!TSInfo)
3863 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3864
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003865 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3866 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00003867 TSInfo,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003868 Exprs,
3869 NumExprs,
Douglas Gregor199db362010-04-27 20:36:09 +00003870 Kind.getParenRange().getEnd(),
3871 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003872 } else {
3873 CXXConstructExpr::ConstructionKind ConstructKind =
3874 CXXConstructExpr::CK_Complete;
3875
3876 if (Entity.getKind() == InitializedEntity::EK_Base) {
3877 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3878 CXXConstructExpr::CK_VirtualBase :
3879 CXXConstructExpr::CK_NonVirtualBase;
3880 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003881
3882 // If the entity allows NRVO, mark the construction as elidable
3883 // unconditionally.
3884 if (Entity.allowsNRVO())
3885 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3886 Constructor, /*Elidable=*/true,
3887 move_arg(ConstructorArgs),
3888 ConstructorInitRequiresZeroInit,
3889 ConstructKind);
3890 else
3891 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3892 Constructor,
3893 move_arg(ConstructorArgs),
3894 ConstructorInitRequiresZeroInit,
3895 ConstructKind);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003896 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003897 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003898 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003899
3900 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003901 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003902 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003903 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003904
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003905 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003906 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003907
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003908 break;
3909 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003910
3911 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003912 step_iterator NextStep = Step;
3913 ++NextStep;
3914 if (NextStep != StepEnd &&
3915 NextStep->Kind == SK_ConstructorInitialization) {
3916 // The need for zero-initialization is recorded directly into
3917 // the call to the object's constructor within the next step.
3918 ConstructorInitRequiresZeroInit = true;
3919 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3920 S.getLangOptions().CPlusPlus &&
3921 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00003922 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3923 if (!TSInfo)
3924 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
3925 Kind.getRange().getBegin());
3926
3927 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
3928 TSInfo->getType().getNonLValueExprType(S.Context),
3929 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003930 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003931 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003932 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003933 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003934 break;
3935 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003936
3937 case SK_CAssignment: {
3938 QualType SourceType = CurInitExpr->getType();
3939 Sema::AssignConvertType ConvTy =
3940 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003941
3942 // If this is a call, allow conversion to a transparent union.
3943 if (ConvTy != Sema::Compatible &&
3944 Entity.getKind() == InitializedEntity::EK_Parameter &&
3945 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3946 == Sema::Compatible)
3947 ConvTy = Sema::Compatible;
3948
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003949 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00003950 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3951 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003952 CurInitExpr,
3953 getAssignmentAction(Entity),
3954 &Complained)) {
3955 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003956 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003957 } else if (Complained)
3958 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003959
3960 CurInit.release();
3961 CurInit = S.Owned(CurInitExpr);
3962 break;
3963 }
Eli Friedman78275202009-12-19 08:11:05 +00003964
3965 case SK_StringInit: {
3966 QualType Ty = Step->Type;
3967 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3968 break;
3969 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003970
3971 case SK_ObjCObjectConversion:
3972 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003973 CK_ObjCObjectLValueCast,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003974 S.CastCategory(CurInitExpr));
3975 CurInit.release();
3976 CurInit = S.Owned(CurInitExpr);
3977 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003978 }
3979 }
3980
3981 return move(CurInit);
3982}
3983
3984//===----------------------------------------------------------------------===//
3985// Diagnose initialization failures
3986//===----------------------------------------------------------------------===//
3987bool InitializationSequence::Diagnose(Sema &S,
3988 const InitializedEntity &Entity,
3989 const InitializationKind &Kind,
3990 Expr **Args, unsigned NumArgs) {
3991 if (SequenceKind != FailedSequence)
3992 return false;
3993
Douglas Gregor1b303932009-12-22 15:35:07 +00003994 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003995 switch (Failure) {
3996 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003997 // FIXME: Customize for the initialized entity?
3998 if (NumArgs == 0)
3999 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4000 << DestType.getNonReferenceType();
4001 else // FIXME: diagnostic below could be better!
4002 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4003 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004004 break;
4005
4006 case FK_ArrayNeedsInitList:
4007 case FK_ArrayNeedsInitListOrStringLiteral:
4008 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4009 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4010 break;
4011
John McCall16df1e52010-03-30 21:47:33 +00004012 case FK_AddressOfOverloadFailed: {
4013 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004014 S.ResolveAddressOfOverloadedFunction(Args[0],
4015 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004016 true,
4017 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004018 break;
John McCall16df1e52010-03-30 21:47:33 +00004019 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004020
4021 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004022 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004023 switch (FailedOverloadResult) {
4024 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004025 if (Failure == FK_UserConversionOverloadFailed)
4026 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4027 << Args[0]->getType() << DestType
4028 << Args[0]->getSourceRange();
4029 else
4030 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4031 << DestType << Args[0]->getType()
4032 << Args[0]->getSourceRange();
4033
John McCall5c32be02010-08-24 20:38:10 +00004034 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004035 break;
4036
4037 case OR_No_Viable_Function:
4038 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4039 << Args[0]->getType() << DestType.getNonReferenceType()
4040 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004041 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004042 break;
4043
4044 case OR_Deleted: {
4045 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4046 << Args[0]->getType() << DestType.getNonReferenceType()
4047 << Args[0]->getSourceRange();
4048 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004049 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004050 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4051 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004052 if (Ovl == OR_Deleted) {
4053 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4054 << Best->Function->isDeleted();
4055 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004056 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057 }
4058 break;
4059 }
4060
4061 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004062 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004063 break;
4064 }
4065 break;
4066
4067 case FK_NonConstLValueReferenceBindingToTemporary:
4068 case FK_NonConstLValueReferenceBindingToUnrelated:
4069 S.Diag(Kind.getLocation(),
4070 Failure == FK_NonConstLValueReferenceBindingToTemporary
4071 ? diag::err_lvalue_reference_bind_to_temporary
4072 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004073 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004074 << DestType.getNonReferenceType()
4075 << Args[0]->getType()
4076 << Args[0]->getSourceRange();
4077 break;
4078
4079 case FK_RValueReferenceBindingToLValue:
4080 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4081 << Args[0]->getSourceRange();
4082 break;
4083
4084 case FK_ReferenceInitDropsQualifiers:
4085 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4086 << DestType.getNonReferenceType()
4087 << Args[0]->getType()
4088 << Args[0]->getSourceRange();
4089 break;
4090
4091 case FK_ReferenceInitFailed:
4092 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4093 << DestType.getNonReferenceType()
4094 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4095 << Args[0]->getType()
4096 << Args[0]->getSourceRange();
4097 break;
4098
4099 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004100 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4101 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004102 << DestType
4103 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4104 << Args[0]->getType()
4105 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004106 break;
4107
4108 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004109 SourceRange R;
4110
4111 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004112 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004113 InitList->getLocEnd());
Douglas Gregor8ec51732010-09-08 21:40:08 +00004114 else
4115 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004116
Douglas Gregor8ec51732010-09-08 21:40:08 +00004117 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4118 if (Kind.isCStyleOrFunctionalCast())
4119 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4120 << R;
4121 else
4122 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4123 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004124 break;
4125 }
4126
4127 case FK_ReferenceBindingToInitList:
4128 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4129 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4130 break;
4131
4132 case FK_InitListBadDestinationType:
4133 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4134 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4135 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004136
4137 case FK_ConstructorOverloadFailed: {
4138 SourceRange ArgsRange;
4139 if (NumArgs)
4140 ArgsRange = SourceRange(Args[0]->getLocStart(),
4141 Args[NumArgs - 1]->getLocEnd());
4142
4143 // FIXME: Using "DestType" for the entity we're printing is probably
4144 // bad.
4145 switch (FailedOverloadResult) {
4146 case OR_Ambiguous:
4147 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4148 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004149 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4150 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004151 break;
4152
4153 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004154 if (Kind.getKind() == InitializationKind::IK_Default &&
4155 (Entity.getKind() == InitializedEntity::EK_Base ||
4156 Entity.getKind() == InitializedEntity::EK_Member) &&
4157 isa<CXXConstructorDecl>(S.CurContext)) {
4158 // This is implicit default initialization of a member or
4159 // base within a constructor. If no viable function was
4160 // found, notify the user that she needs to explicitly
4161 // initialize this base/member.
4162 CXXConstructorDecl *Constructor
4163 = cast<CXXConstructorDecl>(S.CurContext);
4164 if (Entity.getKind() == InitializedEntity::EK_Base) {
4165 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4166 << Constructor->isImplicit()
4167 << S.Context.getTypeDeclType(Constructor->getParent())
4168 << /*base=*/0
4169 << Entity.getType();
4170
4171 RecordDecl *BaseDecl
4172 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4173 ->getDecl();
4174 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4175 << S.Context.getTagDeclType(BaseDecl);
4176 } else {
4177 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4178 << Constructor->isImplicit()
4179 << S.Context.getTypeDeclType(Constructor->getParent())
4180 << /*member=*/1
4181 << Entity.getName();
4182 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4183
4184 if (const RecordType *Record
4185 = Entity.getType()->getAs<RecordType>())
4186 S.Diag(Record->getDecl()->getLocation(),
4187 diag::note_previous_decl)
4188 << S.Context.getTagDeclType(Record->getDecl());
4189 }
4190 break;
4191 }
4192
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004193 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4194 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004195 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004196 break;
4197
4198 case OR_Deleted: {
4199 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4200 << true << DestType << ArgsRange;
4201 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004202 OverloadingResult Ovl
4203 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004204 if (Ovl == OR_Deleted) {
4205 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4206 << Best->Function->isDeleted();
4207 } else {
4208 llvm_unreachable("Inconsistent overload resolution?");
4209 }
4210 break;
4211 }
4212
4213 case OR_Success:
4214 llvm_unreachable("Conversion did not fail!");
4215 break;
4216 }
4217 break;
4218 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004219
4220 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004221 if (Entity.getKind() == InitializedEntity::EK_Member &&
4222 isa<CXXConstructorDecl>(S.CurContext)) {
4223 // This is implicit default-initialization of a const member in
4224 // a constructor. Complain that it needs to be explicitly
4225 // initialized.
4226 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4227 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4228 << Constructor->isImplicit()
4229 << S.Context.getTypeDeclType(Constructor->getParent())
4230 << /*const=*/1
4231 << Entity.getName();
4232 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4233 << Entity.getName();
4234 } else {
4235 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4236 << DestType << (bool)DestType->getAs<RecordType>();
4237 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004238 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004239
4240 case FK_Incomplete:
4241 S.RequireCompleteType(Kind.getLocation(), DestType,
4242 diag::err_init_incomplete_type);
4243 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004244 }
4245
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004246 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004247 return true;
4248}
Douglas Gregore1314a62009-12-18 05:02:21 +00004249
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004250void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4251 switch (SequenceKind) {
4252 case FailedSequence: {
4253 OS << "Failed sequence: ";
4254 switch (Failure) {
4255 case FK_TooManyInitsForReference:
4256 OS << "too many initializers for reference";
4257 break;
4258
4259 case FK_ArrayNeedsInitList:
4260 OS << "array requires initializer list";
4261 break;
4262
4263 case FK_ArrayNeedsInitListOrStringLiteral:
4264 OS << "array requires initializer list or string literal";
4265 break;
4266
4267 case FK_AddressOfOverloadFailed:
4268 OS << "address of overloaded function failed";
4269 break;
4270
4271 case FK_ReferenceInitOverloadFailed:
4272 OS << "overload resolution for reference initialization failed";
4273 break;
4274
4275 case FK_NonConstLValueReferenceBindingToTemporary:
4276 OS << "non-const lvalue reference bound to temporary";
4277 break;
4278
4279 case FK_NonConstLValueReferenceBindingToUnrelated:
4280 OS << "non-const lvalue reference bound to unrelated type";
4281 break;
4282
4283 case FK_RValueReferenceBindingToLValue:
4284 OS << "rvalue reference bound to an lvalue";
4285 break;
4286
4287 case FK_ReferenceInitDropsQualifiers:
4288 OS << "reference initialization drops qualifiers";
4289 break;
4290
4291 case FK_ReferenceInitFailed:
4292 OS << "reference initialization failed";
4293 break;
4294
4295 case FK_ConversionFailed:
4296 OS << "conversion failed";
4297 break;
4298
4299 case FK_TooManyInitsForScalar:
4300 OS << "too many initializers for scalar";
4301 break;
4302
4303 case FK_ReferenceBindingToInitList:
4304 OS << "referencing binding to initializer list";
4305 break;
4306
4307 case FK_InitListBadDestinationType:
4308 OS << "initializer list for non-aggregate, non-scalar type";
4309 break;
4310
4311 case FK_UserConversionOverloadFailed:
4312 OS << "overloading failed for user-defined conversion";
4313 break;
4314
4315 case FK_ConstructorOverloadFailed:
4316 OS << "constructor overloading failed";
4317 break;
4318
4319 case FK_DefaultInitOfConst:
4320 OS << "default initialization of a const variable";
4321 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004322
4323 case FK_Incomplete:
4324 OS << "initialization of incomplete type";
4325 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004326 }
4327 OS << '\n';
4328 return;
4329 }
4330
4331 case DependentSequence:
4332 OS << "Dependent sequence: ";
4333 return;
4334
4335 case UserDefinedConversion:
4336 OS << "User-defined conversion sequence: ";
4337 break;
4338
4339 case ConstructorInitialization:
4340 OS << "Constructor initialization sequence: ";
4341 break;
4342
4343 case ReferenceBinding:
4344 OS << "Reference binding: ";
4345 break;
4346
4347 case ListInitialization:
4348 OS << "List initialization: ";
4349 break;
4350
4351 case ZeroInitialization:
4352 OS << "Zero initialization\n";
4353 return;
4354
4355 case NoInitialization:
4356 OS << "No initialization\n";
4357 return;
4358
4359 case StandardConversion:
4360 OS << "Standard conversion: ";
4361 break;
4362
4363 case CAssignment:
4364 OS << "C assignment: ";
4365 break;
4366
4367 case StringInit:
4368 OS << "String initialization: ";
4369 break;
4370 }
4371
4372 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4373 if (S != step_begin()) {
4374 OS << " -> ";
4375 }
4376
4377 switch (S->Kind) {
4378 case SK_ResolveAddressOfOverloadedFunction:
4379 OS << "resolve address of overloaded function";
4380 break;
4381
4382 case SK_CastDerivedToBaseRValue:
4383 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4384 break;
4385
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004386 case SK_CastDerivedToBaseXValue:
4387 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4388 break;
4389
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004390 case SK_CastDerivedToBaseLValue:
4391 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4392 break;
4393
4394 case SK_BindReference:
4395 OS << "bind reference to lvalue";
4396 break;
4397
4398 case SK_BindReferenceToTemporary:
4399 OS << "bind reference to a temporary";
4400 break;
4401
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004402 case SK_ExtraneousCopyToTemporary:
4403 OS << "extraneous C++03 copy to temporary";
4404 break;
4405
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004406 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004407 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004408 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004409
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004410 case SK_QualificationConversionRValue:
4411 OS << "qualification conversion (rvalue)";
4412
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004413 case SK_QualificationConversionXValue:
4414 OS << "qualification conversion (xvalue)";
4415
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004416 case SK_QualificationConversionLValue:
4417 OS << "qualification conversion (lvalue)";
4418 break;
4419
4420 case SK_ConversionSequence:
4421 OS << "implicit conversion sequence (";
4422 S->ICS->DebugPrint(); // FIXME: use OS
4423 OS << ")";
4424 break;
4425
4426 case SK_ListInitialization:
4427 OS << "list initialization";
4428 break;
4429
4430 case SK_ConstructorInitialization:
4431 OS << "constructor initialization";
4432 break;
4433
4434 case SK_ZeroInitialization:
4435 OS << "zero initialization";
4436 break;
4437
4438 case SK_CAssignment:
4439 OS << "C assignment";
4440 break;
4441
4442 case SK_StringInit:
4443 OS << "string initialization";
4444 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004445
4446 case SK_ObjCObjectConversion:
4447 OS << "Objective-C object conversion";
4448 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004449 }
4450 }
4451}
4452
4453void InitializationSequence::dump() const {
4454 dump(llvm::errs());
4455}
4456
Douglas Gregore1314a62009-12-18 05:02:21 +00004457//===----------------------------------------------------------------------===//
4458// Initialization helper functions
4459//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004460ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004461Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4462 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004463 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004464 if (Init.isInvalid())
4465 return ExprError();
4466
4467 Expr *InitE = (Expr *)Init.get();
4468 assert(InitE && "No initialization expression?");
4469
4470 if (EqualLoc.isInvalid())
4471 EqualLoc = InitE->getLocStart();
4472
4473 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4474 EqualLoc);
4475 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4476 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004477 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004478}