blob: a28fd7fe12bd81ef340bf5f892a4fa80d10d61ad [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
John McCall19510852010-08-20 18:27:03 +000018#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000021#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000025#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000028#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000029#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000030using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000031
Chris Lattnerdd8e0062009-02-24 22:27:37 +000032//===----------------------------------------------------------------------===//
33// Sema Initialization Checking
34//===----------------------------------------------------------------------===//
35
Chris Lattner79e079d2009-02-24 23:10:27 +000036static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000037 const ArrayType *AT = Context.getAsArrayType(DeclType);
38 if (!AT) return 0;
39
Eli Friedman8718a6a2009-05-29 18:22:49 +000040 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
41 return 0;
42
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // See if this is a string literal or @encode.
44 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000045
Chris Lattner8879e3b2009-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 Lattner220b6362009-02-26 23:42:47 +000052 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000053
54 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-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 Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000059
Eli Friedmanbb6415c2009-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 Lattner8879e3b2009-02-26 23:26:43 +000066 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattnerdd8e0062009-02-24 22:27:37 +000068 return 0;
69}
70
Chris Lattner79e079d2009-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 Stump1eb44332009-09-09 15:08:12 +000076
Chris Lattner79e079d2009-02-24 23:10:27 +000077 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000078 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000079 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000080 // being initialized to a string literal.
81 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000082 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000083 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000084 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
85 ConstVal,
86 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000087 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000088 }
Mike Stump1eb44332009-09-09 15:08:12 +000089
Eli Friedman8718a6a2009-05-29 18:22:49 +000090 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000091
Eli Friedman8718a6a2009-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 Stump1eb44332009-09-09 15:08:12 +000099
Eli Friedman8718a6a2009-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 Lattnerdd8e0062009-02-24 22:27:37 +0000105}
106
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000107//===----------------------------------------------------------------------===//
108// Semantic checking for initializer lists.
109//===----------------------------------------------------------------------===//
110
Douglas Gregor9e80f722009-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 Lattner8b419b92009-02-24 22:48:58 +0000138namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000139class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000140 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000141 bool hadError;
142 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
143 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000145 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000146 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000147 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000148 unsigned &StructuredIndex,
149 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000150 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000151 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000152 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000153 unsigned &StructuredIndex,
154 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000155 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000156 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000157 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000158 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000159 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000160 unsigned &StructuredIndex,
161 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000162 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000163 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000164 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000165 InitListExpr *StructuredList,
166 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000167 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000168 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000169 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000170 InitListExpr *StructuredList,
171 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000172 void CheckReferenceType(const InitializedEntity &Entity,
173 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000174 unsigned &Index,
175 InitListExpr *StructuredList,
176 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000177 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000178 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000179 InitListExpr *StructuredList,
180 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000181 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000182 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000183 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000184 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000185 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000188 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000190 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000191 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
193 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000195 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000196 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000197 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000198 RecordDecl::field_iterator *NextField,
199 llvm::APSInt *NextElementIndex,
200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000203 bool FinishSubobjectInit,
204 bool TopLevelObject);
Douglas Gregorc34ee5e2009-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 Gregor9e80f722009-01-29 01:05:33 +0000210 void UpdateStructuredListElement(InitListExpr *StructuredList,
211 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000212 Expr *expr);
213 int numArrayElements(QualType DeclType);
214 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000215
Douglas Gregord6d37de2009-12-22 00:05:34 +0000216 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
217 const InitializedEntity &ParentEntity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000219 void FillInValueInitializations(const InitializedEntity &Entity,
220 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000221public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000222 InitListChecker(Sema &S, const InitializedEntity &Entity,
223 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-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 Lattner8b419b92009-02-24 22:48:58 +0000230} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000231
Douglas Gregord6d37de2009-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 McCall60d7b3a2010-08-24 06:29:42 +0000267 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000268 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-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 Kremenek709210f2010-04-13 23:39:13 +0000284 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-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 Gregor4c678342009-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 Gregorcb57fb92009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Ted Kremenek6217b802009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-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 Gregor4c678342009-01-28 21:54:33 +0000319
Douglas Gregord6d37de2009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000321 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000325 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000326
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000336 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000354 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000357
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssond3d824d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregor87fd7032009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-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 Gregor87fd7032009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
John McCall60d7b3a2010-08-24 06:29:42 +0000376 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000377 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000378 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000379 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000380 return;
381 }
382
383 if (hadError) {
384 // Do nothing
385 } else if (Init < NumInits) {
386 ILE->setInit(Init, ElementInit.takeAs<Expr>());
387 } else if (InitSeq.getKind()
388 == InitializationSequence::ConstructorInitialization) {
389 // Value-initialization requires a constructor call, so
390 // extend the initializer list to include the constructor
391 // call and make a note that we'll need to take another pass
392 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000393 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000394 RequiresSecondPass = true;
395 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000396 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000397 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
398 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000399 }
400}
401
Chris Lattner68355a52009-01-29 05:10:57 +0000402
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000403InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
404 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000405 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000406 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000407
Eli Friedmanb85f7072008-05-19 19:16:24 +0000408 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000409 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000410 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000411 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000412 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000413 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000414 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000415
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000416 if (!hadError) {
417 bool RequiresSecondPass = false;
418 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000419 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000420 FillInValueInitializations(Entity, FullyStructuredList,
421 RequiresSecondPass);
422 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000423}
424
425int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000426 // FIXME: use a proper constant
427 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000428 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000429 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000430 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
431 }
432 return maxElements;
433}
434
435int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000436 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000437 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000438 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000439 Field = structDecl->field_begin(),
440 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000441 Field != FieldEnd; ++Field) {
442 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
443 ++InitializableMembers;
444 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000445 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000446 return std::min(InitializableMembers, 1);
447 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000448}
449
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000450void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000451 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000452 QualType T, unsigned &Index,
453 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000454 unsigned &StructuredIndex,
455 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000456 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Steve Naroff0cca7492008-05-01 22:18:59 +0000458 if (T->isArrayType())
459 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000460 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000461 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000462 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000463 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000464 else
465 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000466
Eli Friedman402256f2008-05-25 13:49:22 +0000467 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000468 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000469 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000470 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000471 hadError = true;
472 return;
473 }
474
Douglas Gregor4c678342009-01-28 21:54:33 +0000475 // Build a structured initializer list corresponding to this subobject.
476 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000477 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
478 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000479 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
480 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000482
Douglas Gregor4c678342009-01-28 21:54:33 +0000483 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000484 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000485 CheckListElementTypes(Entity, ParentIList, T,
486 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000487 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000488 StructuredSubobjectInitIndex,
489 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000490 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000491 StructuredSubobjectInitList->setType(T);
492
Douglas Gregored8a93d2009-03-01 17:12:46 +0000493 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000494 // range corresponds with the end of the last initializer it used.
495 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000496 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000497 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
498 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
499 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000500
501 // Warn about missing braces.
502 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000503 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
504 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000505 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000506 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
507 "{")
508 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner1dcd0612010-03-07 04:47:12 +0000509 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000510 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000511 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000512}
513
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000514void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000515 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000516 unsigned &Index,
517 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000518 unsigned &StructuredIndex,
519 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000520 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 SyntacticToSemantic[IList] = StructuredList;
522 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000523 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
524 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000525 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
526 IList->setType(ExprTy);
527 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000528 if (hadError)
529 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000530
Eli Friedman638e1442008-05-25 13:22:35 +0000531 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000532 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000533 if (StructuredIndex == 1 &&
534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000536 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000537 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000538 hadError = true;
539 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000540 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000542 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000543 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000544 // Don't complain for incomplete types, since we'll get an error
545 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000547 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000548 CurrentObjectType->isArrayType()? 0 :
549 CurrentObjectType->isVectorType()? 1 :
550 CurrentObjectType->isScalarType()? 2 :
551 CurrentObjectType->isUnionType()? 3 :
552 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000553
554 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Nate Begeman08634522009-07-07 21:53:06 +0000559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000563
Chris Lattner08202542009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000565 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000566 }
567 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000568
Eli Friedman759f2522009-05-16 11:45:48 +0000569 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000571 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000572 << FixItHint::CreateRemoval(IList->getLocStart())
573 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000574}
575
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000577 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000578 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000579 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000580 unsigned &Index,
581 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000582 unsigned &StructuredIndex,
583 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000584 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000585 CheckScalarType(Entity, IList, DeclType, Index,
586 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000588 CheckVectorType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000590 } else if (DeclType->isAggregateType()) {
591 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000592 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000593 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000595 StructuredList, StructuredIndex,
596 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000597 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000598 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000599 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000600 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000601 CheckArrayType(Entity, IList, DeclType, Zero,
602 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000604 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000605 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000608 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000610 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000611 hadError = true;
Douglas Gregor930d8b52009-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 Lattner08202542009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000622 << DeclType << IList->getSourceRange();
623 hadError = true;
624 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000625 CheckReferenceType(Entity, IList, DeclType, Index,
626 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000627 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000628 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
629 << DeclType;
630 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000631 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000632 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
633 << DeclType;
634 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000635 }
636}
637
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000638void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000639 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000640 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000641 unsigned &Index,
642 InitListExpr *StructuredList,
643 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000644 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000645 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
646 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000648 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 = getStructuredSubobjectInit(IList, Index, ElemType,
650 StructuredList, StructuredIndex,
651 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000652 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000653 newStructuredList, newStructuredIndex);
654 ++StructuredIndex;
655 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000656 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
657 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000658 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000659 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000660 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000661 CheckScalarType(Entity, IList, ElemType, Index,
662 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000663 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000664 CheckReferenceType(Entity, IList, ElemType, Index,
665 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000666 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000667 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-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 Carlssond28b4282009-08-27 17:18:13 +0000673
Anders Carlsson1b36a2f2010-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 McCall60d7b3a2010-08-24 06:29:42 +0000680 ExprResult Result =
John McCallf312b1e2010-08-26 23:41:50 +0000681 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000682 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000683 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000684
685 UpdateStructuredListElement(StructuredList, StructuredIndex,
686 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000687 ++Index;
688 return;
689 }
690
691 // Fall through for subaggregate initialization
692 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000693 // C99 6.7.8p13:
Douglas Gregor930d8b52009-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 Friedman6b5374f2009-06-13 10:38:46 +0000701 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000702 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-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 Stump1eb44332009-09-09 15:08:12 +0000712 //
Douglas Gregor930d8b52009-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 Carlsson987dc6a2010-01-23 20:47:59 +0000718 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-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 Carlssonca755fe2010-01-30 01:56:32 +0000724 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
725 SemaRef.Owned(expr));
726 IList->setInit(Index, 0);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000727 hadError = true;
728 ++Index;
729 ++StructuredIndex;
730 }
731 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000732}
733
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000734void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000735 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000736 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000737 InitListExpr *StructuredList,
738 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000739 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000740 Expr *expr = IList->getInit(Index);
Eli Friedman09865a92010-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 Friedmanbb504d32008-05-19 20:12:18 +0000748 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000749 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000750 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000751 diag::err_designator_for_scalar_init)
752 << DeclType << expr->getSourceRange();
753 hadError = true;
754 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000755 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000756 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000757 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000758
John McCall60d7b3a2010-08-24 06:29:42 +0000759 ExprResult Result =
Eli Friedmana1635d92010-01-25 17:04:54 +0000760 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
761 SemaRef.Owned(expr));
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000762
Chandler Carruthb5719242010-02-13 07:23:01 +0000763 Expr *ResultExpr = 0;
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000764
765 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000766 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-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 Gregor05c13a32009-01-22 00:58:24 +0000774 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000775 if (hadError)
776 ++StructuredIndex;
777 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000778 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000779 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000780 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000781 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000782 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000783 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000784 ++Index;
785 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000786 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000787 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000788}
789
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000790void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
791 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-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 Lattner08202542009-02-24 22:50:46 +0000798 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000799 << DeclType << IList->getSourceRange();
800 hadError = true;
801 ++Index;
802 ++StructuredIndex;
803 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000804 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000805
John McCall60d7b3a2010-08-24 06:29:42 +0000806 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000807 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
808 SemaRef.Owned(expr));
809
810 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000811 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000812
813 expr = Result.takeAs<Expr>();
814 IList->setInit(Index, expr);
815
Douglas Gregor930d8b52009-01-30 22:09:00 +0000816 if (hadError)
817 ++StructuredIndex;
818 else
819 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
820 ++Index;
821 } else {
Mike Stump390b4cc2009-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 Stump1eb44332009-09-09 15:08:12 +0000826 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-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 Carlsson8ff9e862010-01-23 23:23:01 +0000837void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000838 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000839 unsigned &Index,
840 InitListExpr *StructuredList,
841 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000842 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000843 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000844 unsigned maxElements = VT->getNumElements();
845 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000846 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Nate Begeman2ef13e52009-08-10 23:49:36 +0000848 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000849 InitializedEntity ElementEntity =
850 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000851
Anders Carlsson8ff9e862010-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 Carlsson46f46592010-01-23 19:55:29 +0000856
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000857 ElementEntity.setElementIndex(Index);
858 CheckSubElementType(ElementEntity, IList, elementType, Index,
859 StructuredList, StructuredIndex);
860 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000861 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000862 InitializedEntity ElementEntity =
863 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
864
Nate Begeman2ef13e52009-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 Carlsson8ff9e862010-01-23 23:23:01 +0000870
871 ElementEntity.setElementIndex(Index);
872
Nate Begeman2ef13e52009-08-10 23:49:36 +0000873 QualType IType = IList->getInit(Index)->getType();
874 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000875 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000876 StructuredList, StructuredIndex);
877 ++numEltsInit;
878 } else {
Nate Begeman3e315522010-07-07 22:26:56 +0000879 QualType VecType;
John McCall183700f2009-09-21 23:43:11 +0000880 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000881 unsigned numIElts = IVT->getNumElements();
Nate Begeman3e315522010-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 Carlsson8ff9e862010-01-23 23:23:01 +0000888 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000889 StructuredList, StructuredIndex);
890 numEltsInit += numIElts;
891 }
892 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000893 }
Mike Stump1eb44332009-09-09 15:08:12 +0000894
John Thompsonf3afbea2010-04-20 23:21:17 +0000895 // OpenCL requires all elements to be initialized.
Nate Begeman2ef13e52009-08-10 23:49:36 +0000896 if (numEltsInit != maxElements)
Chris Lattnere12a7792010-04-20 05:19:10 +0000897 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman2ef13e52009-08-10 23:49:36 +0000898 SemaRef.Diag(IList->getSourceRange().getBegin(),
899 diag::err_vector_incorrect_num_initializers)
900 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000901 }
902}
903
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000904void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000905 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000906 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000907 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000908 unsigned &Index,
909 InitListExpr *StructuredList,
910 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000911 // Check for the special-case of initializing an array with a string.
912 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000913 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
914 SemaRef.Context)) {
915 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-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 Lattnerf71ae8d2009-02-24 22:41:04 +0000921 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000922 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000923 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000924 return;
925 }
926 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000927 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000928 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-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 Lattner08202542009-02-24 22:50:46 +0000932 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000933 diag::err_variable_object_no_init)
934 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000935 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000936 ++Index;
937 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000938 return;
939 }
940
Douglas Gregor05c13a32009-01-22 00:58:24 +0000941 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000942 llvm::APSInt maxElements(elementIndex.getBitWidth(),
943 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000944 bool maxElementsKnown = false;
945 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000946 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000947 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000948 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000949 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000950 maxElementsKnown = true;
951 }
952
Chris Lattner08202542009-02-24 22:50:46 +0000953 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000954 ->getElementType();
Douglas Gregor05c13a32009-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 Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +0000963
Douglas Gregor87f55cf2009-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 Carlsson9a8a70e2010-01-23 22:49:02 +0000966 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000967 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000968 StructuredList, StructuredIndex, true,
969 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000970 hadError = true;
971 continue;
972 }
973
Douglas Gregorf6c717c2009-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 Gregore3fa2de2009-01-23 18:58:42 +0000978 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000979
Douglas Gregor87f55cf2009-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 Gregor05c13a32009-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 Naroff0cca7492008-05-01 22:18:59 +0000991 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000992
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000993 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +0000994 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000995 Entity);
996 // Check this element.
997 CheckSubElementType(ElementEntity, IList, elementType, Index,
998 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-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 Naroff0cca7492008-05-01 22:18:59 +00001005 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001006 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001007 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001008 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001009 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001010 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-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 Lattner08202542009-02-24 22:50:46 +00001013 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001014 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001015 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001016
Mike Stump1eb44332009-09-09 15:08:12 +00001017 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001018 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001019 }
1020}
1021
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001022void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001023 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001024 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001025 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001026 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001027 unsigned &Index,
1028 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001029 unsigned &StructuredIndex,
1030 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001031 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Eli Friedmanb85f7072008-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 Stump1eb44332009-09-09 15:08:12 +00001038 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001039
1040 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1041 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001042 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001043 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-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 Gregor05c13a32009-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 Kremenek6217b802009-07-29 21:53:49 +00001057 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001058 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001059 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001060 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-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 Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +00001070
Douglas Gregor87f55cf2009-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 Carlsson9a8a70e2010-01-23 22:49:02 +00001073 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001074 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001075 StructuredList, StructuredIndex,
1076 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001077 hadError = true;
1078
Douglas Gregordfb5e592009-02-12 19:00:39 +00001079 InitializedSomething = true;
John McCall80639de2010-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 Gregor05c13a32009-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 Gregordfb5e592009-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 Gregor44b43212008-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 Gregor0bb76892009-01-29 16:53:55 +00001100 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001101 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001102 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001103 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001104 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001105
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001106 InitializedEntity MemberEntity =
1107 InitializedEntity::InitializeMember(*Field, &Entity);
1108 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1109 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001110 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001111
1112 if (DeclType->isUnionType()) {
1113 // Initialize the first field within the union.
1114 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001115 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001116
1117 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001118 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001119
John McCall80639de2010-03-11 19:32:38 +00001120 // Emit warnings for missing struct field initializers.
Douglas Gregor8e198902010-06-18 21:43:10 +00001121 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-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 Stump1eb44332009-09-09 15:08:12 +00001135 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001136 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001137 return;
1138
1139 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001140 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001141 (!isa<InitListExpr>(IList->getInit(Index)) ||
1142 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001143 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001144 diag::err_flexible_array_init_nonempty)
1145 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001146 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001147 << *Field;
1148 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001149 ++Index;
1150 return;
1151 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001152 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-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 Gregoreeb15d42009-02-04 22:46:25 +00001157 }
1158
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001159 InitializedEntity MemberEntity =
1160 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001161
Anders Carlsson8ff9e862010-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 Carlsson987dc6a2010-01-23 20:47:59 +00001167 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001168}
Steve Naroff0cca7492008-05-01 22:18:59 +00001169
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001170/// \brief Expand a field designator that refers to a member of an
1171/// anonymous struct or union into a series of field designators that
1172/// refers to the field within the appropriate subobject.
1173///
1174/// Field/FieldIndex will be updated to point to the (new)
1175/// currently-designated field.
1176static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001177 DesignatedInitExpr *DIE,
1178 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001179 FieldDecl *Field,
1180 RecordDecl::field_iterator &FieldIter,
1181 unsigned &FieldIndex) {
1182 typedef DesignatedInitExpr::Designator Designator;
1183
1184 // Build the path from the current object to the member of the
1185 // anonymous struct/union (backwards).
1186 llvm::SmallVector<FieldDecl *, 4> Path;
1187 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001189 // Build the replacement designators.
1190 llvm::SmallVector<Designator, 4> Replacements;
1191 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1192 FI = Path.rbegin(), FIEnd = Path.rend();
1193 FI != FIEnd; ++FI) {
1194 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001195 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001196 DIE->getDesignator(DesigIdx)->getDotLoc(),
1197 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1198 else
1199 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1200 SourceLocation()));
1201 Replacements.back().setField(*FI);
1202 }
1203
1204 // Expand the current designator into the set of replacement
1205 // designators, so we have a full subobject path down to where the
1206 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001207 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001208 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001210 // Update FieldIter/FieldIndex;
1211 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001212 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001213 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001214 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001215 FieldIter != FEnd; ++FieldIter) {
1216 if (FieldIter->isUnnamedBitfield())
1217 continue;
1218
1219 if (*FieldIter == Path.back())
1220 return;
1221
1222 ++FieldIndex;
1223 }
1224
1225 assert(false && "Unable to find anonymous struct/union field");
1226}
1227
Douglas Gregor05c13a32009-01-22 00:58:24 +00001228/// @brief Check the well-formedness of a C99 designated initializer.
1229///
1230/// Determines whether the designated initializer @p DIE, which
1231/// resides at the given @p Index within the initializer list @p
1232/// IList, is well-formed for a current object of type @p DeclType
1233/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001234/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001235/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001236///
1237/// @param IList The initializer list in which this designated
1238/// initializer occurs.
1239///
Douglas Gregor71199712009-04-15 04:56:10 +00001240/// @param DIE The designated initializer expression.
1241///
1242/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001243///
1244/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1245/// into which the designation in @p DIE should refer.
1246///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001247/// @param NextField If non-NULL and the first designator in @p DIE is
1248/// a field, this will be set to the field declaration corresponding
1249/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001250///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001251/// @param NextElementIndex If non-NULL and the first designator in @p
1252/// DIE is an array designator or GNU array-range designator, this
1253/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001254///
1255/// @param Index Index into @p IList where the designated initializer
1256/// @p DIE occurs.
1257///
Douglas Gregor4c678342009-01-28 21:54:33 +00001258/// @param StructuredList The initializer list expression that
1259/// describes all of the subobject initializers in the order they'll
1260/// actually be initialized.
1261///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001262/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001263bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001264InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001265 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001266 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001267 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001268 QualType &CurrentObjectType,
1269 RecordDecl::field_iterator *NextField,
1270 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001271 unsigned &Index,
1272 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001273 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001274 bool FinishSubobjectInit,
1275 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001276 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001277 // Check the actual initialization for the designated object type.
1278 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001279
1280 // Temporarily remove the designator expression from the
1281 // initializer list that the child calls see, so that we don't try
1282 // to re-process the designator.
1283 unsigned OldIndex = Index;
1284 IList->setInit(OldIndex, DIE->getInit());
1285
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001286 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001287 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001288
1289 // Restore the designated initializer expression in the syntactic
1290 // form of the initializer list.
1291 if (IList->getInit(OldIndex) != DIE->getInit())
1292 DIE->setInit(IList->getInit(OldIndex));
1293 IList->setInit(OldIndex, DIE);
1294
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001295 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001296 }
1297
Douglas Gregor71199712009-04-15 04:56:10 +00001298 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001299 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001300 "Need a non-designated initializer list to start from");
1301
Douglas Gregor71199712009-04-15 04:56:10 +00001302 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001303 // Determine the structural initializer list that corresponds to the
1304 // current subobject.
1305 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001306 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001307 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001308 SourceRange(D->getStartLocation(),
1309 DIE->getSourceRange().getEnd()));
1310 assert(StructuredList && "Expected a structured initializer list");
1311
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001312 if (D->isFieldDesignator()) {
1313 // C99 6.7.8p7:
1314 //
1315 // If a designator has the form
1316 //
1317 // . identifier
1318 //
1319 // then the current object (defined below) shall have
1320 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001321 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001322 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001323 if (!RT) {
1324 SourceLocation Loc = D->getDotLoc();
1325 if (Loc.isInvalid())
1326 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001327 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1328 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001329 ++Index;
1330 return true;
1331 }
1332
Douglas Gregor4c678342009-01-28 21:54:33 +00001333 // Note: we perform a linear search of the fields here, despite
1334 // the fact that we have a faster lookup method, because we always
1335 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001336 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001337 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001338 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001339 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001340 Field = RT->getDecl()->field_begin(),
1341 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001342 for (; Field != FieldEnd; ++Field) {
1343 if (Field->isUnnamedBitfield())
1344 continue;
1345
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001346 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001347 break;
1348
1349 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001350 }
1351
Douglas Gregor4c678342009-01-28 21:54:33 +00001352 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001353 // There was no normal field in the struct with the designated
1354 // name. Perform another lookup for this name, which may find
1355 // something that we can't designate (e.g., a member function),
1356 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001357 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001358 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001359 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001360 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001361 // Name lookup didn't find anything. Determine whether this
1362 // was a typo for another field name.
1363 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1364 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001365 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1366 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001367 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001368 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001369 ->Equals(RT->getDecl())) {
1370 SemaRef.Diag(D->getFieldLoc(),
1371 diag::err_field_designator_unknown_suggest)
1372 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001373 << FixItHint::CreateReplacement(D->getFieldLoc(),
1374 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001375 SemaRef.Diag(ReplacementField->getLocation(),
1376 diag::note_previous_decl)
1377 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001378 } else {
1379 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1380 << FieldName << CurrentObjectType;
1381 ++Index;
1382 return true;
1383 }
1384 } else if (!KnownField) {
1385 // Determine whether we found a field at all.
1386 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1387 }
1388
1389 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001390 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001391 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001392 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001393 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001394 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001395 ++Index;
1396 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001397 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001398
1399 if (!KnownField &&
1400 cast<RecordDecl>((ReplacementField)->getDeclContext())
1401 ->isAnonymousStructOrUnion()) {
1402 // Handle an field designator that refers to a member of an
1403 // anonymous struct or union.
1404 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1405 ReplacementField,
1406 Field, FieldIndex);
1407 D = DIE->getDesignator(DesigIdx);
1408 } else if (!KnownField) {
1409 // The replacement field comes from typo correction; find it
1410 // in the list of fields.
1411 FieldIndex = 0;
1412 Field = RT->getDecl()->field_begin();
1413 for (; Field != FieldEnd; ++Field) {
1414 if (Field->isUnnamedBitfield())
1415 continue;
1416
1417 if (ReplacementField == *Field ||
1418 Field->getIdentifier() == ReplacementField->getIdentifier())
1419 break;
1420
1421 ++FieldIndex;
1422 }
1423 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001424 } else if (!KnownField &&
1425 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001426 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001427 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1428 Field, FieldIndex);
1429 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001430 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001431
1432 // All of the fields of a union are located at the same place in
1433 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001434 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001435 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001436 StructuredList->setInitializedFieldInUnion(*Field);
1437 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001438
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001439 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001440 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Douglas Gregor4c678342009-01-28 21:54:33 +00001442 // Make sure that our non-designated initializer list has space
1443 // for a subobject corresponding to this field.
1444 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001445 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001446
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001447 // This designator names a flexible array member.
1448 if (Field->getType()->isIncompleteArrayType()) {
1449 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001450 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001451 // We can't designate an object within the flexible array
1452 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001453 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001454 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001455 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001456 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001457 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001458 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001459 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001460 << *Field;
1461 Invalid = true;
1462 }
1463
1464 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1465 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001466 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001467 diag::err_flexible_array_init_needs_braces)
1468 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001469 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001470 << *Field;
1471 Invalid = true;
1472 }
1473
1474 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001475 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001476 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001478 diag::err_flexible_array_init_nonempty)
1479 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001480 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001481 << *Field;
1482 Invalid = true;
1483 }
1484
1485 if (Invalid) {
1486 ++Index;
1487 return true;
1488 }
1489
1490 // Initialize the array.
1491 bool prevHadError = hadError;
1492 unsigned newStructuredIndex = FieldIndex;
1493 unsigned OldIndex = Index;
1494 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001495
1496 InitializedEntity MemberEntity =
1497 InitializedEntity::InitializeMember(*Field, &Entity);
1498 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001499 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001500
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001501 IList->setInit(OldIndex, DIE);
1502 if (hadError && !prevHadError) {
1503 ++Field;
1504 ++FieldIndex;
1505 if (NextField)
1506 *NextField = Field;
1507 StructuredIndex = FieldIndex;
1508 return true;
1509 }
1510 } else {
1511 // Recurse to check later designated subobjects.
1512 QualType FieldType = (*Field)->getType();
1513 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001514
1515 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001516 InitializedEntity::InitializeMember(*Field, &Entity);
1517 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001518 FieldType, 0, 0, Index,
1519 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001520 true, false))
1521 return true;
1522 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001523
1524 // Find the position of the next field to be initialized in this
1525 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001526 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001527 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001528
1529 // If this the first designator, our caller will continue checking
1530 // the rest of this struct/class/union subobject.
1531 if (IsFirstDesignator) {
1532 if (NextField)
1533 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001534 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001535 return false;
1536 }
1537
Douglas Gregor34e79462009-01-28 23:36:17 +00001538 if (!FinishSubobjectInit)
1539 return false;
1540
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001541 // We've already initialized something in the union; we're done.
1542 if (RT->getDecl()->isUnion())
1543 return hadError;
1544
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001545 // Check the remaining fields within this class/struct/union subobject.
1546 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001547
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001548 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001549 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001550 return hadError && !prevHadError;
1551 }
1552
1553 // C99 6.7.8p6:
1554 //
1555 // If a designator has the form
1556 //
1557 // [ constant-expression ]
1558 //
1559 // then the current object (defined below) shall have array
1560 // type and the expression shall be an integer constant
1561 // expression. If the array is of unknown size, any
1562 // nonnegative value is valid.
1563 //
1564 // Additionally, cope with the GNU extension that permits
1565 // designators of the form
1566 //
1567 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001568 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001569 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001570 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571 << CurrentObjectType;
1572 ++Index;
1573 return true;
1574 }
1575
1576 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001577 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1578 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001579 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001580 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001581 DesignatedEndIndex = DesignatedStartIndex;
1582 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001583 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001584
Mike Stump1eb44332009-09-09 15:08:12 +00001585
1586 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001587 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001588 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001589 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001590 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001591
Chris Lattner3bf68932009-04-25 21:59:05 +00001592 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001593 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001594 }
1595
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001596 if (isa<ConstantArrayType>(AT)) {
1597 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001598 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1599 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1600 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1601 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1602 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001603 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001604 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001605 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001606 << IndexExpr->getSourceRange();
1607 ++Index;
1608 return true;
1609 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001610 } else {
1611 // Make sure the bit-widths and signedness match.
1612 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1613 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001614 else if (DesignatedStartIndex.getBitWidth() <
1615 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001616 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1617 DesignatedStartIndex.setIsUnsigned(true);
1618 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Douglas Gregor4c678342009-01-28 21:54:33 +00001621 // Make sure that our non-designated initializer list has space
1622 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001623 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001624 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001625 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001626
Douglas Gregor34e79462009-01-28 23:36:17 +00001627 // Repeatedly perform subobject initializations in the range
1628 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001629
Douglas Gregor34e79462009-01-28 23:36:17 +00001630 // Move to the next designator
1631 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1632 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001633
1634 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001635 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001636
Douglas Gregor34e79462009-01-28 23:36:17 +00001637 while (DesignatedStartIndex <= DesignatedEndIndex) {
1638 // Recurse to check later designated subobjects.
1639 QualType ElementType = AT->getElementType();
1640 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001641
1642 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001643 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001644 ElementType, 0, 0, Index,
1645 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001646 (DesignatedStartIndex == DesignatedEndIndex),
1647 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001648 return true;
1649
1650 // Move to the next index in the array that we'll be initializing.
1651 ++DesignatedStartIndex;
1652 ElementIndex = DesignatedStartIndex.getZExtValue();
1653 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001654
1655 // If this the first designator, our caller will continue checking
1656 // the rest of this array subobject.
1657 if (IsFirstDesignator) {
1658 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001659 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001660 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001661 return false;
1662 }
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Douglas Gregor34e79462009-01-28 23:36:17 +00001664 if (!FinishSubobjectInit)
1665 return false;
1666
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001667 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001668 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001669 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001670 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001671 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001672 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001673}
1674
Douglas Gregor4c678342009-01-28 21:54:33 +00001675// Get the structured initializer list for a subobject of type
1676// @p CurrentObjectType.
1677InitListExpr *
1678InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1679 QualType CurrentObjectType,
1680 InitListExpr *StructuredList,
1681 unsigned StructuredIndex,
1682 SourceRange InitRange) {
1683 Expr *ExistingInit = 0;
1684 if (!StructuredList)
1685 ExistingInit = SyntacticToSemantic[IList];
1686 else if (StructuredIndex < StructuredList->getNumInits())
1687 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Douglas Gregor4c678342009-01-28 21:54:33 +00001689 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1690 return Result;
1691
1692 if (ExistingInit) {
1693 // We are creating an initializer list that initializes the
1694 // subobjects of the current object, but there was already an
1695 // initialization that completely initialized the current
1696 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001697 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001698 // struct X { int a, b; };
1699 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001700 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001701 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1702 // designated initializer re-initializes the whole
1703 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001704 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001705 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001706 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001707 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001708 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001709 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001710 << ExistingInit->getSourceRange();
1711 }
1712
Mike Stump1eb44332009-09-09 15:08:12 +00001713 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001714 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1715 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001716 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001717
Douglas Gregor63982352010-07-13 18:40:04 +00001718 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001719
Douglas Gregorfa219202009-03-20 23:58:33 +00001720 // Pre-allocate storage for the structured initializer list.
1721 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001722 unsigned NumInits = 0;
1723 if (!StructuredList)
1724 NumInits = IList->getNumInits();
1725 else if (Index < IList->getNumInits()) {
1726 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1727 NumInits = SubList->getNumInits();
1728 }
1729
Mike Stump1eb44332009-09-09 15:08:12 +00001730 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001731 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1732 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1733 NumElements = CAType->getSize().getZExtValue();
1734 // Simple heuristic so that we don't allocate a very large
1735 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001736 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001737 NumElements = 0;
1738 }
John McCall183700f2009-09-21 23:43:11 +00001739 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001740 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001741 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001742 RecordDecl *RDecl = RType->getDecl();
1743 if (RDecl->isUnion())
1744 NumElements = 1;
1745 else
Mike Stump1eb44332009-09-09 15:08:12 +00001746 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001747 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001748 }
1749
Douglas Gregor08457732009-03-21 18:13:52 +00001750 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001751 NumElements = IList->getNumInits();
1752
Ted Kremenek709210f2010-04-13 23:39:13 +00001753 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001754
Douglas Gregor4c678342009-01-28 21:54:33 +00001755 // Link this new initializer list into the structured initializer
1756 // lists.
1757 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001758 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001759 else {
1760 Result->setSyntacticForm(IList);
1761 SyntacticToSemantic[IList] = Result;
1762 }
1763
1764 return Result;
1765}
1766
1767/// Update the initializer at index @p StructuredIndex within the
1768/// structured initializer list to the value @p expr.
1769void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1770 unsigned &StructuredIndex,
1771 Expr *expr) {
1772 // No structured initializer list to update
1773 if (!StructuredList)
1774 return;
1775
Ted Kremenek709210f2010-04-13 23:39:13 +00001776 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1777 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001778 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001779 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001780 diag::warn_initializer_overrides)
1781 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001782 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001783 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001784 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001785 << PrevInit->getSourceRange();
1786 }
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Douglas Gregor4c678342009-01-28 21:54:33 +00001788 ++StructuredIndex;
1789}
1790
Douglas Gregor05c13a32009-01-22 00:58:24 +00001791/// Check that the given Index expression is a valid array designator
1792/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001793/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001794/// and produces a reasonable diagnostic if there is a
1795/// failure. Returns true if there was an error, false otherwise. If
1796/// everything went okay, Value will receive the value of the constant
1797/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001798static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001799CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001800 SourceLocation Loc = Index->getSourceRange().getBegin();
1801
1802 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001803 if (S.VerifyIntegerConstantExpression(Index, &Value))
1804 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001805
Chris Lattner3bf68932009-04-25 21:59:05 +00001806 if (Value.isSigned() && Value.isNegative())
1807 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001808 << Value.toString(10) << Index->getSourceRange();
1809
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001810 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001811 return false;
1812}
1813
John McCall60d7b3a2010-08-24 06:29:42 +00001814ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001815 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001816 bool GNUSyntax,
John McCall60d7b3a2010-08-24 06:29:42 +00001817 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001818 typedef DesignatedInitExpr::Designator ASTDesignator;
1819
1820 bool Invalid = false;
1821 llvm::SmallVector<ASTDesignator, 32> Designators;
1822 llvm::SmallVector<Expr *, 32> InitExpressions;
1823
1824 // Build designators and check array designator expressions.
1825 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1826 const Designator &D = Desig.getDesignator(Idx);
1827 switch (D.getKind()) {
1828 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001829 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001830 D.getFieldLoc()));
1831 break;
1832
1833 case Designator::ArrayDesignator: {
1834 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1835 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001836 if (!Index->isTypeDependent() &&
1837 !Index->isValueDependent() &&
1838 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001839 Invalid = true;
1840 else {
1841 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001842 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001843 D.getRBracketLoc()));
1844 InitExpressions.push_back(Index);
1845 }
1846 break;
1847 }
1848
1849 case Designator::ArrayRangeDesignator: {
1850 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1851 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1852 llvm::APSInt StartValue;
1853 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001854 bool StartDependent = StartIndex->isTypeDependent() ||
1855 StartIndex->isValueDependent();
1856 bool EndDependent = EndIndex->isTypeDependent() ||
1857 EndIndex->isValueDependent();
1858 if ((!StartDependent &&
1859 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1860 (!EndDependent &&
1861 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001862 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001863 else {
1864 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001865 if (StartDependent || EndDependent) {
1866 // Nothing to compute.
1867 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001868 EndValue.extend(StartValue.getBitWidth());
1869 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1870 StartValue.extend(EndValue.getBitWidth());
1871
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001872 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001873 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001874 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001875 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1876 Invalid = true;
1877 } else {
1878 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001879 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001880 D.getEllipsisLoc(),
1881 D.getRBracketLoc()));
1882 InitExpressions.push_back(StartIndex);
1883 InitExpressions.push_back(EndIndex);
1884 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001885 }
1886 break;
1887 }
1888 }
1889 }
1890
1891 if (Invalid || Init.isInvalid())
1892 return ExprError();
1893
1894 // Clear out the expressions within the designation.
1895 Desig.ClearExprs(*this);
1896
1897 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001898 = DesignatedInitExpr::Create(Context,
1899 Designators.data(), Designators.size(),
1900 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001901 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001902 return Owned(DIE);
1903}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001904
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001905bool Sema::CheckInitList(const InitializedEntity &Entity,
1906 InitListExpr *&InitList, QualType &DeclType) {
1907 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001908 if (!CheckInitList.HadError())
1909 InitList = CheckInitList.getFullyStructuredList();
1910
1911 return CheckInitList.HadError();
1912}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001913
Douglas Gregor20093b42009-12-09 23:02:17 +00001914//===----------------------------------------------------------------------===//
1915// Initialization entity
1916//===----------------------------------------------------------------------===//
1917
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001918InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1919 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001920 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001921{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001922 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1923 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001924 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001925 } else {
1926 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001927 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001928 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001929}
1930
1931InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001932 CXXBaseSpecifier *Base,
1933 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001934{
1935 InitializedEntity Result;
1936 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001937 Result.Base = reinterpret_cast<uintptr_t>(Base);
1938 if (IsInheritedVirtualBase)
1939 Result.Base |= 0x01;
1940
Douglas Gregord6542d82009-12-22 15:35:07 +00001941 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001942 return Result;
1943}
1944
Douglas Gregor99a2e602009-12-16 01:38:02 +00001945DeclarationName InitializedEntity::getName() const {
1946 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001947 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001948 if (!VariableOrMember)
1949 return DeclarationName();
1950 // Fall through
1951
1952 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001953 case EK_Member:
1954 return VariableOrMember->getDeclName();
1955
1956 case EK_Result:
1957 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001958 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001959 case EK_Temporary:
1960 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001961 case EK_ArrayElement:
1962 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001963 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001964 return DeclarationName();
1965 }
1966
1967 // Silence GCC warning
1968 return DeclarationName();
1969}
1970
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001971DeclaratorDecl *InitializedEntity::getDecl() const {
1972 switch (getKind()) {
1973 case EK_Variable:
1974 case EK_Parameter:
1975 case EK_Member:
1976 return VariableOrMember;
1977
1978 case EK_Result:
1979 case EK_Exception:
1980 case EK_New:
1981 case EK_Temporary:
1982 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001983 case EK_ArrayElement:
1984 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001985 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001986 return 0;
1987 }
1988
1989 // Silence GCC warning
1990 return 0;
1991}
1992
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001993bool InitializedEntity::allowsNRVO() const {
1994 switch (getKind()) {
1995 case EK_Result:
1996 case EK_Exception:
1997 return LocAndNRVO.NRVO;
1998
1999 case EK_Variable:
2000 case EK_Parameter:
2001 case EK_Member:
2002 case EK_New:
2003 case EK_Temporary:
2004 case EK_Base:
2005 case EK_ArrayElement:
2006 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002007 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002008 break;
2009 }
2010
2011 return false;
2012}
2013
Douglas Gregor20093b42009-12-09 23:02:17 +00002014//===----------------------------------------------------------------------===//
2015// Initialization sequence
2016//===----------------------------------------------------------------------===//
2017
2018void InitializationSequence::Step::Destroy() {
2019 switch (Kind) {
2020 case SK_ResolveAddressOfOverloadedFunction:
2021 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002022 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002023 case SK_CastDerivedToBaseLValue:
2024 case SK_BindReference:
2025 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002026 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002027 case SK_UserConversion:
2028 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002029 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002030 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002031 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002032 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002033 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002034 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002035 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002036 case SK_ObjCObjectConversion:
Douglas Gregor20093b42009-12-09 23:02:17 +00002037 break;
2038
2039 case SK_ConversionSequence:
2040 delete ICS;
2041 }
2042}
2043
Douglas Gregorb70cf442010-03-26 20:14:36 +00002044bool InitializationSequence::isDirectReferenceBinding() const {
2045 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2046}
2047
2048bool InitializationSequence::isAmbiguous() const {
2049 if (getKind() != FailedSequence)
2050 return false;
2051
2052 switch (getFailureKind()) {
2053 case FK_TooManyInitsForReference:
2054 case FK_ArrayNeedsInitList:
2055 case FK_ArrayNeedsInitListOrStringLiteral:
2056 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2057 case FK_NonConstLValueReferenceBindingToTemporary:
2058 case FK_NonConstLValueReferenceBindingToUnrelated:
2059 case FK_RValueReferenceBindingToLValue:
2060 case FK_ReferenceInitDropsQualifiers:
2061 case FK_ReferenceInitFailed:
2062 case FK_ConversionFailed:
2063 case FK_TooManyInitsForScalar:
2064 case FK_ReferenceBindingToInitList:
2065 case FK_InitListBadDestinationType:
2066 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002067 case FK_Incomplete:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002068 return false;
2069
2070 case FK_ReferenceInitOverloadFailed:
2071 case FK_UserConversionOverloadFailed:
2072 case FK_ConstructorOverloadFailed:
2073 return FailedOverloadResult == OR_Ambiguous;
2074 }
2075
2076 return false;
2077}
2078
Douglas Gregord6e44a32010-04-16 22:09:46 +00002079bool InitializationSequence::isConstructorInitialization() const {
2080 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2081}
2082
Douglas Gregor20093b42009-12-09 23:02:17 +00002083void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002084 FunctionDecl *Function,
2085 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002086 Step S;
2087 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2088 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002089 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002090 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002091 Steps.push_back(S);
2092}
2093
2094void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002095 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002096 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002097 switch (VK) {
2098 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2099 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2100 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002101 default: llvm_unreachable("No such category");
2102 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002103 S.Type = BaseType;
2104 Steps.push_back(S);
2105}
2106
2107void InitializationSequence::AddReferenceBindingStep(QualType T,
2108 bool BindingTemporary) {
2109 Step S;
2110 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2111 S.Type = T;
2112 Steps.push_back(S);
2113}
2114
Douglas Gregor523d46a2010-04-18 07:40:54 +00002115void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2116 Step S;
2117 S.Kind = SK_ExtraneousCopyToTemporary;
2118 S.Type = T;
2119 Steps.push_back(S);
2120}
2121
Eli Friedman03981012009-12-11 02:42:07 +00002122void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002123 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002124 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002125 Step S;
2126 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002127 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002128 S.Function.Function = Function;
2129 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002130 Steps.push_back(S);
2131}
2132
2133void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002134 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002135 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002136 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002137 switch (VK) {
2138 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002139 S.Kind = SK_QualificationConversionRValue;
2140 break;
John McCall5baba9d2010-08-25 10:28:54 +00002141 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002142 S.Kind = SK_QualificationConversionXValue;
2143 break;
John McCall5baba9d2010-08-25 10:28:54 +00002144 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002145 S.Kind = SK_QualificationConversionLValue;
2146 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002147 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002148 S.Type = Ty;
2149 Steps.push_back(S);
2150}
2151
2152void InitializationSequence::AddConversionSequenceStep(
2153 const ImplicitConversionSequence &ICS,
2154 QualType T) {
2155 Step S;
2156 S.Kind = SK_ConversionSequence;
2157 S.Type = T;
2158 S.ICS = new ImplicitConversionSequence(ICS);
2159 Steps.push_back(S);
2160}
2161
Douglas Gregord87b61f2009-12-10 17:56:55 +00002162void InitializationSequence::AddListInitializationStep(QualType T) {
2163 Step S;
2164 S.Kind = SK_ListInitialization;
2165 S.Type = T;
2166 Steps.push_back(S);
2167}
2168
Douglas Gregor51c56d62009-12-14 20:49:26 +00002169void
2170InitializationSequence::AddConstructorInitializationStep(
2171 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002172 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002173 QualType T) {
2174 Step S;
2175 S.Kind = SK_ConstructorInitialization;
2176 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002177 S.Function.Function = Constructor;
2178 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002179 Steps.push_back(S);
2180}
2181
Douglas Gregor71d17402009-12-15 00:01:57 +00002182void InitializationSequence::AddZeroInitializationStep(QualType T) {
2183 Step S;
2184 S.Kind = SK_ZeroInitialization;
2185 S.Type = T;
2186 Steps.push_back(S);
2187}
2188
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002189void InitializationSequence::AddCAssignmentStep(QualType T) {
2190 Step S;
2191 S.Kind = SK_CAssignment;
2192 S.Type = T;
2193 Steps.push_back(S);
2194}
2195
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002196void InitializationSequence::AddStringInitStep(QualType T) {
2197 Step S;
2198 S.Kind = SK_StringInit;
2199 S.Type = T;
2200 Steps.push_back(S);
2201}
2202
Douglas Gregor569c3162010-08-07 11:51:51 +00002203void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2204 Step S;
2205 S.Kind = SK_ObjCObjectConversion;
2206 S.Type = T;
2207 Steps.push_back(S);
2208}
2209
Douglas Gregor20093b42009-12-09 23:02:17 +00002210void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2211 OverloadingResult Result) {
2212 SequenceKind = FailedSequence;
2213 this->Failure = Failure;
2214 this->FailedOverloadResult = Result;
2215}
2216
2217//===----------------------------------------------------------------------===//
2218// Attempt initialization
2219//===----------------------------------------------------------------------===//
2220
2221/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002222static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002223 const InitializedEntity &Entity,
2224 const InitializationKind &Kind,
2225 InitListExpr *InitList,
2226 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002227 // FIXME: We only perform rudimentary checking of list
2228 // initializations at this point, then assume that any list
2229 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002230 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002231 // do all of the necessary checking. C++0x initializer lists will
2232 // force us to perform more checking here.
2233 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2234
Douglas Gregord6542d82009-12-22 15:35:07 +00002235 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002236
2237 // C++ [dcl.init]p13:
2238 // If T is a scalar type, then a declaration of the form
2239 //
2240 // T x = { a };
2241 //
2242 // is equivalent to
2243 //
2244 // T x = a;
2245 if (DestType->isScalarType()) {
2246 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2247 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2248 return;
2249 }
2250
2251 // Assume scalar initialization from a single value works.
2252 } else if (DestType->isAggregateType()) {
2253 // Assume aggregate initialization works.
2254 } else if (DestType->isVectorType()) {
2255 // Assume vector initialization works.
2256 } else if (DestType->isReferenceType()) {
2257 // FIXME: C++0x defines behavior for this.
2258 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2259 return;
2260 } else if (DestType->isRecordType()) {
2261 // FIXME: C++0x defines behavior for this
2262 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2263 }
2264
2265 // Add a general "list initialization" step.
2266 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002267}
2268
2269/// \brief Try a reference initialization that involves calling a conversion
2270/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002271static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2272 const InitializedEntity &Entity,
2273 const InitializationKind &Kind,
2274 Expr *Initializer,
2275 bool AllowRValues,
2276 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002277 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002278 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2279 QualType T1 = cv1T1.getUnqualifiedType();
2280 QualType cv2T2 = Initializer->getType();
2281 QualType T2 = cv2T2.getUnqualifiedType();
2282
2283 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002284 bool ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002285 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002286 T1, T2, DerivedToBase,
2287 ObjCConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002288 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002289 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002290 (void)ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002291
2292 // Build the candidate set directly in the initialization sequence
2293 // structure, so that it will persist if we fail.
2294 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2295 CandidateSet.clear();
2296
2297 // Determine whether we are allowed to call explicit constructors or
2298 // explicit conversion operators.
2299 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2300
2301 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002302 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2303 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002304 // The type we're converting to is a class type. Enumerate its constructors
2305 // to see if there is a suitable conversion.
2306 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002307
Douglas Gregor20093b42009-12-09 23:02:17 +00002308 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002309 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002310 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002311 NamedDecl *D = *Con;
2312 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2313
Douglas Gregor20093b42009-12-09 23:02:17 +00002314 // Find the constructor (which may be a template).
2315 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002316 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002317 if (ConstructorTmpl)
2318 Constructor = cast<CXXConstructorDecl>(
2319 ConstructorTmpl->getTemplatedDecl());
2320 else
John McCall9aa472c2010-03-19 07:35:19 +00002321 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002322
2323 if (!Constructor->isInvalidDecl() &&
2324 Constructor->isConvertingConstructor(AllowExplicit)) {
2325 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002326 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002327 /*ExplicitArgs*/ 0,
Douglas Gregor20093b42009-12-09 23:02:17 +00002328 &Initializer, 1, CandidateSet);
2329 else
John McCall9aa472c2010-03-19 07:35:19 +00002330 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002331 &Initializer, 1, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002332 }
2333 }
2334 }
John McCall572fc622010-08-17 07:23:57 +00002335 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2336 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002337
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002338 const RecordType *T2RecordType = 0;
2339 if ((T2RecordType = T2->getAs<RecordType>()) &&
2340 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002341 // The type we're converting from is a class type, enumerate its conversion
2342 // functions.
2343 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2344
2345 // Determine the type we are converting to. If we are allowed to
2346 // convert to an rvalue, take the type that the destination type
2347 // refers to.
2348 QualType ToType = AllowRValues? cv1T1 : DestType;
2349
John McCalleec51cf2010-01-20 00:46:10 +00002350 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002351 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002352 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2353 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002354 NamedDecl *D = *I;
2355 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2356 if (isa<UsingShadowDecl>(D))
2357 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2358
2359 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2360 CXXConversionDecl *Conv;
2361 if (ConvTemplate)
2362 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2363 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002364 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002365
2366 // If the conversion function doesn't return a reference type,
2367 // it can't be considered for this conversion unless we're allowed to
2368 // consider rvalues.
2369 // FIXME: Do we need to make sure that we only consider conversion
2370 // candidates with reference-compatible results? That might be needed to
2371 // break recursion.
2372 if ((AllowExplicit || !Conv->isExplicit()) &&
2373 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2374 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002375 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002376 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002377 ToType, CandidateSet);
2378 else
John McCall9aa472c2010-03-19 07:35:19 +00002379 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002380 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002381 }
2382 }
2383 }
John McCall572fc622010-08-17 07:23:57 +00002384 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2385 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002386
2387 SourceLocation DeclLoc = Initializer->getLocStart();
2388
2389 // Perform overload resolution. If it fails, return the failed result.
2390 OverloadCandidateSet::iterator Best;
2391 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002392 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor20093b42009-12-09 23:02:17 +00002393 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002394
Douglas Gregor20093b42009-12-09 23:02:17 +00002395 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002396
2397 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002398 if (isa<CXXConversionDecl>(Function))
2399 T2 = Function->getResultType();
2400 else
2401 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002402
2403 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002404 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002405 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002406
2407 // Determine whether we need to perform derived-to-base or
2408 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002409 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002410 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002411 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002412 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002413 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002414
Douglas Gregor20093b42009-12-09 23:02:17 +00002415 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002416 bool NewObjCConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002417 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregor63982352010-07-13 18:40:04 +00002418 = S.CompareReferenceRelationship(DeclLoc, T1,
2419 T2.getNonLValueExprType(S.Context),
Douglas Gregor569c3162010-08-07 11:51:51 +00002420 NewDerivedToBase, NewObjCConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002421 if (NewRefRelationship == Sema::Ref_Incompatible) {
2422 // If the type we've converted to is not reference-related to the
2423 // type we're looking for, then there is another conversion step
2424 // we need to perform to produce a temporary of the right type
2425 // that we'll be binding to.
2426 ImplicitConversionSequence ICS;
2427 ICS.setStandard();
2428 ICS.Standard = Best->FinalConversion;
2429 T2 = ICS.Standard.getToType(2);
2430 Sequence.AddConversionSequenceStep(ICS, T2);
2431 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002432 Sequence.AddDerivedToBaseCastStep(
2433 S.Context.getQualifiedType(T1,
2434 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002435 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002436 else if (NewObjCConversion)
2437 Sequence.AddObjCObjectConversionStep(
2438 S.Context.getQualifiedType(T1,
2439 T2.getNonReferenceType().getQualifiers()));
2440
Douglas Gregor20093b42009-12-09 23:02:17 +00002441 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002442 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00002443
2444 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2445 return OR_Success;
2446}
2447
Sebastian Redl4680bf22010-06-30 18:13:39 +00002448/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor20093b42009-12-09 23:02:17 +00002449static void TryReferenceInitialization(Sema &S,
2450 const InitializedEntity &Entity,
2451 const InitializationKind &Kind,
2452 Expr *Initializer,
2453 InitializationSequence &Sequence) {
2454 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002455
Douglas Gregord6542d82009-12-22 15:35:07 +00002456 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002457 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002458 Qualifiers T1Quals;
2459 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002460 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002461 Qualifiers T2Quals;
2462 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002463 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002464
Douglas Gregor20093b42009-12-09 23:02:17 +00002465 // If the initializer is the address of an overloaded function, try
2466 // to resolve the overloaded function. If all goes well, T2 is the
2467 // type of the resulting function.
2468 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002469 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002470 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2471 T1,
John McCall6bb80172010-03-30 21:47:33 +00002472 false,
2473 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002474 if (!Fn) {
2475 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2476 return;
2477 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002478
John McCall6bb80172010-03-30 21:47:33 +00002479 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00002480 cv2T2 = Fn->getType();
2481 T2 = cv2T2.getUnqualifiedType();
2482 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002483
Douglas Gregor20093b42009-12-09 23:02:17 +00002484 // Compute some basic properties of the types and the initializer.
2485 bool isLValueRef = DestType->isLValueReferenceType();
2486 bool isRValueRef = !isLValueRef;
2487 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002488 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002489 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002490 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002491 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2492 ObjCConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002493
Douglas Gregor20093b42009-12-09 23:02:17 +00002494 // C++0x [dcl.init.ref]p5:
2495 // A reference to type "cv1 T1" is initialized by an expression of type
2496 // "cv2 T2" as follows:
2497 //
2498 // - If the reference is an lvalue reference and the initializer
2499 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002500 // Note the analogous bullet points for rvlaue refs to functions. Because
2501 // there are no function rvalues in C++, rvalue refs to functions are treated
2502 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002503 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002504 bool T1Function = T1->isFunctionType();
2505 if (isLValueRef || T1Function) {
2506 if (InitCategory.isLValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002507 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2508 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2509 // reference-compatible with "cv2 T2," or
2510 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002511 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002512 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002513 // can occur. However, we do pay attention to whether it is a bit-field
2514 // to decide whether we're actually binding to a temporary created from
2515 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002516 if (DerivedToBase)
2517 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002518 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002519 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002520 else if (ObjCConversion)
2521 Sequence.AddObjCObjectConversionStep(
2522 S.Context.getQualifiedType(T1, T2Quals));
2523
Chandler Carruth5535c382010-01-12 20:32:25 +00002524 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002525 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002526 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002527 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002528 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002529 return;
2530 }
2531
2532 // - has a class type (i.e., T2 is a class type), where T1 is not
2533 // reference-related to T2, and can be implicitly converted to an
2534 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2535 // with "cv3 T3" (this conversion is selected by enumerating the
2536 // applicable conversion functions (13.3.1.6) and choosing the best
2537 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002538 // If we have an rvalue ref to function type here, the rhs must be
2539 // an rvalue.
2540 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2541 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002542 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2543 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002544 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002545 Sequence);
2546 if (ConvOvlResult == OR_Success)
2547 return;
John McCall1d318332010-01-12 00:44:57 +00002548 if (ConvOvlResult != OR_No_Viable_Function) {
2549 Sequence.SetOverloadFailure(
2550 InitializationSequence::FK_ReferenceInitOverloadFailed,
2551 ConvOvlResult);
2552 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002553 }
2554 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002555
Douglas Gregor20093b42009-12-09 23:02:17 +00002556 // - Otherwise, the reference shall be an lvalue reference to a
2557 // non-volatile const type (i.e., cv1 shall be const), or the reference
2558 // shall be an rvalue reference and the initializer expression shall
Sebastian Redl4680bf22010-06-30 18:13:39 +00002559 // be an rvalue or have a function type.
2560 // We handled the function type stuff above.
Douglas Gregoref06e242010-01-29 19:39:15 +00002561 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redl4680bf22010-06-30 18:13:39 +00002562 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002563 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2564 Sequence.SetOverloadFailure(
2565 InitializationSequence::FK_ReferenceInitOverloadFailed,
2566 ConvOvlResult);
2567 else if (isLValueRef)
Sebastian Redl4680bf22010-06-30 18:13:39 +00002568 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002569 ? (RefRelationship == Sema::Ref_Related
2570 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2571 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2572 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2573 else
2574 Sequence.SetFailed(
2575 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002576
Douglas Gregor20093b42009-12-09 23:02:17 +00002577 return;
2578 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002579
2580 // - [If T1 is not a function type], if T2 is a class type and
2581 if (!T1Function && T2->isRecordType()) {
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002582 bool isXValue = InitCategory.isXValue();
Douglas Gregor20093b42009-12-09 23:02:17 +00002583 // - the initializer expression is an rvalue and "cv1 T1" is
2584 // reference-compatible with "cv2 T2", or
Sebastian Redl4680bf22010-06-30 18:13:39 +00002585 if (InitCategory.isRValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002586 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002587 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2588 // compiler the freedom to perform a copy here or bind to the
2589 // object, while C++0x requires that we bind directly to the
2590 // object. Hence, we always bind to the object without making an
2591 // extra copy. However, in C++03 requires that we check for the
2592 // presence of a suitable copy constructor:
2593 //
2594 // The constructor that would be used to make the copy shall
2595 // be callable whether or not the copy is actually done.
2596 if (!S.getLangOptions().CPlusPlus0x)
2597 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2598
Douglas Gregor20093b42009-12-09 23:02:17 +00002599 if (DerivedToBase)
2600 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002601 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002602 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002603 else if (ObjCConversion)
2604 Sequence.AddObjCObjectConversionStep(
2605 S.Context.getQualifiedType(T1, T2Quals));
2606
Chandler Carruth5535c382010-01-12 20:32:25 +00002607 if (T1Quals != T2Quals)
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002608 Sequence.AddQualificationConversionStep(cv1T1,
John McCall5baba9d2010-08-25 10:28:54 +00002609 isXValue ? VK_XValue : VK_RValue);
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002610 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00002611 return;
2612 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002613
Douglas Gregor20093b42009-12-09 23:02:17 +00002614 // - T1 is not reference-related to T2 and the initializer expression
2615 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2616 // conversion is selected by enumerating the applicable conversion
2617 // functions (13.3.1.6) and choosing the best one through overload
2618 // resolution (13.3)),
2619 if (RefRelationship == Sema::Ref_Incompatible) {
2620 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2621 Kind, Initializer,
2622 /*AllowRValues=*/true,
2623 Sequence);
2624 if (ConvOvlResult)
2625 Sequence.SetOverloadFailure(
2626 InitializationSequence::FK_ReferenceInitOverloadFailed,
2627 ConvOvlResult);
2628
2629 return;
2630 }
2631
2632 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2633 return;
2634 }
2635
2636 // - If the initializer expression is an rvalue, with T2 an array type,
2637 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2638 // is bound to the object represented by the rvalue (see 3.10).
2639 // FIXME: How can an array type be reference-compatible with anything?
2640 // Don't we mean the element types of T1 and T2?
2641
2642 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2643 // from the initializer expression using the rules for a non-reference
2644 // copy initialization (8.5). The reference is then bound to the
2645 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002646
Douglas Gregor20093b42009-12-09 23:02:17 +00002647 // Determine whether we are allowed to call explicit constructors or
2648 // explicit conversion operators.
2649 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002650
2651 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2652
2653 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2654 /*SuppressUserConversions*/ false,
2655 AllowExplicit,
2656 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002657 // FIXME: Use the conversion function set stored in ICS to turn
2658 // this into an overloading ambiguity diagnostic. However, we need
2659 // to keep that set as an OverloadCandidateSet rather than as some
2660 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002661 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2662 Sequence.SetOverloadFailure(
2663 InitializationSequence::FK_ReferenceInitOverloadFailed,
2664 ConvOvlResult);
2665 else
2666 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002667 return;
2668 }
2669
2670 // [...] If T1 is reference-related to T2, cv1 must be the
2671 // same cv-qualification as, or greater cv-qualification
2672 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002673 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2674 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002675 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002676 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002677 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2678 return;
2679 }
2680
Douglas Gregor20093b42009-12-09 23:02:17 +00002681 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2682 return;
2683}
2684
2685/// \brief Attempt character array initialization from a string literal
2686/// (C++ [dcl.init.string], C99 6.7.8).
2687static void TryStringLiteralInitialization(Sema &S,
2688 const InitializedEntity &Entity,
2689 const InitializationKind &Kind,
2690 Expr *Initializer,
2691 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002692 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002693 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002694}
2695
Douglas Gregor20093b42009-12-09 23:02:17 +00002696/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2697/// enumerates the constructors of the initialized entity and performs overload
2698/// resolution to select the best.
2699static void TryConstructorInitialization(Sema &S,
2700 const InitializedEntity &Entity,
2701 const InitializationKind &Kind,
2702 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002703 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002704 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002705 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002706
2707 // Build the candidate set directly in the initialization sequence
2708 // structure, so that it will persist if we fail.
2709 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2710 CandidateSet.clear();
2711
2712 // Determine whether we are allowed to call explicit constructors or
2713 // explicit conversion operators.
2714 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2715 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002716 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002717
2718 // The type we're constructing needs to be complete.
2719 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002720 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002721 return;
2722 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002723
2724 // The type we're converting to is a class type. Enumerate its constructors
2725 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002726 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2727 assert(DestRecordType && "Constructor initialization requires record type");
2728 CXXRecordDecl *DestRecordDecl
2729 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2730
Douglas Gregor51c56d62009-12-14 20:49:26 +00002731 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002732 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002733 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002734 NamedDecl *D = *Con;
2735 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002736 bool SuppressUserConversions = false;
2737
Douglas Gregor51c56d62009-12-14 20:49:26 +00002738 // Find the constructor (which may be a template).
2739 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002740 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002741 if (ConstructorTmpl)
2742 Constructor = cast<CXXConstructorDecl>(
2743 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002744 else {
John McCall9aa472c2010-03-19 07:35:19 +00002745 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002746
2747 // If we're performing copy initialization using a copy constructor, we
2748 // suppress user-defined conversions on the arguments.
2749 // FIXME: Move constructors?
2750 if (Kind.getKind() == InitializationKind::IK_Copy &&
2751 Constructor->isCopyConstructor())
2752 SuppressUserConversions = true;
2753 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002754
2755 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002756 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002757 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002758 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002759 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002760 Args, NumArgs, CandidateSet,
2761 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002762 else
John McCall9aa472c2010-03-19 07:35:19 +00002763 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002764 Args, NumArgs, CandidateSet,
2765 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002766 }
2767 }
2768
2769 SourceLocation DeclLoc = Kind.getLocation();
2770
2771 // Perform overload resolution. If it fails, return the failed result.
2772 OverloadCandidateSet::iterator Best;
2773 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002774 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002775 Sequence.SetOverloadFailure(
2776 InitializationSequence::FK_ConstructorOverloadFailed,
2777 Result);
2778 return;
2779 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002780
2781 // C++0x [dcl.init]p6:
2782 // If a program calls for the default initialization of an object
2783 // of a const-qualified type T, T shall be a class type with a
2784 // user-provided default constructor.
2785 if (Kind.getKind() == InitializationKind::IK_Default &&
2786 Entity.getType().isConstQualified() &&
2787 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2788 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2789 return;
2790 }
2791
Douglas Gregor51c56d62009-12-14 20:49:26 +00002792 // Add the constructor initialization step. Any cv-qualification conversion is
2793 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002794 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002795 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002796 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002797 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002798}
2799
Douglas Gregor71d17402009-12-15 00:01:57 +00002800/// \brief Attempt value initialization (C++ [dcl.init]p7).
2801static void TryValueInitialization(Sema &S,
2802 const InitializedEntity &Entity,
2803 const InitializationKind &Kind,
2804 InitializationSequence &Sequence) {
2805 // C++ [dcl.init]p5:
2806 //
2807 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002808 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002809
2810 // -- if T is an array type, then each element is value-initialized;
2811 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2812 T = AT->getElementType();
2813
2814 if (const RecordType *RT = T->getAs<RecordType>()) {
2815 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2816 // -- if T is a class type (clause 9) with a user-declared
2817 // constructor (12.1), then the default constructor for T is
2818 // called (and the initialization is ill-formed if T has no
2819 // accessible default constructor);
2820 //
2821 // FIXME: we really want to refer to a single subobject of the array,
2822 // but Entity doesn't have a way to capture that (yet).
2823 if (ClassDecl->hasUserDeclaredConstructor())
2824 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2825
Douglas Gregor16006c92009-12-16 18:50:27 +00002826 // -- if T is a (possibly cv-qualified) non-union class type
2827 // without a user-provided constructor, then the object is
2828 // zero-initialized and, if T’s implicitly-declared default
2829 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002830 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002831 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002832 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002833 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2834 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002835 }
2836 }
2837
Douglas Gregord6542d82009-12-22 15:35:07 +00002838 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002839 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2840}
2841
Douglas Gregor99a2e602009-12-16 01:38:02 +00002842/// \brief Attempt default initialization (C++ [dcl.init]p6).
2843static void TryDefaultInitialization(Sema &S,
2844 const InitializedEntity &Entity,
2845 const InitializationKind &Kind,
2846 InitializationSequence &Sequence) {
2847 assert(Kind.getKind() == InitializationKind::IK_Default);
2848
2849 // C++ [dcl.init]p6:
2850 // To default-initialize an object of type T means:
2851 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002852 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002853 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2854 DestType = Array->getElementType();
2855
2856 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2857 // constructor for T is called (and the initialization is ill-formed if
2858 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002859 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00002860 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2861 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002862 }
2863
2864 // - otherwise, no initialization is performed.
2865 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2866
2867 // If a program calls for the default initialization of an object of
2868 // a const-qualified type T, T shall be a class type with a user-provided
2869 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002870 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002871 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2872}
2873
Douglas Gregor20093b42009-12-09 23:02:17 +00002874/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2875/// which enumerates all conversion functions and performs overload resolution
2876/// to select the best.
2877static void TryUserDefinedConversion(Sema &S,
2878 const InitializedEntity &Entity,
2879 const InitializationKind &Kind,
2880 Expr *Initializer,
2881 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002882 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2883
Douglas Gregord6542d82009-12-22 15:35:07 +00002884 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002885 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2886 QualType SourceType = Initializer->getType();
2887 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2888 "Must have a class type to perform a user-defined conversion");
2889
2890 // Build the candidate set directly in the initialization sequence
2891 // structure, so that it will persist if we fail.
2892 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2893 CandidateSet.clear();
2894
2895 // Determine whether we are allowed to call explicit constructors or
2896 // explicit conversion operators.
2897 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2898
2899 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2900 // The type we're converting to is a class type. Enumerate its constructors
2901 // to see if there is a suitable conversion.
2902 CXXRecordDecl *DestRecordDecl
2903 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2904
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002905 // Try to complete the type we're converting to.
2906 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002907 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002908 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002909 Con != ConEnd; ++Con) {
2910 NamedDecl *D = *Con;
2911 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002912
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002913 // Find the constructor (which may be a template).
2914 CXXConstructorDecl *Constructor = 0;
2915 FunctionTemplateDecl *ConstructorTmpl
2916 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002917 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002918 Constructor = cast<CXXConstructorDecl>(
2919 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002920 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002921 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002922
2923 if (!Constructor->isInvalidDecl() &&
2924 Constructor->isConvertingConstructor(AllowExplicit)) {
2925 if (ConstructorTmpl)
2926 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2927 /*ExplicitArgs*/ 0,
2928 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002929 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002930 else
2931 S.AddOverloadCandidate(Constructor, FoundDecl,
2932 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002933 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002934 }
2935 }
2936 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002937 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002938
2939 SourceLocation DeclLoc = Initializer->getLocStart();
2940
Douglas Gregor4a520a22009-12-14 17:27:33 +00002941 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2942 // The type we're converting from is a class type, enumerate its conversion
2943 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002944
Eli Friedman33c2da92009-12-20 22:12:03 +00002945 // We can only enumerate the conversion functions for a complete type; if
2946 // the type isn't complete, simply skip this step.
2947 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2948 CXXRecordDecl *SourceRecordDecl
2949 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002950
John McCalleec51cf2010-01-20 00:46:10 +00002951 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002952 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002953 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002954 E = Conversions->end();
2955 I != E; ++I) {
2956 NamedDecl *D = *I;
2957 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2958 if (isa<UsingShadowDecl>(D))
2959 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2960
2961 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2962 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002963 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002964 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002965 else
John McCall32daa422010-03-31 01:36:47 +00002966 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00002967
2968 if (AllowExplicit || !Conv->isExplicit()) {
2969 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002970 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002971 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00002972 CandidateSet);
2973 else
John McCall9aa472c2010-03-19 07:35:19 +00002974 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00002975 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00002976 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002977 }
2978 }
2979 }
2980
Douglas Gregor4a520a22009-12-14 17:27:33 +00002981 // Perform overload resolution. If it fails, return the failed result.
2982 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002983 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002984 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002985 Sequence.SetOverloadFailure(
2986 InitializationSequence::FK_UserConversionOverloadFailed,
2987 Result);
2988 return;
2989 }
John McCall1d318332010-01-12 00:44:57 +00002990
Douglas Gregor4a520a22009-12-14 17:27:33 +00002991 FunctionDecl *Function = Best->Function;
2992
2993 if (isa<CXXConstructorDecl>(Function)) {
2994 // Add the user-defined conversion step. Any cv-qualification conversion is
2995 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00002996 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002997 return;
2998 }
2999
3000 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003001 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003002 if (ConvType->getAs<RecordType>()) {
3003 // If we're converting to a class type, there may be an copy if
3004 // the resulting temporary object (possible to create an object of
3005 // a base class type). That copy is not a separate conversion, so
3006 // we just make a note of the actual destination type (possibly a
3007 // base class of the type returned by the conversion function) and
3008 // let the user-defined conversion step handle the conversion.
3009 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3010 return;
3011 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003012
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003013 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3014
3015 // If the conversion following the call to the conversion function
3016 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003017 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3018 Best->FinalConversion.Third) {
3019 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003020 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003021 ICS.Standard = Best->FinalConversion;
3022 Sequence.AddConversionSequenceStep(ICS, DestType);
3023 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003024}
3025
Douglas Gregor20093b42009-12-09 23:02:17 +00003026InitializationSequence::InitializationSequence(Sema &S,
3027 const InitializedEntity &Entity,
3028 const InitializationKind &Kind,
3029 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003030 unsigned NumArgs)
3031 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003032 ASTContext &Context = S.Context;
3033
3034 // C++0x [dcl.init]p16:
3035 // The semantics of initializers are as follows. The destination type is
3036 // the type of the object or reference being initialized and the source
3037 // type is the type of the initializer expression. The source type is not
3038 // defined when the initializer is a braced-init-list or when it is a
3039 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003040 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003041
3042 if (DestType->isDependentType() ||
3043 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3044 SequenceKind = DependentSequence;
3045 return;
3046 }
3047
3048 QualType SourceType;
3049 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003050 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003051 Initializer = Args[0];
3052 if (!isa<InitListExpr>(Initializer))
3053 SourceType = Initializer->getType();
3054 }
3055
3056 // - If the initializer is a braced-init-list, the object is
3057 // list-initialized (8.5.4).
3058 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3059 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003060 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003061 }
3062
3063 // - If the destination type is a reference type, see 8.5.3.
3064 if (DestType->isReferenceType()) {
3065 // C++0x [dcl.init.ref]p1:
3066 // A variable declared to be a T& or T&&, that is, "reference to type T"
3067 // (8.3.2), shall be initialized by an object, or function, of type T or
3068 // by an object that can be converted into a T.
3069 // (Therefore, multiple arguments are not permitted.)
3070 if (NumArgs != 1)
3071 SetFailed(FK_TooManyInitsForReference);
3072 else
3073 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3074 return;
3075 }
3076
3077 // - If the destination type is an array of characters, an array of
3078 // char16_t, an array of char32_t, or an array of wchar_t, and the
3079 // initializer is a string literal, see 8.5.2.
3080 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3081 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3082 return;
3083 }
3084
3085 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003086 if (Kind.getKind() == InitializationKind::IK_Value ||
3087 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003088 TryValueInitialization(S, Entity, Kind, *this);
3089 return;
3090 }
3091
Douglas Gregor99a2e602009-12-16 01:38:02 +00003092 // Handle default initialization.
3093 if (Kind.getKind() == InitializationKind::IK_Default){
3094 TryDefaultInitialization(S, Entity, Kind, *this);
3095 return;
3096 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003097
Douglas Gregor20093b42009-12-09 23:02:17 +00003098 // - Otherwise, if the destination type is an array, the program is
3099 // ill-formed.
3100 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3101 if (AT->getElementType()->isAnyCharacterType())
3102 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3103 else
3104 SetFailed(FK_ArrayNeedsInitList);
3105
3106 return;
3107 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003108
3109 // Handle initialization in C
3110 if (!S.getLangOptions().CPlusPlus) {
3111 setSequenceKind(CAssignment);
3112 AddCAssignmentStep(DestType);
3113 return;
3114 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003115
3116 // - If the destination type is a (possibly cv-qualified) class type:
3117 if (DestType->isRecordType()) {
3118 // - If the initialization is direct-initialization, or if it is
3119 // copy-initialization where the cv-unqualified version of the
3120 // source type is the same class as, or a derived class of, the
3121 // class of the destination, constructors are considered. [...]
3122 if (Kind.getKind() == InitializationKind::IK_Direct ||
3123 (Kind.getKind() == InitializationKind::IK_Copy &&
3124 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3125 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003126 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003127 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003128 // - Otherwise (i.e., for the remaining copy-initialization cases),
3129 // user-defined conversion sequences that can convert from the source
3130 // type to the destination type or (when a conversion function is
3131 // used) to a derived class thereof are enumerated as described in
3132 // 13.3.1.4, and the best one is chosen through overload resolution
3133 // (13.3).
3134 else
3135 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3136 return;
3137 }
3138
Douglas Gregor99a2e602009-12-16 01:38:02 +00003139 if (NumArgs > 1) {
3140 SetFailed(FK_TooManyInitsForScalar);
3141 return;
3142 }
3143 assert(NumArgs == 1 && "Zero-argument case handled above");
3144
Douglas Gregor20093b42009-12-09 23:02:17 +00003145 // - Otherwise, if the source type is a (possibly cv-qualified) class
3146 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003147 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003148 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3149 return;
3150 }
3151
3152 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003153 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003154 // conversions (Clause 4) will be used, if necessary, to convert the
3155 // initializer expression to the cv-unqualified version of the
3156 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003157 if (S.TryImplicitConversion(*this, Entity, Initializer,
3158 /*SuppressUserConversions*/ true,
3159 /*AllowExplicitConversions*/ false,
3160 /*InOverloadResolution*/ false))
3161 SetFailed(InitializationSequence::FK_ConversionFailed);
3162 else
3163 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003164}
3165
3166InitializationSequence::~InitializationSequence() {
3167 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3168 StepEnd = Steps.end();
3169 Step != StepEnd; ++Step)
3170 Step->Destroy();
3171}
3172
3173//===----------------------------------------------------------------------===//
3174// Perform initialization
3175//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003176static Sema::AssignmentAction
3177getAssignmentAction(const InitializedEntity &Entity) {
3178 switch(Entity.getKind()) {
3179 case InitializedEntity::EK_Variable:
3180 case InitializedEntity::EK_New:
3181 return Sema::AA_Initializing;
3182
3183 case InitializedEntity::EK_Parameter:
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003184 if (Entity.getDecl() &&
3185 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3186 return Sema::AA_Sending;
3187
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003188 return Sema::AA_Passing;
3189
3190 case InitializedEntity::EK_Result:
3191 return Sema::AA_Returning;
3192
3193 case InitializedEntity::EK_Exception:
3194 case InitializedEntity::EK_Base:
3195 llvm_unreachable("No assignment action for C++-specific initialization");
3196 break;
3197
3198 case InitializedEntity::EK_Temporary:
3199 // FIXME: Can we tell apart casting vs. converting?
3200 return Sema::AA_Casting;
3201
3202 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003203 case InitializedEntity::EK_ArrayElement:
3204 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003205 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003206 return Sema::AA_Initializing;
3207 }
3208
3209 return Sema::AA_Converting;
3210}
3211
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003212/// \brief Whether we should binding a created object as a temporary when
3213/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003214static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003215 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003216 case InitializedEntity::EK_ArrayElement:
3217 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003218 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003219 case InitializedEntity::EK_New:
3220 case InitializedEntity::EK_Variable:
3221 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003222 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003223 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003224 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003225 return false;
3226
3227 case InitializedEntity::EK_Parameter:
3228 case InitializedEntity::EK_Temporary:
3229 return true;
3230 }
3231
3232 llvm_unreachable("missed an InitializedEntity kind?");
3233}
3234
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003235/// \brief Whether the given entity, when initialized with an object
3236/// created for that initialization, requires destruction.
3237static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3238 switch (Entity.getKind()) {
3239 case InitializedEntity::EK_Member:
3240 case InitializedEntity::EK_Result:
3241 case InitializedEntity::EK_New:
3242 case InitializedEntity::EK_Base:
3243 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003244 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003245 return false;
3246
3247 case InitializedEntity::EK_Variable:
3248 case InitializedEntity::EK_Parameter:
3249 case InitializedEntity::EK_Temporary:
3250 case InitializedEntity::EK_ArrayElement:
3251 case InitializedEntity::EK_Exception:
3252 return true;
3253 }
3254
3255 llvm_unreachable("missed an InitializedEntity kind?");
3256}
3257
Douglas Gregor523d46a2010-04-18 07:40:54 +00003258/// \brief Make a (potentially elidable) temporary copy of the object
3259/// provided by the given initializer by calling the appropriate copy
3260/// constructor.
3261///
3262/// \param S The Sema object used for type-checking.
3263///
3264/// \param T The type of the temporary object, which must either by
3265/// the type of the initializer expression or a superclass thereof.
3266///
3267/// \param Enter The entity being initialized.
3268///
3269/// \param CurInit The initializer expression.
3270///
3271/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3272/// is permitted in C++03 (but not C++0x) when binding a reference to
3273/// an rvalue.
3274///
3275/// \returns An expression that copies the initializer expression into
3276/// a temporary object, or an error expression if a copy could not be
3277/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003278static ExprResult CopyObject(Sema &S,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003279 QualType T,
Douglas Gregor2f599792010-04-02 18:24:57 +00003280 const InitializedEntity &Entity,
John McCall60d7b3a2010-08-24 06:29:42 +00003281 ExprResult CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00003282 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003283 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003284 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003285 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003286 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003287 Class = cast<CXXRecordDecl>(Record->getDecl());
3288 if (!Class)
3289 return move(CurInit);
3290
3291 // C++0x [class.copy]p34:
3292 // When certain criteria are met, an implementation is allowed to
3293 // omit the copy/move construction of a class object, even if the
3294 // copy/move constructor and/or destructor for the object have
3295 // side effects. [...]
3296 // - when a temporary class object that has not been bound to a
3297 // reference (12.2) would be copied/moved to a class object
3298 // with the same cv-unqualified type, the copy/move operation
3299 // can be omitted by constructing the temporary object
3300 // directly into the target of the omitted copy/move
3301 //
3302 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003303 // elision for return statements and throw expressions are handled as part
3304 // of constructor initialization, while copy elision for exception handlers
3305 // is handled by the run-time.
Douglas Gregor2f599792010-04-02 18:24:57 +00003306 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregor523d46a2010-04-18 07:40:54 +00003307 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003308 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003309 switch (Entity.getKind()) {
3310 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003311 Loc = Entity.getReturnLoc();
3312 break;
3313
3314 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003315 Loc = Entity.getThrowLoc();
3316 break;
3317
3318 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003319 Loc = Entity.getDecl()->getLocation();
3320 break;
3321
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003322 case InitializedEntity::EK_ArrayElement:
3323 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003324 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003325 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003326 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003327 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003328 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003329 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003330 Loc = CurInitExpr->getLocStart();
3331 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003332 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003333
3334 // Make sure that the type we are copying is complete.
3335 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3336 return move(CurInit);
3337
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003338 // Perform overload resolution using the class's copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003339 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003340 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003341 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003342 Con != ConEnd; ++Con) {
Douglas Gregor2f599792010-04-02 18:24:57 +00003343 // Only consider copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003344 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3345 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor153b3ba2010-04-18 02:16:12 +00003346 !Constructor->isCopyConstructor() ||
3347 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003348 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003349
3350 DeclAccessPair FoundDecl
3351 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3352 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003353 &CurInitExpr, 1, CandidateSet);
Douglas Gregor2f599792010-04-02 18:24:57 +00003354 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003355
3356 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00003357 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003358 case OR_Success:
3359 break;
3360
3361 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003362 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3363 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3364 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003365 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003366 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003367 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003368 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003369 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003370 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003371
3372 case OR_Ambiguous:
3373 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003374 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003375 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003376 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003377 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003378
3379 case OR_Deleted:
3380 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003381 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003382 << CurInitExpr->getSourceRange();
3383 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3384 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003385 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003386 }
3387
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003388 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003389 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003390 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003391
Anders Carlsson9a68a672010-04-21 18:47:17 +00003392 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003393 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003394
3395 if (IsExtraneousCopy) {
3396 // If this is a totally extraneous copy for C++03 reference
3397 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003398 // expression. We don't generate an (elided) copy operation here
3399 // because doing so would require us to pass down a flag to avoid
3400 // infinite recursion, where each step adds another extraneous,
3401 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003402
Douglas Gregor2559a702010-04-18 07:57:34 +00003403 // Instantiate the default arguments of any extra parameters in
3404 // the selected copy constructor, as if we were going to create a
3405 // proper call to the copy constructor.
3406 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3407 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3408 if (S.RequireCompleteType(Loc, Parm->getType(),
3409 S.PDiag(diag::err_call_incomplete_argument)))
3410 break;
3411
3412 // Build the default argument expression; we don't actually care
3413 // if this succeeds or not, because this routine will complain
3414 // if there was a problem.
3415 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3416 }
3417
Douglas Gregor523d46a2010-04-18 07:40:54 +00003418 return S.Owned(CurInitExpr);
3419 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003420
3421 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003422 // constructor call (we might have derived-to-base conversions, or
3423 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003424 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003425 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003426 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003427
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003428 // Actually perform the constructor call.
3429 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003430 move_arg(ConstructorArgs),
3431 /*ZeroInit*/ false,
3432 CXXConstructExpr::CK_Complete);
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003433
3434 // If we're supposed to bind temporaries, do so.
3435 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3436 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3437 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003438}
Douglas Gregor20093b42009-12-09 23:02:17 +00003439
Douglas Gregora41a8c52010-04-22 00:20:18 +00003440void InitializationSequence::PrintInitLocationNote(Sema &S,
3441 const InitializedEntity &Entity) {
3442 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3443 if (Entity.getDecl()->getLocation().isInvalid())
3444 return;
3445
3446 if (Entity.getDecl()->getDeclName())
3447 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3448 << Entity.getDecl()->getDeclName();
3449 else
3450 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3451 }
3452}
3453
John McCall60d7b3a2010-08-24 06:29:42 +00003454ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003455InitializationSequence::Perform(Sema &S,
3456 const InitializedEntity &Entity,
3457 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003458 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003459 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003460 if (SequenceKind == FailedSequence) {
3461 unsigned NumArgs = Args.size();
3462 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003463 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003464 }
3465
3466 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003467 // If the declaration is a non-dependent, incomplete array type
3468 // that has an initializer, then its type will be completed once
3469 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003470 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003471 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003472 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003473 if (const IncompleteArrayType *ArrayT
3474 = S.Context.getAsIncompleteArrayType(DeclType)) {
3475 // FIXME: We don't currently have the ability to accurately
3476 // compute the length of an initializer list without
3477 // performing full type-checking of the initializer list
3478 // (since we have to determine where braces are implicitly
3479 // introduced and such). So, we fall back to making the array
3480 // type a dependently-sized array type with no specified
3481 // bound.
3482 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3483 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003484
Douglas Gregord87b61f2009-12-10 17:56:55 +00003485 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003486 if (DeclaratorDecl *DD = Entity.getDecl()) {
3487 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3488 TypeLoc TL = TInfo->getTypeLoc();
3489 if (IncompleteArrayTypeLoc *ArrayLoc
3490 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3491 Brackets = ArrayLoc->getBracketsRange();
3492 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003493 }
3494
3495 *ResultType
3496 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3497 /*NumElts=*/0,
3498 ArrayT->getSizeModifier(),
3499 ArrayT->getIndexTypeCVRQualifiers(),
3500 Brackets);
3501 }
3502
3503 }
3504 }
3505
Eli Friedman08544622009-12-22 02:35:53 +00003506 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003507 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003508
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003509 if (Args.size() == 0)
3510 return S.Owned((Expr *)0);
3511
Douglas Gregor20093b42009-12-09 23:02:17 +00003512 unsigned NumArgs = Args.size();
3513 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3514 SourceLocation(),
3515 (Expr **)Args.release(),
3516 NumArgs,
3517 SourceLocation()));
3518 }
3519
Douglas Gregor99a2e602009-12-16 01:38:02 +00003520 if (SequenceKind == NoInitialization)
3521 return S.Owned((Expr *)0);
3522
Douglas Gregord6542d82009-12-22 15:35:07 +00003523 QualType DestType = Entity.getType().getNonReferenceType();
3524 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003525 // the same as Entity.getDecl()->getType() in cases involving type merging,
3526 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003527 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003528 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003529 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003530
John McCall60d7b3a2010-08-24 06:29:42 +00003531 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003532
3533 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3534
3535 // For initialization steps that start with a single initializer,
3536 // grab the only argument out the Args and place it into the "current"
3537 // initializer.
3538 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003539 case SK_ResolveAddressOfOverloadedFunction:
3540 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003541 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003542 case SK_CastDerivedToBaseLValue:
3543 case SK_BindReference:
3544 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003545 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003546 case SK_UserConversion:
3547 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003548 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003549 case SK_QualificationConversionRValue:
3550 case SK_ConversionSequence:
3551 case SK_ListInitialization:
3552 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003553 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00003554 case SK_ObjCObjectConversion:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003555 assert(Args.size() == 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003556 CurInit = ExprResult(((Expr **)(Args.get()))[0]->Retain());
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003557 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003558 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003559 break;
3560
3561 case SK_ConstructorInitialization:
3562 case SK_ZeroInitialization:
3563 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003564 }
3565
3566 // Walk through the computed steps for the initialization sequence,
3567 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003568 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003569 for (step_iterator Step = step_begin(), StepEnd = step_end();
3570 Step != StepEnd; ++Step) {
3571 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003572 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003573
3574 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003575 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003576
3577 switch (Step->Kind) {
3578 case SK_ResolveAddressOfOverloadedFunction:
3579 // Overload resolution determined which function invoke; update the
3580 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003581 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003582 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003583 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003584 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003585 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003586 break;
3587
3588 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003589 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003590 case SK_CastDerivedToBaseLValue: {
3591 // We have a derived-to-base cast that produces either an rvalue or an
3592 // lvalue. Perform that cast.
3593
John McCallf871d0c2010-08-07 06:22:56 +00003594 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003595
Douglas Gregor20093b42009-12-09 23:02:17 +00003596 // Casts to inaccessible base classes are allowed with C-style casts.
3597 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3598 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3599 CurInitExpr->getLocStart(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003600 CurInitExpr->getSourceRange(),
3601 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003602 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003603
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003604 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3605 QualType T = SourceType;
3606 if (const PointerType *Pointer = T->getAs<PointerType>())
3607 T = Pointer->getPointeeType();
3608 if (const RecordType *RecordTy = T->getAs<RecordType>())
3609 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3610 cast<CXXRecordDecl>(RecordTy->getDecl()));
3611 }
3612
John McCall5baba9d2010-08-25 10:28:54 +00003613 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003614 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003615 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003616 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003617 VK_XValue :
3618 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00003619 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3620 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003621 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00003622 CurInit.get(),
3623 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00003624 break;
3625 }
3626
3627 case SK_BindReference:
3628 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3629 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3630 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003631 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003632 << BitField->getDeclName()
3633 << CurInitExpr->getSourceRange();
3634 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00003635 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003636 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003637
Anders Carlsson09380262010-01-31 17:18:49 +00003638 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003639 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003640 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3641 << Entity.getType().isVolatileQualified()
3642 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003643 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003644 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00003645 }
3646
Douglas Gregor20093b42009-12-09 23:02:17 +00003647 // Reference binding does not have any corresponding ASTs.
3648
3649 // Check exception specifications
3650 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003651 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003652
Douglas Gregor20093b42009-12-09 23:02:17 +00003653 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003654
Douglas Gregor20093b42009-12-09 23:02:17 +00003655 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003656 // Reference binding does not have any corresponding ASTs.
3657
Douglas Gregor20093b42009-12-09 23:02:17 +00003658 // Check exception specifications
3659 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003660 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003661
Douglas Gregor20093b42009-12-09 23:02:17 +00003662 break;
3663
Douglas Gregor523d46a2010-04-18 07:40:54 +00003664 case SK_ExtraneousCopyToTemporary:
3665 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3666 /*IsExtraneousCopy=*/true);
3667 break;
3668
Douglas Gregor20093b42009-12-09 23:02:17 +00003669 case SK_UserConversion: {
3670 // We have a user-defined conversion that invokes either a constructor
3671 // or a conversion function.
John McCall2de56d12010-08-25 11:45:40 +00003672 CastKind CastKind = CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003673 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003674 FunctionDecl *Fn = Step->Function.Function;
3675 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003676 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003677 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003678 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003679 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003680 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor20093b42009-12-09 23:02:17 +00003681 SourceLocation Loc = CurInitExpr->getLocStart();
3682 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003683
Douglas Gregor20093b42009-12-09 23:02:17 +00003684 // Determine the arguments required to actually perform the constructor
3685 // call.
3686 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00003687 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00003688 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003689 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003690
3691 // Build the an expression that constructs a temporary.
3692 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00003693 move_arg(ConstructorArgs),
3694 /*ZeroInit*/ false,
3695 CXXConstructExpr::CK_Complete);
Douglas Gregor20093b42009-12-09 23:02:17 +00003696 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003697 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003698
Anders Carlsson9a68a672010-04-21 18:47:17 +00003699 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003700 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003701 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor20093b42009-12-09 23:02:17 +00003702
John McCall2de56d12010-08-25 11:45:40 +00003703 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003704 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3705 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3706 S.IsDerivedFrom(SourceType, Class))
3707 IsCopy = true;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003708
3709 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 } else {
3711 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003712 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003713 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003714 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003715 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003716 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003717
Douglas Gregor20093b42009-12-09 23:02:17 +00003718 // FIXME: Should we move this initialization into a separate
3719 // derived-to-base conversion? I believe the answer is "no", because
3720 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003721 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003722 FoundFn, Conversion))
John McCallf312b1e2010-08-26 23:41:50 +00003723 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003724
3725 // Do a little dance to make sure that CurInit has the proper
3726 // pointer.
3727 CurInit.release();
3728
3729 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003730 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3731 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003732 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00003733 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003734
John McCall2de56d12010-08-25 11:45:40 +00003735 CastKind = CK_UserDefinedConversion;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003736
3737 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003738 }
3739
Douglas Gregor2f599792010-04-02 18:24:57 +00003740 bool RequiresCopy = !IsCopy &&
3741 getKind() != InitializationSequence::ReferenceBinding;
3742 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003743 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003744 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3745 CurInitExpr = static_cast<Expr *>(CurInit.get());
3746 QualType T = CurInitExpr->getType();
3747 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00003748 CXXDestructorDecl *Destructor
3749 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003750 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3751 S.PDiag(diag::err_access_dtor_temp) << T);
3752 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3753 }
3754 }
3755
Douglas Gregor20093b42009-12-09 23:02:17 +00003756 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redl906082e2010-07-20 04:20:21 +00003757 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00003758 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3759 CurInitExpr->getType(),
3760 CastKind, CurInitExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00003761 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003762
Douglas Gregor2f599792010-04-02 18:24:57 +00003763 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003764 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3765 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003766
Douglas Gregor20093b42009-12-09 23:02:17 +00003767 break;
3768 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003769
Douglas Gregor20093b42009-12-09 23:02:17 +00003770 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003771 case SK_QualificationConversionXValue:
3772 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003773 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00003774 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003775 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003776 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003777 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003778 VK_XValue :
3779 VK_RValue);
John McCall2de56d12010-08-25 11:45:40 +00003780 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00003781 CurInit.release();
3782 CurInit = S.Owned(CurInitExpr);
3783 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003784 }
3785
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003786 case SK_ConversionSequence: {
3787 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3788
3789 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3790 Sema::AA_Converting, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003791 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003792
3793 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003794 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003795 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003796 }
3797
Douglas Gregord87b61f2009-12-10 17:56:55 +00003798 case SK_ListInitialization: {
3799 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3800 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003801 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00003802 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003803
3804 CurInit.release();
3805 CurInit = S.Owned(InitList);
3806 break;
3807 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003808
3809 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003810 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003811 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003812 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003813
Douglas Gregor51c56d62009-12-14 20:49:26 +00003814 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003815 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00003816 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3817 ? Kind.getEqualLoc()
3818 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003819
3820 if (Kind.getKind() == InitializationKind::IK_Default) {
3821 // Force even a trivial, implicit default constructor to be
3822 // semantically checked. We do this explicitly because we don't build
3823 // the definition for completely trivial constructors.
3824 CXXRecordDecl *ClassDecl = Constructor->getParent();
3825 assert(ClassDecl && "No parent class for constructor.");
3826 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3827 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3828 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3829 }
3830
Douglas Gregor51c56d62009-12-14 20:49:26 +00003831 // Determine the arguments required to actually perform the constructor
3832 // call.
3833 if (S.CompleteConstructorCall(Constructor, move(Args),
3834 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003835 return ExprError();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003836
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003837
Douglas Gregor91be6f52010-03-02 17:18:33 +00003838 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003839 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003840 (Kind.getKind() == InitializationKind::IK_Direct ||
3841 Kind.getKind() == InitializationKind::IK_Value)) {
3842 // An explicitly-constructed temporary, e.g., X(1, 2).
3843 unsigned NumExprs = ConstructorArgs.size();
3844 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003845 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor91be6f52010-03-02 17:18:33 +00003846 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3847 Constructor,
3848 Entity.getType(),
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003849 Loc,
Douglas Gregor91be6f52010-03-02 17:18:33 +00003850 Exprs,
3851 NumExprs,
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003852 Kind.getParenRange().getEnd(),
3853 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003854 } else {
3855 CXXConstructExpr::ConstructionKind ConstructKind =
3856 CXXConstructExpr::CK_Complete;
3857
3858 if (Entity.getKind() == InitializedEntity::EK_Base) {
3859 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3860 CXXConstructExpr::CK_VirtualBase :
3861 CXXConstructExpr::CK_NonVirtualBase;
3862 }
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003863
3864 // If the entity allows NRVO, mark the construction as elidable
3865 // unconditionally.
3866 if (Entity.allowsNRVO())
3867 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3868 Constructor, /*Elidable=*/true,
3869 move_arg(ConstructorArgs),
3870 ConstructorInitRequiresZeroInit,
3871 ConstructKind);
3872 else
3873 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3874 Constructor,
3875 move_arg(ConstructorArgs),
3876 ConstructorInitRequiresZeroInit,
3877 ConstructKind);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003878 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003879 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003880 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003881
3882 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00003883 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003884 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003885 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003886
Douglas Gregor2f599792010-04-02 18:24:57 +00003887 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003888 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003889
Douglas Gregor51c56d62009-12-14 20:49:26 +00003890 break;
3891 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003892
3893 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003894 step_iterator NextStep = Step;
3895 ++NextStep;
3896 if (NextStep != StepEnd &&
3897 NextStep->Kind == SK_ConstructorInitialization) {
3898 // The need for zero-initialization is recorded directly into
3899 // the call to the object's constructor within the next step.
3900 ConstructorInitRequiresZeroInit = true;
3901 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3902 S.getLangOptions().CPlusPlus &&
3903 !Kind.isImplicitValueInit()) {
Douglas Gregored8abf12010-07-08 06:14:04 +00003904 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(Step->Type,
Douglas Gregor71d17402009-12-15 00:01:57 +00003905 Kind.getRange().getBegin(),
3906 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003907 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003908 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003909 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003910 break;
3911 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003912
3913 case SK_CAssignment: {
3914 QualType SourceType = CurInitExpr->getType();
3915 Sema::AssignConvertType ConvTy =
3916 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003917
3918 // If this is a call, allow conversion to a transparent union.
3919 if (ConvTy != Sema::Compatible &&
3920 Entity.getKind() == InitializedEntity::EK_Parameter &&
3921 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3922 == Sema::Compatible)
3923 ConvTy = Sema::Compatible;
3924
Douglas Gregora41a8c52010-04-22 00:20:18 +00003925 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003926 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3927 Step->Type, SourceType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00003928 CurInitExpr,
3929 getAssignmentAction(Entity),
3930 &Complained)) {
3931 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003932 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003933 } else if (Complained)
3934 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003935
3936 CurInit.release();
3937 CurInit = S.Owned(CurInitExpr);
3938 break;
3939 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003940
3941 case SK_StringInit: {
3942 QualType Ty = Step->Type;
3943 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3944 break;
3945 }
Douglas Gregor569c3162010-08-07 11:51:51 +00003946
3947 case SK_ObjCObjectConversion:
3948 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003949 CK_ObjCObjectLValueCast,
Douglas Gregor569c3162010-08-07 11:51:51 +00003950 S.CastCategory(CurInitExpr));
3951 CurInit.release();
3952 CurInit = S.Owned(CurInitExpr);
3953 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003954 }
3955 }
3956
3957 return move(CurInit);
3958}
3959
3960//===----------------------------------------------------------------------===//
3961// Diagnose initialization failures
3962//===----------------------------------------------------------------------===//
3963bool InitializationSequence::Diagnose(Sema &S,
3964 const InitializedEntity &Entity,
3965 const InitializationKind &Kind,
3966 Expr **Args, unsigned NumArgs) {
3967 if (SequenceKind != FailedSequence)
3968 return false;
3969
Douglas Gregord6542d82009-12-22 15:35:07 +00003970 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003971 switch (Failure) {
3972 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003973 // FIXME: Customize for the initialized entity?
3974 if (NumArgs == 0)
3975 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3976 << DestType.getNonReferenceType();
3977 else // FIXME: diagnostic below could be better!
3978 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3979 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00003980 break;
3981
3982 case FK_ArrayNeedsInitList:
3983 case FK_ArrayNeedsInitListOrStringLiteral:
3984 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3985 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3986 break;
3987
John McCall6bb80172010-03-30 21:47:33 +00003988 case FK_AddressOfOverloadFailed: {
3989 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00003990 S.ResolveAddressOfOverloadedFunction(Args[0],
3991 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00003992 true,
3993 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00003994 break;
John McCall6bb80172010-03-30 21:47:33 +00003995 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003996
3997 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003998 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003999 switch (FailedOverloadResult) {
4000 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004001 if (Failure == FK_UserConversionOverloadFailed)
4002 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4003 << Args[0]->getType() << DestType
4004 << Args[0]->getSourceRange();
4005 else
4006 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4007 << DestType << Args[0]->getType()
4008 << Args[0]->getSourceRange();
4009
John McCall120d63c2010-08-24 20:38:10 +00004010 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004011 break;
4012
4013 case OR_No_Viable_Function:
4014 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4015 << Args[0]->getType() << DestType.getNonReferenceType()
4016 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004017 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004018 break;
4019
4020 case OR_Deleted: {
4021 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4022 << Args[0]->getType() << DestType.getNonReferenceType()
4023 << Args[0]->getSourceRange();
4024 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004025 OverloadingResult Ovl
4026 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor20093b42009-12-09 23:02:17 +00004027 if (Ovl == OR_Deleted) {
4028 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4029 << Best->Function->isDeleted();
4030 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004031 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004032 }
4033 break;
4034 }
4035
4036 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004037 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004038 break;
4039 }
4040 break;
4041
4042 case FK_NonConstLValueReferenceBindingToTemporary:
4043 case FK_NonConstLValueReferenceBindingToUnrelated:
4044 S.Diag(Kind.getLocation(),
4045 Failure == FK_NonConstLValueReferenceBindingToTemporary
4046 ? diag::err_lvalue_reference_bind_to_temporary
4047 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004048 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004049 << DestType.getNonReferenceType()
4050 << Args[0]->getType()
4051 << Args[0]->getSourceRange();
4052 break;
4053
4054 case FK_RValueReferenceBindingToLValue:
4055 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4056 << Args[0]->getSourceRange();
4057 break;
4058
4059 case FK_ReferenceInitDropsQualifiers:
4060 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4061 << DestType.getNonReferenceType()
4062 << Args[0]->getType()
4063 << Args[0]->getSourceRange();
4064 break;
4065
4066 case FK_ReferenceInitFailed:
4067 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4068 << DestType.getNonReferenceType()
4069 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4070 << Args[0]->getType()
4071 << Args[0]->getSourceRange();
4072 break;
4073
4074 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004075 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4076 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004077 << DestType
4078 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4079 << Args[0]->getType()
4080 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004081 break;
4082
4083 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004084 SourceRange R;
4085
4086 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4087 R = SourceRange(InitList->getInit(1)->getLocStart(),
4088 InitList->getLocEnd());
4089 else
4090 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004091
4092 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00004093 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004094 break;
4095 }
4096
4097 case FK_ReferenceBindingToInitList:
4098 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4099 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4100 break;
4101
4102 case FK_InitListBadDestinationType:
4103 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4104 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4105 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00004106
4107 case FK_ConstructorOverloadFailed: {
4108 SourceRange ArgsRange;
4109 if (NumArgs)
4110 ArgsRange = SourceRange(Args[0]->getLocStart(),
4111 Args[NumArgs - 1]->getLocEnd());
4112
4113 // FIXME: Using "DestType" for the entity we're printing is probably
4114 // bad.
4115 switch (FailedOverloadResult) {
4116 case OR_Ambiguous:
4117 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4118 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004119 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4120 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004121 break;
4122
4123 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004124 if (Kind.getKind() == InitializationKind::IK_Default &&
4125 (Entity.getKind() == InitializedEntity::EK_Base ||
4126 Entity.getKind() == InitializedEntity::EK_Member) &&
4127 isa<CXXConstructorDecl>(S.CurContext)) {
4128 // This is implicit default initialization of a member or
4129 // base within a constructor. If no viable function was
4130 // found, notify the user that she needs to explicitly
4131 // initialize this base/member.
4132 CXXConstructorDecl *Constructor
4133 = cast<CXXConstructorDecl>(S.CurContext);
4134 if (Entity.getKind() == InitializedEntity::EK_Base) {
4135 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4136 << Constructor->isImplicit()
4137 << S.Context.getTypeDeclType(Constructor->getParent())
4138 << /*base=*/0
4139 << Entity.getType();
4140
4141 RecordDecl *BaseDecl
4142 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4143 ->getDecl();
4144 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4145 << S.Context.getTagDeclType(BaseDecl);
4146 } else {
4147 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4148 << Constructor->isImplicit()
4149 << S.Context.getTypeDeclType(Constructor->getParent())
4150 << /*member=*/1
4151 << Entity.getName();
4152 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4153
4154 if (const RecordType *Record
4155 = Entity.getType()->getAs<RecordType>())
4156 S.Diag(Record->getDecl()->getLocation(),
4157 diag::note_previous_decl)
4158 << S.Context.getTagDeclType(Record->getDecl());
4159 }
4160 break;
4161 }
4162
Douglas Gregor51c56d62009-12-14 20:49:26 +00004163 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4164 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004165 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004166 break;
4167
4168 case OR_Deleted: {
4169 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4170 << true << DestType << ArgsRange;
4171 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004172 OverloadingResult Ovl
4173 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004174 if (Ovl == OR_Deleted) {
4175 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4176 << Best->Function->isDeleted();
4177 } else {
4178 llvm_unreachable("Inconsistent overload resolution?");
4179 }
4180 break;
4181 }
4182
4183 case OR_Success:
4184 llvm_unreachable("Conversion did not fail!");
4185 break;
4186 }
4187 break;
4188 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004189
4190 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004191 if (Entity.getKind() == InitializedEntity::EK_Member &&
4192 isa<CXXConstructorDecl>(S.CurContext)) {
4193 // This is implicit default-initialization of a const member in
4194 // a constructor. Complain that it needs to be explicitly
4195 // initialized.
4196 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4197 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4198 << Constructor->isImplicit()
4199 << S.Context.getTypeDeclType(Constructor->getParent())
4200 << /*const=*/1
4201 << Entity.getName();
4202 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4203 << Entity.getName();
4204 } else {
4205 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4206 << DestType << (bool)DestType->getAs<RecordType>();
4207 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004208 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004209
4210 case FK_Incomplete:
4211 S.RequireCompleteType(Kind.getLocation(), DestType,
4212 diag::err_init_incomplete_type);
4213 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004214 }
4215
Douglas Gregora41a8c52010-04-22 00:20:18 +00004216 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004217 return true;
4218}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004219
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004220void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4221 switch (SequenceKind) {
4222 case FailedSequence: {
4223 OS << "Failed sequence: ";
4224 switch (Failure) {
4225 case FK_TooManyInitsForReference:
4226 OS << "too many initializers for reference";
4227 break;
4228
4229 case FK_ArrayNeedsInitList:
4230 OS << "array requires initializer list";
4231 break;
4232
4233 case FK_ArrayNeedsInitListOrStringLiteral:
4234 OS << "array requires initializer list or string literal";
4235 break;
4236
4237 case FK_AddressOfOverloadFailed:
4238 OS << "address of overloaded function failed";
4239 break;
4240
4241 case FK_ReferenceInitOverloadFailed:
4242 OS << "overload resolution for reference initialization failed";
4243 break;
4244
4245 case FK_NonConstLValueReferenceBindingToTemporary:
4246 OS << "non-const lvalue reference bound to temporary";
4247 break;
4248
4249 case FK_NonConstLValueReferenceBindingToUnrelated:
4250 OS << "non-const lvalue reference bound to unrelated type";
4251 break;
4252
4253 case FK_RValueReferenceBindingToLValue:
4254 OS << "rvalue reference bound to an lvalue";
4255 break;
4256
4257 case FK_ReferenceInitDropsQualifiers:
4258 OS << "reference initialization drops qualifiers";
4259 break;
4260
4261 case FK_ReferenceInitFailed:
4262 OS << "reference initialization failed";
4263 break;
4264
4265 case FK_ConversionFailed:
4266 OS << "conversion failed";
4267 break;
4268
4269 case FK_TooManyInitsForScalar:
4270 OS << "too many initializers for scalar";
4271 break;
4272
4273 case FK_ReferenceBindingToInitList:
4274 OS << "referencing binding to initializer list";
4275 break;
4276
4277 case FK_InitListBadDestinationType:
4278 OS << "initializer list for non-aggregate, non-scalar type";
4279 break;
4280
4281 case FK_UserConversionOverloadFailed:
4282 OS << "overloading failed for user-defined conversion";
4283 break;
4284
4285 case FK_ConstructorOverloadFailed:
4286 OS << "constructor overloading failed";
4287 break;
4288
4289 case FK_DefaultInitOfConst:
4290 OS << "default initialization of a const variable";
4291 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004292
4293 case FK_Incomplete:
4294 OS << "initialization of incomplete type";
4295 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004296 }
4297 OS << '\n';
4298 return;
4299 }
4300
4301 case DependentSequence:
4302 OS << "Dependent sequence: ";
4303 return;
4304
4305 case UserDefinedConversion:
4306 OS << "User-defined conversion sequence: ";
4307 break;
4308
4309 case ConstructorInitialization:
4310 OS << "Constructor initialization sequence: ";
4311 break;
4312
4313 case ReferenceBinding:
4314 OS << "Reference binding: ";
4315 break;
4316
4317 case ListInitialization:
4318 OS << "List initialization: ";
4319 break;
4320
4321 case ZeroInitialization:
4322 OS << "Zero initialization\n";
4323 return;
4324
4325 case NoInitialization:
4326 OS << "No initialization\n";
4327 return;
4328
4329 case StandardConversion:
4330 OS << "Standard conversion: ";
4331 break;
4332
4333 case CAssignment:
4334 OS << "C assignment: ";
4335 break;
4336
4337 case StringInit:
4338 OS << "String initialization: ";
4339 break;
4340 }
4341
4342 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4343 if (S != step_begin()) {
4344 OS << " -> ";
4345 }
4346
4347 switch (S->Kind) {
4348 case SK_ResolveAddressOfOverloadedFunction:
4349 OS << "resolve address of overloaded function";
4350 break;
4351
4352 case SK_CastDerivedToBaseRValue:
4353 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4354 break;
4355
Sebastian Redl906082e2010-07-20 04:20:21 +00004356 case SK_CastDerivedToBaseXValue:
4357 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4358 break;
4359
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004360 case SK_CastDerivedToBaseLValue:
4361 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4362 break;
4363
4364 case SK_BindReference:
4365 OS << "bind reference to lvalue";
4366 break;
4367
4368 case SK_BindReferenceToTemporary:
4369 OS << "bind reference to a temporary";
4370 break;
4371
Douglas Gregor523d46a2010-04-18 07:40:54 +00004372 case SK_ExtraneousCopyToTemporary:
4373 OS << "extraneous C++03 copy to temporary";
4374 break;
4375
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004376 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004377 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004378 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004379
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004380 case SK_QualificationConversionRValue:
4381 OS << "qualification conversion (rvalue)";
4382
Sebastian Redl906082e2010-07-20 04:20:21 +00004383 case SK_QualificationConversionXValue:
4384 OS << "qualification conversion (xvalue)";
4385
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004386 case SK_QualificationConversionLValue:
4387 OS << "qualification conversion (lvalue)";
4388 break;
4389
4390 case SK_ConversionSequence:
4391 OS << "implicit conversion sequence (";
4392 S->ICS->DebugPrint(); // FIXME: use OS
4393 OS << ")";
4394 break;
4395
4396 case SK_ListInitialization:
4397 OS << "list initialization";
4398 break;
4399
4400 case SK_ConstructorInitialization:
4401 OS << "constructor initialization";
4402 break;
4403
4404 case SK_ZeroInitialization:
4405 OS << "zero initialization";
4406 break;
4407
4408 case SK_CAssignment:
4409 OS << "C assignment";
4410 break;
4411
4412 case SK_StringInit:
4413 OS << "string initialization";
4414 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004415
4416 case SK_ObjCObjectConversion:
4417 OS << "Objective-C object conversion";
4418 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004419 }
4420 }
4421}
4422
4423void InitializationSequence::dump() const {
4424 dump(llvm::errs());
4425}
4426
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004427//===----------------------------------------------------------------------===//
4428// Initialization helper functions
4429//===----------------------------------------------------------------------===//
John McCall60d7b3a2010-08-24 06:29:42 +00004430ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004431Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4432 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004433 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004434 if (Init.isInvalid())
4435 return ExprError();
4436
4437 Expr *InitE = (Expr *)Init.get();
4438 assert(InitE && "No initialization expression?");
4439
4440 if (EqualLoc.isInvalid())
4441 EqualLoc = InitE->getLocStart();
4442
4443 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4444 EqualLoc);
4445 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4446 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004447 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004448}