blob: 555166076de4e8c7e0e483b664d4fafa58353595 [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//
Steve Naroff0cca7492008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattner79e079d2009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman8718a6a2009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner8879e3b2009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000057
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000064 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 return 0;
67}
68
Chris Lattner79e079d2009-02-24 23:10:27 +000069static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
70 // Get the length of the string as parsed.
71 uint64_t StrLength =
72 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
73
Mike Stump1eb44332009-09-09 15:08:12 +000074
Chris Lattner79e079d2009-02-24 23:10:27 +000075 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000077 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000078 // being initialized to a string literal.
79 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000080 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000081 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000082 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
83 ConstVal,
84 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000085 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086 }
Mike Stump1eb44332009-09-09 15:08:12 +000087
Eli Friedman8718a6a2009-05-29 18:22:49 +000088 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +000089
Eli Friedman8718a6a2009-05-29 18:22:49 +000090 // C99 6.7.8p14. We have an array of character type with known size. However,
91 // the size may be smaller or larger than the string we are initializing.
92 // FIXME: Avoid truncation for 64-bit length strings.
93 if (StrLength-1 > CAT->getSize().getZExtValue())
94 S.Diag(Str->getSourceRange().getBegin(),
95 diag::warn_initializer_string_for_char_array_too_long)
96 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000097
Eli Friedman8718a6a2009-05-29 18:22:49 +000098 // Set the type to the actual size that we are initializing. If we have
99 // something like:
100 // char x[1] = "foo";
101 // then this will set the string literal's type to char[1].
102 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000103}
104
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000105//===----------------------------------------------------------------------===//
106// Semantic checking for initializer lists.
107//===----------------------------------------------------------------------===//
108
Douglas Gregor9e80f722009-01-29 01:05:33 +0000109/// @brief Semantic checking for initializer lists.
110///
111/// The InitListChecker class contains a set of routines that each
112/// handle the initialization of a certain kind of entity, e.g.,
113/// arrays, vectors, struct/union types, scalars, etc. The
114/// InitListChecker itself performs a recursive walk of the subobject
115/// structure of the type to be initialized, while stepping through
116/// the initializer list one element at a time. The IList and Index
117/// parameters to each of the Check* routines contain the active
118/// (syntactic) initializer list and the index into that initializer
119/// list that represents the current initializer. Each routine is
120/// responsible for moving that Index forward as it consumes elements.
121///
122/// Each Check* routine also has a StructuredList/StructuredIndex
123/// arguments, which contains the current the "structured" (semantic)
124/// initializer list and the index into that initializer list where we
125/// are copying initializers as we map them over to the semantic
126/// list. Once we have completed our recursive walk of the subobject
127/// structure, we will have constructed a full semantic initializer
128/// list.
129///
130/// C99 designators cause changes in the initializer list traversal,
131/// because they make the initialization "jump" into a specific
132/// subobject and then continue the initialization from that
133/// point. CheckDesignatedInitializer() recursively steps into the
134/// designated subobject and manages backing out the recursion to
135/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000136namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000137class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000138 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000139 bool hadError;
140 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
141 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000143 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000144 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000145 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000146 unsigned &StructuredIndex,
147 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000148 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000149 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000153 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000155 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000156 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000158 unsigned &StructuredIndex,
159 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000160 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000161 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000162 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000163 InitListExpr *StructuredList,
164 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000165 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000170 void CheckReferenceType(const InitializedEntity &Entity,
171 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000172 unsigned &Index,
173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000175 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000176 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000177 InitListExpr *StructuredList,
178 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000179 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000180 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000181 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000182 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000183 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000186 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000188 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000189 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
191 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000192 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000193 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000194 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000195 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 RecordDecl::field_iterator *NextField,
197 llvm::APSInt *NextElementIndex,
198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000201 bool FinishSubobjectInit,
202 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000203 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
204 QualType CurrentObjectType,
205 InitListExpr *StructuredList,
206 unsigned StructuredIndex,
207 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 void UpdateStructuredListElement(InitListExpr *StructuredList,
209 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000210 Expr *expr);
211 int numArrayElements(QualType DeclType);
212 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000213
Douglas Gregord6d37de2009-12-22 00:05:34 +0000214 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
215 const InitializedEntity &ParentEntity,
216 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000217 void FillInValueInitializations(const InitializedEntity &Entity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000220 InitListChecker(Sema &S, const InitializedEntity &Entity,
221 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool HadError() { return hadError; }
223
224 // @brief Retrieves the fully-structured initializer list used for
225 // semantic analysis and code generation.
226 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
227};
Chris Lattner8b419b92009-02-24 22:48:58 +0000228} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000229
Douglas Gregord6d37de2009-12-22 00:05:34 +0000230void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
231 const InitializedEntity &ParentEntity,
232 InitListExpr *ILE,
233 bool &RequiresSecondPass) {
234 SourceLocation Loc = ILE->getSourceRange().getBegin();
235 unsigned NumInits = ILE->getNumInits();
236 InitializedEntity MemberEntity
237 = InitializedEntity::InitializeMember(Field, &ParentEntity);
238 if (Init >= NumInits || !ILE->getInit(Init)) {
239 // FIXME: We probably don't need to handle references
240 // specially here, since value-initialization of references is
241 // handled in InitializationSequence.
242 if (Field->getType()->isReferenceType()) {
243 // C++ [dcl.init.aggr]p9:
244 // If an incomplete or empty initializer-list leaves a
245 // member of reference type uninitialized, the program is
246 // ill-formed.
247 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
248 << Field->getType()
249 << ILE->getSyntacticForm()->getSourceRange();
250 SemaRef.Diag(Field->getLocation(),
251 diag::note_uninit_reference_member);
252 hadError = true;
253 return;
254 }
255
256 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
257 true);
258 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
259 if (!InitSeq) {
260 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
261 hadError = true;
262 return;
263 }
264
John McCall60d7b3a2010-08-24 06:29:42 +0000265 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000266 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000267 if (MemberInit.isInvalid()) {
268 hadError = true;
269 return;
270 }
271
272 if (hadError) {
273 // Do nothing
274 } else if (Init < NumInits) {
275 ILE->setInit(Init, MemberInit.takeAs<Expr>());
276 } else if (InitSeq.getKind()
277 == InitializationSequence::ConstructorInitialization) {
278 // Value-initialization requires a constructor call, so
279 // extend the initializer list to include the constructor
280 // call and make a note that we'll need to take another pass
281 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000282 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000283 RequiresSecondPass = true;
284 }
285 } else if (InitListExpr *InnerILE
286 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
287 FillInValueInitializations(MemberEntity, InnerILE,
288 RequiresSecondPass);
289}
290
Douglas Gregor4c678342009-01-28 21:54:33 +0000291/// Recursively replaces NULL values within the given initializer list
292/// with expressions that perform value-initialization of the
293/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000294void
295InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
296 InitListExpr *ILE,
297 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000298 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000299 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000300 SourceLocation Loc = ILE->getSourceRange().getBegin();
301 if (ILE->getSyntacticForm())
302 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Ted Kremenek6217b802009-07-29 21:53:49 +0000304 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000305 if (RType->getDecl()->isUnion() &&
306 ILE->getInitializedFieldInUnion())
307 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
308 Entity, ILE, RequiresSecondPass);
309 else {
310 unsigned Init = 0;
311 for (RecordDecl::field_iterator
312 Field = RType->getDecl()->field_begin(),
313 FieldEnd = RType->getDecl()->field_end();
314 Field != FieldEnd; ++Field) {
315 if (Field->isUnnamedBitfield())
316 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000317
Douglas Gregord6d37de2009-12-22 00:05:34 +0000318 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000319 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000320
321 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
322 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000323 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000324
Douglas Gregord6d37de2009-12-22 00:05:34 +0000325 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000326
Douglas Gregord6d37de2009-12-22 00:05:34 +0000327 // Only look at the first initialization of a union.
328 if (RType->getDecl()->isUnion())
329 break;
330 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000331 }
332
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000335
336 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000338 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000339 unsigned NumInits = ILE->getNumInits();
340 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000341 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000342 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000343 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
344 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000345 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
346 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000347 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000348 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000349 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000350 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
351 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000352 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000353 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000355
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000357 if (hadError)
358 return;
359
Anders Carlssond3d824d2010-01-23 04:34:47 +0000360 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
361 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000362 ElementEntity.setElementIndex(Init);
363
Douglas Gregor87fd7032009-02-02 17:43:21 +0000364 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000365 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
366 true);
367 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
368 if (!InitSeq) {
369 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000370 hadError = true;
371 return;
372 }
373
John McCall60d7b3a2010-08-24 06:29:42 +0000374 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000375 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000376 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000377 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000378 return;
379 }
380
381 if (hadError) {
382 // Do nothing
383 } else if (Init < NumInits) {
384 ILE->setInit(Init, ElementInit.takeAs<Expr>());
385 } else if (InitSeq.getKind()
386 == InitializationSequence::ConstructorInitialization) {
387 // Value-initialization requires a constructor call, so
388 // extend the initializer list to include the constructor
389 // call and make a note that we'll need to take another pass
390 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000391 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000392 RequiresSecondPass = true;
393 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000394 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
396 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000397 }
398}
399
Chris Lattner68355a52009-01-29 05:10:57 +0000400
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
402 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000403 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000404 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000405
Eli Friedmanb85f7072008-05-19 19:16:24 +0000406 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000407 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000408 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000409 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000410 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000411 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000412 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000413
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000414 if (!hadError) {
415 bool RequiresSecondPass = false;
416 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000417 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 FillInValueInitializations(Entity, FullyStructuredList,
419 RequiresSecondPass);
420 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000421}
422
423int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000424 // FIXME: use a proper constant
425 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000426 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000427 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000428 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
429 }
430 return maxElements;
431}
432
433int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000434 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000435 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000436 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000437 Field = structDecl->field_begin(),
438 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000439 Field != FieldEnd; ++Field) {
440 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
441 ++InitializableMembers;
442 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000443 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000444 return std::min(InitializableMembers, 1);
445 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000446}
447
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000448void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000449 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000450 QualType T, unsigned &Index,
451 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000452 unsigned &StructuredIndex,
453 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000454 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Steve Naroff0cca7492008-05-01 22:18:59 +0000456 if (T->isArrayType())
457 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000458 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000460 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000461 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000462 else
463 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000464
Eli Friedman402256f2008-05-25 13:49:22 +0000465 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000466 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000467 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000468 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000469 hadError = true;
470 return;
471 }
472
Douglas Gregor4c678342009-01-28 21:54:33 +0000473 // Build a structured initializer list corresponding to this subobject.
474 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000475 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
476 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000477 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
478 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000480
Douglas Gregor4c678342009-01-28 21:54:33 +0000481 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000482 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000483 CheckListElementTypes(Entity, ParentIList, T,
484 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000485 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000486 StructuredSubobjectInitIndex,
487 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000488 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000489 StructuredSubobjectInitList->setType(T);
490
Douglas Gregored8a93d2009-03-01 17:12:46 +0000491 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000492 // range corresponds with the end of the last initializer it used.
493 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000494 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000495 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
496 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
497 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000498
499 // Warn about missing braces.
500 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000501 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
502 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000503 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000504 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
505 "{")
506 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner1dcd0612010-03-07 04:47:12 +0000507 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000508 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000509 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000510}
511
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000512void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000513 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000514 unsigned &Index,
515 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000516 unsigned &StructuredIndex,
517 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000518 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000519 SyntacticToSemantic[IList] = StructuredList;
520 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000521 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
522 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000523 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
524 IList->setType(ExprTy);
525 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000526 if (hadError)
527 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000528
Eli Friedman638e1442008-05-25 13:22:35 +0000529 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000530 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000531 if (StructuredIndex == 1 &&
532 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000533 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000534 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000536 hadError = true;
537 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000538 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000539 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000540 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000541 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000542 // Don't complain for incomplete types, since we'll get an error
543 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000544 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000545 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 CurrentObjectType->isArrayType()? 0 :
547 CurrentObjectType->isVectorType()? 1 :
548 CurrentObjectType->isScalarType()? 2 :
549 CurrentObjectType->isUnionType()? 3 :
550 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000551
552 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000553 if (SemaRef.getLangOptions().CPlusPlus) {
554 DK = diag::err_excess_initializers;
555 hadError = true;
556 }
Nate Begeman08634522009-07-07 21:53:06 +0000557 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000561
Chris Lattner08202542009-02-24 22:50:46 +0000562 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000563 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000564 }
565 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000566
Eli Friedman759f2522009-05-16 11:45:48 +0000567 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000568 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000569 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000570 << FixItHint::CreateRemoval(IList->getLocStart())
571 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000572}
573
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000574void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000575 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000576 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000577 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000578 unsigned &Index,
579 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000580 unsigned &StructuredIndex,
581 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000582 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000583 CheckScalarType(Entity, IList, DeclType, Index,
584 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000585 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000586 CheckVectorType(Entity, IList, DeclType, Index,
587 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000588 } else if (DeclType->isAggregateType()) {
589 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000590 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000591 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000592 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000593 StructuredList, StructuredIndex,
594 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000595 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000596 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000597 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000598 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000599 CheckArrayType(Entity, IList, DeclType, Zero,
600 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000601 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000602 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000604 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
605 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000608 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000609 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000610 } else if (DeclType->isRecordType()) {
611 // C++ [dcl.init]p14:
612 // [...] If the class is an aggregate (8.5.1), and the initializer
613 // is a brace-enclosed list, see 8.5.1.
614 //
615 // Note: 8.5.1 is handled below; here, we diagnose the case where
616 // we have an initializer list and a destination type that is not
617 // an aggregate.
618 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000619 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000620 << DeclType << IList->getSourceRange();
621 hadError = true;
622 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000623 CheckReferenceType(Entity, IList, DeclType, Index,
624 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000625 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000626 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
627 << DeclType;
628 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000629 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000630 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
631 << DeclType;
632 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000633 }
634}
635
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000636void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000637 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000638 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 unsigned &Index,
640 InitListExpr *StructuredList,
641 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000642 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000643 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
644 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000645 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000646 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 = getStructuredSubobjectInit(IList, Index, ElemType,
648 StructuredList, StructuredIndex,
649 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000650 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000651 newStructuredList, newStructuredIndex);
652 ++StructuredIndex;
653 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000654 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
655 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000656 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000657 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000658 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000659 CheckScalarType(Entity, IList, ElemType, Index,
660 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000661 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000662 CheckReferenceType(Entity, IList, ElemType, Index,
663 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000664 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000665 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000666 // C++ [dcl.init.aggr]p12:
667 // All implicit type conversions (clause 4) are considered when
668 // initializing the aggregate member with an ini- tializer from
669 // an initializer-list. If the initializer can initialize a
670 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000671
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000672 // FIXME: Better EqualLoc?
673 InitializationKind Kind =
674 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
675 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
676
677 if (Seq) {
John McCall60d7b3a2010-08-24 06:29:42 +0000678 ExprResult Result =
John McCallf312b1e2010-08-26 23:41:50 +0000679 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000680 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000681 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000682
683 UpdateStructuredListElement(StructuredList, StructuredIndex,
684 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 ++Index;
686 return;
687 }
688
689 // Fall through for subaggregate initialization
690 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000691 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000692 //
693 // The initializer for a structure or union object that has
694 // automatic storage duration shall be either an initializer
695 // list as described below, or a single expression that has
696 // compatible structure or union type. In the latter case, the
697 // initial value of the object, including unnamed members, is
698 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000699 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000700 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
John McCall74e40b72010-12-04 09:03:57 +0000701 SemaRef.DefaultFunctionArrayLvalueConversion(expr);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000702 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
703 ++Index;
704 return;
705 }
706
707 // Fall through for subaggregate initialization
708 }
709
710 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000711 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000712 // [...] Otherwise, if the member is itself a non-empty
713 // subaggregate, brace elision is assumed and the initializer is
714 // considered for the initialization of the first member of
715 // the subaggregate.
716 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000717 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000718 StructuredIndex);
719 ++StructuredIndex;
720 } else {
721 // We cannot initialize this element, so let
722 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssonca755fe2010-01-30 01:56:32 +0000723 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
724 SemaRef.Owned(expr));
Douglas Gregor930d8b52009-01-30 22:09:00 +0000725 hadError = true;
726 ++Index;
727 ++StructuredIndex;
728 }
729 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000730}
731
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000732void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000733 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000734 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000735 InitListExpr *StructuredList,
736 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000737 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000738 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000739 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000740 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000741 ++Index;
742 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000743 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000744 }
John McCallb934c2d2010-11-11 00:46:36 +0000745
746 Expr *expr = IList->getInit(Index);
747 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
748 SemaRef.Diag(SubIList->getLocStart(),
749 diag::warn_many_braces_around_scalar_init)
750 << SubIList->getSourceRange();
751
752 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
753 StructuredIndex);
754 return;
755 } else if (isa<DesignatedInitExpr>(expr)) {
756 SemaRef.Diag(expr->getSourceRange().getBegin(),
757 diag::err_designator_for_scalar_init)
758 << DeclType << expr->getSourceRange();
759 hadError = true;
760 ++Index;
761 ++StructuredIndex;
762 return;
763 }
764
765 ExprResult Result =
766 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
767 SemaRef.Owned(expr));
768
769 Expr *ResultExpr = 0;
770
771 if (Result.isInvalid())
772 hadError = true; // types weren't compatible.
773 else {
774 ResultExpr = Result.takeAs<Expr>();
775
776 if (ResultExpr != expr) {
777 // The type was promoted, update initializer list.
778 IList->setInit(Index, ResultExpr);
779 }
780 }
781 if (hadError)
782 ++StructuredIndex;
783 else
784 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
785 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000786}
787
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000788void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
789 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000790 unsigned &Index,
791 InitListExpr *StructuredList,
792 unsigned &StructuredIndex) {
793 if (Index < IList->getNumInits()) {
794 Expr *expr = IList->getInit(Index);
795 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000796 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000797 << DeclType << IList->getSourceRange();
798 hadError = true;
799 ++Index;
800 ++StructuredIndex;
801 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000802 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000803
John McCall60d7b3a2010-08-24 06:29:42 +0000804 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000805 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
806 SemaRef.Owned(expr));
807
808 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000809 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000810
811 expr = Result.takeAs<Expr>();
812 IList->setInit(Index, expr);
813
Douglas Gregor930d8b52009-01-30 22:09:00 +0000814 if (hadError)
815 ++StructuredIndex;
816 else
817 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
818 ++Index;
819 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000820 // FIXME: It would be wonderful if we could point at the actual member. In
821 // general, it would be useful to pass location information down the stack,
822 // so that we know the location (or decl) of the "current object" being
823 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000824 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000825 diag::err_init_reference_member_uninitialized)
826 << DeclType
827 << IList->getSourceRange();
828 hadError = true;
829 ++Index;
830 ++StructuredIndex;
831 return;
832 }
833}
834
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000835void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000836 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000837 unsigned &Index,
838 InitListExpr *StructuredList,
839 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000840 if (Index >= IList->getNumInits())
841 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000842
John McCall20e047a2010-10-30 00:11:39 +0000843 const VectorType *VT = DeclType->getAs<VectorType>();
844 unsigned maxElements = VT->getNumElements();
845 unsigned numEltsInit = 0;
846 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000847
John McCall20e047a2010-10-30 00:11:39 +0000848 if (!SemaRef.getLangOptions().OpenCL) {
849 // If the initializing element is a vector, try to copy-initialize
850 // instead of breaking it apart (which is doomed to failure anyway).
851 Expr *Init = IList->getInit(Index);
852 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
853 ExprResult Result =
854 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
855 SemaRef.Owned(Init));
856
857 Expr *ResultExpr = 0;
858 if (Result.isInvalid())
859 hadError = true; // types weren't compatible.
860 else {
861 ResultExpr = Result.takeAs<Expr>();
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000862
John McCall20e047a2010-10-30 00:11:39 +0000863 if (ResultExpr != Init) {
864 // The type was promoted, update initializer list.
865 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000866 }
867 }
John McCall20e047a2010-10-30 00:11:39 +0000868 if (hadError)
869 ++StructuredIndex;
870 else
871 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
872 ++Index;
873 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
John McCall20e047a2010-10-30 00:11:39 +0000876 InitializedEntity ElementEntity =
877 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
878
879 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
880 // Don't attempt to go past the end of the init list
881 if (Index >= IList->getNumInits())
882 break;
883
884 ElementEntity.setElementIndex(Index);
885 CheckSubElementType(ElementEntity, IList, elementType, Index,
886 StructuredList, StructuredIndex);
887 }
888 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000889 }
John McCall20e047a2010-10-30 00:11:39 +0000890
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 // OpenCL initializers allows vectors to be constructed from vectors.
895 for (unsigned i = 0; i < maxElements; ++i) {
896 // Don't attempt to go past the end of the init list
897 if (Index >= IList->getNumInits())
898 break;
899
900 ElementEntity.setElementIndex(Index);
901
902 QualType IType = IList->getInit(Index)->getType();
903 if (!IType->isVectorType()) {
904 CheckSubElementType(ElementEntity, IList, elementType, Index,
905 StructuredList, StructuredIndex);
906 ++numEltsInit;
907 } else {
908 QualType VecType;
909 const VectorType *IVT = IType->getAs<VectorType>();
910 unsigned numIElts = IVT->getNumElements();
911
912 if (IType->isExtVectorType())
913 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
914 else
915 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000916 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000917 CheckSubElementType(ElementEntity, IList, VecType, Index,
918 StructuredList, StructuredIndex);
919 numEltsInit += numIElts;
920 }
921 }
922
923 // OpenCL requires all elements to be initialized.
924 if (numEltsInit != maxElements)
925 if (SemaRef.getLangOptions().OpenCL)
926 SemaRef.Diag(IList->getSourceRange().getBegin(),
927 diag::err_vector_incorrect_num_initializers)
928 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000929}
930
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000931void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000932 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000933 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000934 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000935 unsigned &Index,
936 InitListExpr *StructuredList,
937 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000938 // Check for the special-case of initializing an array with a string.
939 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000940 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
941 SemaRef.Context)) {
942 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000943 // We place the string literal directly into the resulting
944 // initializer list. This is the only place where the structure
945 // of the structured initializer list doesn't match exactly,
946 // because doing so would involve allocating one character
947 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000948 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000949 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000950 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000951 return;
952 }
953 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000954 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000955 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000956 // Check for VLAs; in standard C it would be possible to check this
957 // earlier, but I don't know where clang accepts VLAs (gcc accepts
958 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000959 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000960 diag::err_variable_object_no_init)
961 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000962 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000963 ++Index;
964 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000965 return;
966 }
967
Douglas Gregor05c13a32009-01-22 00:58:24 +0000968 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000969 llvm::APSInt maxElements(elementIndex.getBitWidth(),
970 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000971 bool maxElementsKnown = false;
972 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000973 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000974 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +0000975 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000976 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000977 maxElementsKnown = true;
978 }
979
Chris Lattner08202542009-02-24 22:50:46 +0000980 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000981 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000982 while (Index < IList->getNumInits()) {
983 Expr *Init = IList->getInit(Index);
984 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000985 // If we're not the subobject that matches up with the '{' for
986 // the designator, we shouldn't be handling the
987 // designator. Return immediately.
988 if (!SubobjectIsDesignatorContext)
989 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000990
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000991 // Handle this designated initializer. elementIndex will be
992 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000993 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000994 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000995 StructuredList, StructuredIndex, true,
996 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000997 hadError = true;
998 continue;
999 }
1000
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001001 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001002 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001003 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001004 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001005 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001006
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001007 // If the array is of incomplete type, keep track of the number of
1008 // elements in the initializer.
1009 if (!maxElementsKnown && elementIndex > maxElements)
1010 maxElements = elementIndex;
1011
Douglas Gregor05c13a32009-01-22 00:58:24 +00001012 continue;
1013 }
1014
1015 // If we know the maximum number of elements, and we've already
1016 // hit it, stop consuming elements in the initializer list.
1017 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001018 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001019
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001020 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +00001021 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001022 Entity);
1023 // Check this element.
1024 CheckSubElementType(ElementEntity, IList, elementType, Index,
1025 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001026 ++elementIndex;
1027
1028 // If the array is of incomplete type, keep track of the number of
1029 // elements in the initializer.
1030 if (!maxElementsKnown && elementIndex > maxElements)
1031 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001032 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001033 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001034 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001035 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001036 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001037 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001038 // Sizing an array implicitly to zero is not allowed by ISO C,
1039 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001040 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001041 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001042 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001043
Mike Stump1eb44332009-09-09 15:08:12 +00001044 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001045 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001046 }
1047}
1048
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001049void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001050 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001051 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001052 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001053 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001054 unsigned &Index,
1055 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001056 unsigned &StructuredIndex,
1057 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001058 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Eli Friedmanb85f7072008-05-19 19:16:24 +00001060 // If the record is invalid, some of it's members are invalid. To avoid
1061 // confusion, we forgo checking the intializer for the entire record.
1062 if (structDecl->isInvalidDecl()) {
1063 hadError = true;
1064 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001065 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001066
1067 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1068 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001069 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001070 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001071 Field != FieldEnd; ++Field) {
1072 if (Field->getDeclName()) {
1073 StructuredList->setInitializedFieldInUnion(*Field);
1074 break;
1075 }
1076 }
1077 return;
1078 }
1079
Douglas Gregor05c13a32009-01-22 00:58:24 +00001080 // If structDecl is a forward declaration, this loop won't do
1081 // anything except look at designated initializers; That's okay,
1082 // because an error should get printed out elsewhere. It might be
1083 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001084 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001085 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001086 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001087 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001088 while (Index < IList->getNumInits()) {
1089 Expr *Init = IList->getInit(Index);
1090
1091 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001092 // If we're not the subobject that matches up with the '{' for
1093 // the designator, we shouldn't be handling the
1094 // designator. Return immediately.
1095 if (!SubobjectIsDesignatorContext)
1096 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001097
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001098 // Handle this designated initializer. Field will be updated to
1099 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001100 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001101 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001102 StructuredList, StructuredIndex,
1103 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001104 hadError = true;
1105
Douglas Gregordfb5e592009-02-12 19:00:39 +00001106 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001107
1108 // Disable check for missing fields when designators are used.
1109 // This matches gcc behaviour.
1110 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001111 continue;
1112 }
1113
1114 if (Field == FieldEnd) {
1115 // We've run out of fields. We're done.
1116 break;
1117 }
1118
Douglas Gregordfb5e592009-02-12 19:00:39 +00001119 // We've already initialized a member of a union. We're done.
1120 if (InitializedSomething && DeclType->isUnionType())
1121 break;
1122
Douglas Gregor44b43212008-12-11 16:49:14 +00001123 // If we've hit the flexible array member at the end, we're done.
1124 if (Field->getType()->isIncompleteArrayType())
1125 break;
1126
Douglas Gregor0bb76892009-01-29 16:53:55 +00001127 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001128 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001129 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001130 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001131 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001132
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001133 InitializedEntity MemberEntity =
1134 InitializedEntity::InitializeMember(*Field, &Entity);
1135 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1136 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001137 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001138
1139 if (DeclType->isUnionType()) {
1140 // Initialize the first field within the union.
1141 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001142 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001143
1144 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001145 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001146
John McCall80639de2010-03-11 19:32:38 +00001147 // Emit warnings for missing struct field initializers.
Douglas Gregor8e198902010-06-18 21:43:10 +00001148 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001149 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1150 // It is possible we have one or more unnamed bitfields remaining.
1151 // Find first (if any) named field and emit warning.
1152 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1153 it != end; ++it) {
1154 if (!it->isUnnamedBitfield()) {
1155 SemaRef.Diag(IList->getSourceRange().getEnd(),
1156 diag::warn_missing_field_initializers) << it->getName();
1157 break;
1158 }
1159 }
1160 }
1161
Mike Stump1eb44332009-09-09 15:08:12 +00001162 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001163 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001164 return;
1165
1166 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001167 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001168 (!isa<InitListExpr>(IList->getInit(Index)) ||
1169 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001170 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001171 diag::err_flexible_array_init_nonempty)
1172 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001173 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001174 << *Field;
1175 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001176 ++Index;
1177 return;
1178 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001179 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001180 diag::ext_flexible_array_init)
1181 << IList->getInit(Index)->getSourceRange().getBegin();
1182 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1183 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001184 }
1185
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001186 InitializedEntity MemberEntity =
1187 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001188
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001189 if (isa<InitListExpr>(IList->getInit(Index)))
1190 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1191 StructuredList, StructuredIndex);
1192 else
1193 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001194 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001195}
Steve Naroff0cca7492008-05-01 22:18:59 +00001196
Douglas Gregor022d13d2010-10-08 20:44:28 +00001197/// \brief Similar to Sema::BuildAnonymousStructUnionMemberPath() but builds a
1198/// relative path and has strict checks.
1199static void BuildRelativeAnonymousStructUnionMemberPath(FieldDecl *Field,
1200 llvm::SmallVectorImpl<FieldDecl *> &Path,
1201 DeclContext *BaseDC) {
1202 Path.push_back(Field);
1203 for (DeclContext *Ctx = Field->getDeclContext();
1204 !Ctx->Equals(BaseDC);
1205 Ctx = Ctx->getParent()) {
1206 ValueDecl *AnonObject =
1207 cast<RecordDecl>(Ctx)->getAnonymousStructOrUnionObject();
1208 FieldDecl *AnonField = cast<FieldDecl>(AnonObject);
1209 Path.push_back(AnonField);
1210 }
1211}
1212
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001213/// \brief Expand a field designator that refers to a member of an
1214/// anonymous struct or union into a series of field designators that
1215/// refers to the field within the appropriate subobject.
1216///
1217/// Field/FieldIndex will be updated to point to the (new)
1218/// currently-designated field.
1219static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001220 DesignatedInitExpr *DIE,
1221 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001222 FieldDecl *Field,
1223 RecordDecl::field_iterator &FieldIter,
Douglas Gregor022d13d2010-10-08 20:44:28 +00001224 unsigned &FieldIndex,
1225 DeclContext *BaseDC) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001226 typedef DesignatedInitExpr::Designator Designator;
1227
1228 // Build the path from the current object to the member of the
1229 // anonymous struct/union (backwards).
1230 llvm::SmallVector<FieldDecl *, 4> Path;
Douglas Gregor022d13d2010-10-08 20:44:28 +00001231 BuildRelativeAnonymousStructUnionMemberPath(Field, Path, BaseDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001233 // Build the replacement designators.
1234 llvm::SmallVector<Designator, 4> Replacements;
1235 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1236 FI = Path.rbegin(), FIEnd = Path.rend();
1237 FI != FIEnd; ++FI) {
1238 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001239 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001240 DIE->getDesignator(DesigIdx)->getDotLoc(),
1241 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1242 else
1243 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1244 SourceLocation()));
1245 Replacements.back().setField(*FI);
1246 }
1247
1248 // Expand the current designator into the set of replacement
1249 // designators, so we have a full subobject path down to where the
1250 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001251 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001252 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001254 // Update FieldIter/FieldIndex;
1255 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001256 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001257 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001258 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001259 FieldIter != FEnd; ++FieldIter) {
1260 if (FieldIter->isUnnamedBitfield())
1261 continue;
1262
1263 if (*FieldIter == Path.back())
1264 return;
1265
1266 ++FieldIndex;
1267 }
1268
1269 assert(false && "Unable to find anonymous struct/union field");
1270}
1271
Douglas Gregor05c13a32009-01-22 00:58:24 +00001272/// @brief Check the well-formedness of a C99 designated initializer.
1273///
1274/// Determines whether the designated initializer @p DIE, which
1275/// resides at the given @p Index within the initializer list @p
1276/// IList, is well-formed for a current object of type @p DeclType
1277/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001278/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001279/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001280///
1281/// @param IList The initializer list in which this designated
1282/// initializer occurs.
1283///
Douglas Gregor71199712009-04-15 04:56:10 +00001284/// @param DIE The designated initializer expression.
1285///
1286/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001287///
1288/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1289/// into which the designation in @p DIE should refer.
1290///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001291/// @param NextField If non-NULL and the first designator in @p DIE is
1292/// a field, this will be set to the field declaration corresponding
1293/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001294///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001295/// @param NextElementIndex If non-NULL and the first designator in @p
1296/// DIE is an array designator or GNU array-range designator, this
1297/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001298///
1299/// @param Index Index into @p IList where the designated initializer
1300/// @p DIE occurs.
1301///
Douglas Gregor4c678342009-01-28 21:54:33 +00001302/// @param StructuredList The initializer list expression that
1303/// describes all of the subobject initializers in the order they'll
1304/// actually be initialized.
1305///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001306/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001307bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001308InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001309 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001310 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001311 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001312 QualType &CurrentObjectType,
1313 RecordDecl::field_iterator *NextField,
1314 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001315 unsigned &Index,
1316 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001317 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001318 bool FinishSubobjectInit,
1319 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001320 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001321 // Check the actual initialization for the designated object type.
1322 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001323
1324 // Temporarily remove the designator expression from the
1325 // initializer list that the child calls see, so that we don't try
1326 // to re-process the designator.
1327 unsigned OldIndex = Index;
1328 IList->setInit(OldIndex, DIE->getInit());
1329
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001330 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001331 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001332
1333 // Restore the designated initializer expression in the syntactic
1334 // form of the initializer list.
1335 if (IList->getInit(OldIndex) != DIE->getInit())
1336 DIE->setInit(IList->getInit(OldIndex));
1337 IList->setInit(OldIndex, DIE);
1338
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001339 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001340 }
1341
Douglas Gregor71199712009-04-15 04:56:10 +00001342 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001343 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001344 "Need a non-designated initializer list to start from");
1345
Douglas Gregor71199712009-04-15 04:56:10 +00001346 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001347 // Determine the structural initializer list that corresponds to the
1348 // current subobject.
1349 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001350 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001351 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001352 SourceRange(D->getStartLocation(),
1353 DIE->getSourceRange().getEnd()));
1354 assert(StructuredList && "Expected a structured initializer list");
1355
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001356 if (D->isFieldDesignator()) {
1357 // C99 6.7.8p7:
1358 //
1359 // If a designator has the form
1360 //
1361 // . identifier
1362 //
1363 // then the current object (defined below) shall have
1364 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001365 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001366 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001367 if (!RT) {
1368 SourceLocation Loc = D->getDotLoc();
1369 if (Loc.isInvalid())
1370 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001371 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1372 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001373 ++Index;
1374 return true;
1375 }
1376
Douglas Gregor4c678342009-01-28 21:54:33 +00001377 // Note: we perform a linear search of the fields here, despite
1378 // the fact that we have a faster lookup method, because we always
1379 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001380 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001381 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001382 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001383 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001384 Field = RT->getDecl()->field_begin(),
1385 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001386 for (; Field != FieldEnd; ++Field) {
1387 if (Field->isUnnamedBitfield())
1388 continue;
1389
Douglas Gregor022d13d2010-10-08 20:44:28 +00001390 if (KnownField && KnownField == *Field)
1391 break;
1392 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 break;
1394
1395 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001396 }
1397
Douglas Gregor4c678342009-01-28 21:54:33 +00001398 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001399 // There was no normal field in the struct with the designated
1400 // name. Perform another lookup for this name, which may find
1401 // something that we can't designate (e.g., a member function),
1402 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001403 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001404 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001405 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001406 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001407 // Name lookup didn't find anything. Determine whether this
1408 // was a typo for another field name.
1409 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1410 Sema::LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001411 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1412 Sema::CTC_NoKeywords) &&
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001413 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001414 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001415 ->Equals(RT->getDecl())) {
1416 SemaRef.Diag(D->getFieldLoc(),
1417 diag::err_field_designator_unknown_suggest)
1418 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001419 << FixItHint::CreateReplacement(D->getFieldLoc(),
1420 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001421 SemaRef.Diag(ReplacementField->getLocation(),
1422 diag::note_previous_decl)
1423 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001424 } else {
1425 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1426 << FieldName << CurrentObjectType;
1427 ++Index;
1428 return true;
1429 }
1430 } else if (!KnownField) {
1431 // Determine whether we found a field at all.
1432 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001433
1434 // Check if ReplacementField is an anonymous field.
1435 if (!ReplacementField)
1436 if (IndirectFieldDecl* IField = dyn_cast<IndirectFieldDecl>(*Lookup.first))
1437 ReplacementField = IField->getAnonField();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001438 }
1439
1440 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001441 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001442 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001443 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001444 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001445 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001446 ++Index;
1447 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001448 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001449
1450 if (!KnownField &&
1451 cast<RecordDecl>((ReplacementField)->getDeclContext())
1452 ->isAnonymousStructOrUnion()) {
1453 // Handle an field designator that refers to a member of an
Douglas Gregor022d13d2010-10-08 20:44:28 +00001454 // anonymous struct or union. This is a C1X feature.
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001455 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1456 ReplacementField,
Douglas Gregor022d13d2010-10-08 20:44:28 +00001457 Field, FieldIndex, RT->getDecl());
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001458 D = DIE->getDesignator(DesigIdx);
1459 } else if (!KnownField) {
1460 // The replacement field comes from typo correction; find it
1461 // in the list of fields.
1462 FieldIndex = 0;
1463 Field = RT->getDecl()->field_begin();
1464 for (; Field != FieldEnd; ++Field) {
1465 if (Field->isUnnamedBitfield())
1466 continue;
1467
1468 if (ReplacementField == *Field ||
1469 Field->getIdentifier() == ReplacementField->getIdentifier())
1470 break;
1471
1472 ++FieldIndex;
1473 }
1474 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001475 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001476
1477 // All of the fields of a union are located at the same place in
1478 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001479 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001480 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001481 StructuredList->setInitializedFieldInUnion(*Field);
1482 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001483
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001484 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001485 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Douglas Gregor4c678342009-01-28 21:54:33 +00001487 // Make sure that our non-designated initializer list has space
1488 // for a subobject corresponding to this field.
1489 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001490 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001491
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001492 // This designator names a flexible array member.
1493 if (Field->getType()->isIncompleteArrayType()) {
1494 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001495 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001496 // We can't designate an object within the flexible array
1497 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001498 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001499 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001500 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001501 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001502 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001503 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001504 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001505 << *Field;
1506 Invalid = true;
1507 }
1508
Chris Lattner9046c222010-10-10 17:49:49 +00001509 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1510 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001511 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001512 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001513 diag::err_flexible_array_init_needs_braces)
1514 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001515 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001516 << *Field;
1517 Invalid = true;
1518 }
1519
1520 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001521 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001522 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001523 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001524 diag::err_flexible_array_init_nonempty)
1525 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001526 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001527 << *Field;
1528 Invalid = true;
1529 }
1530
1531 if (Invalid) {
1532 ++Index;
1533 return true;
1534 }
1535
1536 // Initialize the array.
1537 bool prevHadError = hadError;
1538 unsigned newStructuredIndex = FieldIndex;
1539 unsigned OldIndex = Index;
1540 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001541
1542 InitializedEntity MemberEntity =
1543 InitializedEntity::InitializeMember(*Field, &Entity);
1544 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001545 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001546
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001547 IList->setInit(OldIndex, DIE);
1548 if (hadError && !prevHadError) {
1549 ++Field;
1550 ++FieldIndex;
1551 if (NextField)
1552 *NextField = Field;
1553 StructuredIndex = FieldIndex;
1554 return true;
1555 }
1556 } else {
1557 // Recurse to check later designated subobjects.
1558 QualType FieldType = (*Field)->getType();
1559 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001560
1561 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001562 InitializedEntity::InitializeMember(*Field, &Entity);
1563 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001564 FieldType, 0, 0, Index,
1565 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001566 true, false))
1567 return true;
1568 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001569
1570 // Find the position of the next field to be initialized in this
1571 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001572 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001573 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001574
1575 // If this the first designator, our caller will continue checking
1576 // the rest of this struct/class/union subobject.
1577 if (IsFirstDesignator) {
1578 if (NextField)
1579 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001580 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001581 return false;
1582 }
1583
Douglas Gregor34e79462009-01-28 23:36:17 +00001584 if (!FinishSubobjectInit)
1585 return false;
1586
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001587 // We've already initialized something in the union; we're done.
1588 if (RT->getDecl()->isUnion())
1589 return hadError;
1590
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001591 // Check the remaining fields within this class/struct/union subobject.
1592 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001593
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001594 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001595 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001596 return hadError && !prevHadError;
1597 }
1598
1599 // C99 6.7.8p6:
1600 //
1601 // If a designator has the form
1602 //
1603 // [ constant-expression ]
1604 //
1605 // then the current object (defined below) shall have array
1606 // type and the expression shall be an integer constant
1607 // expression. If the array is of unknown size, any
1608 // nonnegative value is valid.
1609 //
1610 // Additionally, cope with the GNU extension that permits
1611 // designators of the form
1612 //
1613 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001614 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001615 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001616 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001617 << CurrentObjectType;
1618 ++Index;
1619 return true;
1620 }
1621
1622 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001623 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1624 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001625 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001626 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001627 DesignatedEndIndex = DesignatedStartIndex;
1628 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001629 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001630
Mike Stump1eb44332009-09-09 15:08:12 +00001631
1632 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001633 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001634 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001635 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001636 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001637
Chris Lattner3bf68932009-04-25 21:59:05 +00001638 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001639 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001640 }
1641
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001642 if (isa<ConstantArrayType>(AT)) {
1643 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001644 DesignatedStartIndex
1645 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001646 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001647 DesignatedEndIndex
1648 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001649 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1650 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001651 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001652 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001653 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001654 << IndexExpr->getSourceRange();
1655 ++Index;
1656 return true;
1657 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001658 } else {
1659 // Make sure the bit-widths and signedness match.
1660 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001661 DesignatedEndIndex
1662 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001663 else if (DesignatedStartIndex.getBitWidth() <
1664 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001665 DesignatedStartIndex
1666 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001667 DesignatedStartIndex.setIsUnsigned(true);
1668 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001669 }
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Douglas Gregor4c678342009-01-28 21:54:33 +00001671 // Make sure that our non-designated initializer list has space
1672 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001673 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001674 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001675 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001676
Douglas Gregor34e79462009-01-28 23:36:17 +00001677 // Repeatedly perform subobject initializations in the range
1678 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001679
Douglas Gregor34e79462009-01-28 23:36:17 +00001680 // Move to the next designator
1681 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1682 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001683
1684 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001685 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001686
Douglas Gregor34e79462009-01-28 23:36:17 +00001687 while (DesignatedStartIndex <= DesignatedEndIndex) {
1688 // Recurse to check later designated subobjects.
1689 QualType ElementType = AT->getElementType();
1690 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001691
1692 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001693 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001694 ElementType, 0, 0, Index,
1695 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001696 (DesignatedStartIndex == DesignatedEndIndex),
1697 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001698 return true;
1699
1700 // Move to the next index in the array that we'll be initializing.
1701 ++DesignatedStartIndex;
1702 ElementIndex = DesignatedStartIndex.getZExtValue();
1703 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001704
1705 // If this the first designator, our caller will continue checking
1706 // the rest of this array subobject.
1707 if (IsFirstDesignator) {
1708 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001709 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001710 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001711 return false;
1712 }
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Douglas Gregor34e79462009-01-28 23:36:17 +00001714 if (!FinishSubobjectInit)
1715 return false;
1716
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001717 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001718 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001719 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001720 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001721 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001722 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001723}
1724
Douglas Gregor4c678342009-01-28 21:54:33 +00001725// Get the structured initializer list for a subobject of type
1726// @p CurrentObjectType.
1727InitListExpr *
1728InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1729 QualType CurrentObjectType,
1730 InitListExpr *StructuredList,
1731 unsigned StructuredIndex,
1732 SourceRange InitRange) {
1733 Expr *ExistingInit = 0;
1734 if (!StructuredList)
1735 ExistingInit = SyntacticToSemantic[IList];
1736 else if (StructuredIndex < StructuredList->getNumInits())
1737 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Douglas Gregor4c678342009-01-28 21:54:33 +00001739 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1740 return Result;
1741
1742 if (ExistingInit) {
1743 // We are creating an initializer list that initializes the
1744 // subobjects of the current object, but there was already an
1745 // initialization that completely initialized the current
1746 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001747 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001748 // struct X { int a, b; };
1749 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001750 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001751 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1752 // designated initializer re-initializes the whole
1753 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001754 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001755 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001756 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001757 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001758 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001759 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001760 << ExistingInit->getSourceRange();
1761 }
1762
Mike Stump1eb44332009-09-09 15:08:12 +00001763 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001764 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1765 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001766 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001767
Douglas Gregor63982352010-07-13 18:40:04 +00001768 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001769
Douglas Gregorfa219202009-03-20 23:58:33 +00001770 // Pre-allocate storage for the structured initializer list.
1771 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001772 unsigned NumInits = 0;
1773 if (!StructuredList)
1774 NumInits = IList->getNumInits();
1775 else if (Index < IList->getNumInits()) {
1776 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1777 NumInits = SubList->getNumInits();
1778 }
1779
Mike Stump1eb44332009-09-09 15:08:12 +00001780 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001781 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1782 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1783 NumElements = CAType->getSize().getZExtValue();
1784 // Simple heuristic so that we don't allocate a very large
1785 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001786 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001787 NumElements = 0;
1788 }
John McCall183700f2009-09-21 23:43:11 +00001789 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001790 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001791 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001792 RecordDecl *RDecl = RType->getDecl();
1793 if (RDecl->isUnion())
1794 NumElements = 1;
1795 else
Mike Stump1eb44332009-09-09 15:08:12 +00001796 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001797 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001798 }
1799
Douglas Gregor08457732009-03-21 18:13:52 +00001800 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001801 NumElements = IList->getNumInits();
1802
Ted Kremenek709210f2010-04-13 23:39:13 +00001803 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001804
Douglas Gregor4c678342009-01-28 21:54:33 +00001805 // Link this new initializer list into the structured initializer
1806 // lists.
1807 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001808 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001809 else {
1810 Result->setSyntacticForm(IList);
1811 SyntacticToSemantic[IList] = Result;
1812 }
1813
1814 return Result;
1815}
1816
1817/// Update the initializer at index @p StructuredIndex within the
1818/// structured initializer list to the value @p expr.
1819void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1820 unsigned &StructuredIndex,
1821 Expr *expr) {
1822 // No structured initializer list to update
1823 if (!StructuredList)
1824 return;
1825
Ted Kremenek709210f2010-04-13 23:39:13 +00001826 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1827 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001828 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001829 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001830 diag::warn_initializer_overrides)
1831 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001832 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001833 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001834 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001835 << PrevInit->getSourceRange();
1836 }
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Douglas Gregor4c678342009-01-28 21:54:33 +00001838 ++StructuredIndex;
1839}
1840
Douglas Gregor05c13a32009-01-22 00:58:24 +00001841/// Check that the given Index expression is a valid array designator
1842/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001843/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001844/// and produces a reasonable diagnostic if there is a
1845/// failure. Returns true if there was an error, false otherwise. If
1846/// everything went okay, Value will receive the value of the constant
1847/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001848static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001849CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001850 SourceLocation Loc = Index->getSourceRange().getBegin();
1851
1852 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001853 if (S.VerifyIntegerConstantExpression(Index, &Value))
1854 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001855
Chris Lattner3bf68932009-04-25 21:59:05 +00001856 if (Value.isSigned() && Value.isNegative())
1857 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001858 << Value.toString(10) << Index->getSourceRange();
1859
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001860 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001861 return false;
1862}
1863
John McCall60d7b3a2010-08-24 06:29:42 +00001864ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001865 SourceLocation Loc,
1866 bool GNUSyntax,
1867 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001868 typedef DesignatedInitExpr::Designator ASTDesignator;
1869
1870 bool Invalid = false;
1871 llvm::SmallVector<ASTDesignator, 32> Designators;
1872 llvm::SmallVector<Expr *, 32> InitExpressions;
1873
1874 // Build designators and check array designator expressions.
1875 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1876 const Designator &D = Desig.getDesignator(Idx);
1877 switch (D.getKind()) {
1878 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001879 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001880 D.getFieldLoc()));
1881 break;
1882
1883 case Designator::ArrayDesignator: {
1884 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1885 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001886 if (!Index->isTypeDependent() &&
1887 !Index->isValueDependent() &&
1888 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001889 Invalid = true;
1890 else {
1891 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001892 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001893 D.getRBracketLoc()));
1894 InitExpressions.push_back(Index);
1895 }
1896 break;
1897 }
1898
1899 case Designator::ArrayRangeDesignator: {
1900 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1901 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1902 llvm::APSInt StartValue;
1903 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001904 bool StartDependent = StartIndex->isTypeDependent() ||
1905 StartIndex->isValueDependent();
1906 bool EndDependent = EndIndex->isTypeDependent() ||
1907 EndIndex->isValueDependent();
1908 if ((!StartDependent &&
1909 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1910 (!EndDependent &&
1911 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001912 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001913 else {
1914 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001915 if (StartDependent || EndDependent) {
1916 // Nothing to compute.
1917 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001918 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001919 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001920 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001921
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001922 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001923 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001924 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001925 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1926 Invalid = true;
1927 } else {
1928 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001929 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001930 D.getEllipsisLoc(),
1931 D.getRBracketLoc()));
1932 InitExpressions.push_back(StartIndex);
1933 InitExpressions.push_back(EndIndex);
1934 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001935 }
1936 break;
1937 }
1938 }
1939 }
1940
1941 if (Invalid || Init.isInvalid())
1942 return ExprError();
1943
1944 // Clear out the expressions within the designation.
1945 Desig.ClearExprs(*this);
1946
1947 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001948 = DesignatedInitExpr::Create(Context,
1949 Designators.data(), Designators.size(),
1950 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001951 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001952 return Owned(DIE);
1953}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001954
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001955bool Sema::CheckInitList(const InitializedEntity &Entity,
1956 InitListExpr *&InitList, QualType &DeclType) {
1957 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001958 if (!CheckInitList.HadError())
1959 InitList = CheckInitList.getFullyStructuredList();
1960
1961 return CheckInitList.HadError();
1962}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001963
Douglas Gregor20093b42009-12-09 23:02:17 +00001964//===----------------------------------------------------------------------===//
1965// Initialization entity
1966//===----------------------------------------------------------------------===//
1967
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001968InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1969 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001970 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001971{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001972 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1973 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001974 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001975 } else {
1976 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001977 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001978 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001979}
1980
1981InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001982 CXXBaseSpecifier *Base,
1983 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00001984{
1985 InitializedEntity Result;
1986 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00001987 Result.Base = reinterpret_cast<uintptr_t>(Base);
1988 if (IsInheritedVirtualBase)
1989 Result.Base |= 0x01;
1990
Douglas Gregord6542d82009-12-22 15:35:07 +00001991 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001992 return Result;
1993}
1994
Douglas Gregor99a2e602009-12-16 01:38:02 +00001995DeclarationName InitializedEntity::getName() const {
1996 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001997 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001998 if (!VariableOrMember)
1999 return DeclarationName();
2000 // Fall through
2001
2002 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002003 case EK_Member:
2004 return VariableOrMember->getDeclName();
2005
2006 case EK_Result:
2007 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002008 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002009 case EK_Temporary:
2010 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002011 case EK_ArrayElement:
2012 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002013 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002014 return DeclarationName();
2015 }
2016
2017 // Silence GCC warning
2018 return DeclarationName();
2019}
2020
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002021DeclaratorDecl *InitializedEntity::getDecl() const {
2022 switch (getKind()) {
2023 case EK_Variable:
2024 case EK_Parameter:
2025 case EK_Member:
2026 return VariableOrMember;
2027
2028 case EK_Result:
2029 case EK_Exception:
2030 case EK_New:
2031 case EK_Temporary:
2032 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002033 case EK_ArrayElement:
2034 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002035 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002036 return 0;
2037 }
2038
2039 // Silence GCC warning
2040 return 0;
2041}
2042
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002043bool InitializedEntity::allowsNRVO() const {
2044 switch (getKind()) {
2045 case EK_Result:
2046 case EK_Exception:
2047 return LocAndNRVO.NRVO;
2048
2049 case EK_Variable:
2050 case EK_Parameter:
2051 case EK_Member:
2052 case EK_New:
2053 case EK_Temporary:
2054 case EK_Base:
2055 case EK_ArrayElement:
2056 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002057 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002058 break;
2059 }
2060
2061 return false;
2062}
2063
Douglas Gregor20093b42009-12-09 23:02:17 +00002064//===----------------------------------------------------------------------===//
2065// Initialization sequence
2066//===----------------------------------------------------------------------===//
2067
2068void InitializationSequence::Step::Destroy() {
2069 switch (Kind) {
2070 case SK_ResolveAddressOfOverloadedFunction:
2071 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002072 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002073 case SK_CastDerivedToBaseLValue:
2074 case SK_BindReference:
2075 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002076 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002077 case SK_UserConversion:
2078 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002079 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002080 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002081 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002082 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002083 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002084 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002085 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002086 case SK_ObjCObjectConversion:
Douglas Gregor20093b42009-12-09 23:02:17 +00002087 break;
2088
2089 case SK_ConversionSequence:
2090 delete ICS;
2091 }
2092}
2093
Douglas Gregorb70cf442010-03-26 20:14:36 +00002094bool InitializationSequence::isDirectReferenceBinding() const {
2095 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2096}
2097
2098bool InitializationSequence::isAmbiguous() const {
2099 if (getKind() != FailedSequence)
2100 return false;
2101
2102 switch (getFailureKind()) {
2103 case FK_TooManyInitsForReference:
2104 case FK_ArrayNeedsInitList:
2105 case FK_ArrayNeedsInitListOrStringLiteral:
2106 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2107 case FK_NonConstLValueReferenceBindingToTemporary:
2108 case FK_NonConstLValueReferenceBindingToUnrelated:
2109 case FK_RValueReferenceBindingToLValue:
2110 case FK_ReferenceInitDropsQualifiers:
2111 case FK_ReferenceInitFailed:
2112 case FK_ConversionFailed:
2113 case FK_TooManyInitsForScalar:
2114 case FK_ReferenceBindingToInitList:
2115 case FK_InitListBadDestinationType:
2116 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002117 case FK_Incomplete:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002118 return false;
2119
2120 case FK_ReferenceInitOverloadFailed:
2121 case FK_UserConversionOverloadFailed:
2122 case FK_ConstructorOverloadFailed:
2123 return FailedOverloadResult == OR_Ambiguous;
2124 }
2125
2126 return false;
2127}
2128
Douglas Gregord6e44a32010-04-16 22:09:46 +00002129bool InitializationSequence::isConstructorInitialization() const {
2130 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2131}
2132
Douglas Gregor20093b42009-12-09 23:02:17 +00002133void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002134 FunctionDecl *Function,
2135 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002136 Step S;
2137 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2138 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002139 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002140 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002141 Steps.push_back(S);
2142}
2143
2144void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002145 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002146 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002147 switch (VK) {
2148 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2149 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2150 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002151 default: llvm_unreachable("No such category");
2152 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002153 S.Type = BaseType;
2154 Steps.push_back(S);
2155}
2156
2157void InitializationSequence::AddReferenceBindingStep(QualType T,
2158 bool BindingTemporary) {
2159 Step S;
2160 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2161 S.Type = T;
2162 Steps.push_back(S);
2163}
2164
Douglas Gregor523d46a2010-04-18 07:40:54 +00002165void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2166 Step S;
2167 S.Kind = SK_ExtraneousCopyToTemporary;
2168 S.Type = T;
2169 Steps.push_back(S);
2170}
2171
Eli Friedman03981012009-12-11 02:42:07 +00002172void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002173 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002174 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002175 Step S;
2176 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002177 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002178 S.Function.Function = Function;
2179 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002180 Steps.push_back(S);
2181}
2182
2183void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002184 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002185 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002186 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002187 switch (VK) {
2188 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002189 S.Kind = SK_QualificationConversionRValue;
2190 break;
John McCall5baba9d2010-08-25 10:28:54 +00002191 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002192 S.Kind = SK_QualificationConversionXValue;
2193 break;
John McCall5baba9d2010-08-25 10:28:54 +00002194 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002195 S.Kind = SK_QualificationConversionLValue;
2196 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002197 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002198 S.Type = Ty;
2199 Steps.push_back(S);
2200}
2201
2202void InitializationSequence::AddConversionSequenceStep(
2203 const ImplicitConversionSequence &ICS,
2204 QualType T) {
2205 Step S;
2206 S.Kind = SK_ConversionSequence;
2207 S.Type = T;
2208 S.ICS = new ImplicitConversionSequence(ICS);
2209 Steps.push_back(S);
2210}
2211
Douglas Gregord87b61f2009-12-10 17:56:55 +00002212void InitializationSequence::AddListInitializationStep(QualType T) {
2213 Step S;
2214 S.Kind = SK_ListInitialization;
2215 S.Type = T;
2216 Steps.push_back(S);
2217}
2218
Douglas Gregor51c56d62009-12-14 20:49:26 +00002219void
2220InitializationSequence::AddConstructorInitializationStep(
2221 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002222 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002223 QualType T) {
2224 Step S;
2225 S.Kind = SK_ConstructorInitialization;
2226 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002227 S.Function.Function = Constructor;
2228 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002229 Steps.push_back(S);
2230}
2231
Douglas Gregor71d17402009-12-15 00:01:57 +00002232void InitializationSequence::AddZeroInitializationStep(QualType T) {
2233 Step S;
2234 S.Kind = SK_ZeroInitialization;
2235 S.Type = T;
2236 Steps.push_back(S);
2237}
2238
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002239void InitializationSequence::AddCAssignmentStep(QualType T) {
2240 Step S;
2241 S.Kind = SK_CAssignment;
2242 S.Type = T;
2243 Steps.push_back(S);
2244}
2245
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002246void InitializationSequence::AddStringInitStep(QualType T) {
2247 Step S;
2248 S.Kind = SK_StringInit;
2249 S.Type = T;
2250 Steps.push_back(S);
2251}
2252
Douglas Gregor569c3162010-08-07 11:51:51 +00002253void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2254 Step S;
2255 S.Kind = SK_ObjCObjectConversion;
2256 S.Type = T;
2257 Steps.push_back(S);
2258}
2259
Douglas Gregor20093b42009-12-09 23:02:17 +00002260void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2261 OverloadingResult Result) {
2262 SequenceKind = FailedSequence;
2263 this->Failure = Failure;
2264 this->FailedOverloadResult = Result;
2265}
2266
2267//===----------------------------------------------------------------------===//
2268// Attempt initialization
2269//===----------------------------------------------------------------------===//
2270
2271/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002272static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002273 const InitializedEntity &Entity,
2274 const InitializationKind &Kind,
2275 InitListExpr *InitList,
2276 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002277 // FIXME: We only perform rudimentary checking of list
2278 // initializations at this point, then assume that any list
2279 // initialization of an array, aggregate, or scalar will be
Sebastian Redl36c28db2010-06-30 16:41:54 +00002280 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregord87b61f2009-12-10 17:56:55 +00002281 // do all of the necessary checking. C++0x initializer lists will
2282 // force us to perform more checking here.
2283 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2284
Douglas Gregord6542d82009-12-22 15:35:07 +00002285 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002286
2287 // C++ [dcl.init]p13:
2288 // If T is a scalar type, then a declaration of the form
2289 //
2290 // T x = { a };
2291 //
2292 // is equivalent to
2293 //
2294 // T x = a;
2295 if (DestType->isScalarType()) {
2296 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2297 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2298 return;
2299 }
2300
2301 // Assume scalar initialization from a single value works.
2302 } else if (DestType->isAggregateType()) {
2303 // Assume aggregate initialization works.
2304 } else if (DestType->isVectorType()) {
2305 // Assume vector initialization works.
2306 } else if (DestType->isReferenceType()) {
2307 // FIXME: C++0x defines behavior for this.
2308 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2309 return;
2310 } else if (DestType->isRecordType()) {
2311 // FIXME: C++0x defines behavior for this
2312 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2313 }
2314
2315 // Add a general "list initialization" step.
2316 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002317}
2318
2319/// \brief Try a reference initialization that involves calling a conversion
2320/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002321static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2322 const InitializedEntity &Entity,
2323 const InitializationKind &Kind,
2324 Expr *Initializer,
2325 bool AllowRValues,
2326 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002327 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002328 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2329 QualType T1 = cv1T1.getUnqualifiedType();
2330 QualType cv2T2 = Initializer->getType();
2331 QualType T2 = cv2T2.getUnqualifiedType();
2332
2333 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002334 bool ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002335 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002336 T1, T2, DerivedToBase,
2337 ObjCConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002338 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002339 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002340 (void)ObjCConversion;
Douglas Gregor20093b42009-12-09 23:02:17 +00002341
2342 // Build the candidate set directly in the initialization sequence
2343 // structure, so that it will persist if we fail.
2344 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2345 CandidateSet.clear();
2346
2347 // Determine whether we are allowed to call explicit constructors or
2348 // explicit conversion operators.
2349 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2350
2351 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002352 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2353 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002354 // The type we're converting to is a class type. Enumerate its constructors
2355 // to see if there is a suitable conversion.
2356 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002357
Douglas Gregor20093b42009-12-09 23:02:17 +00002358 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002359 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002360 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002361 NamedDecl *D = *Con;
2362 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2363
Douglas Gregor20093b42009-12-09 23:02:17 +00002364 // Find the constructor (which may be a template).
2365 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002366 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002367 if (ConstructorTmpl)
2368 Constructor = cast<CXXConstructorDecl>(
2369 ConstructorTmpl->getTemplatedDecl());
2370 else
John McCall9aa472c2010-03-19 07:35:19 +00002371 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002372
2373 if (!Constructor->isInvalidDecl() &&
2374 Constructor->isConvertingConstructor(AllowExplicit)) {
2375 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002376 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002377 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002378 &Initializer, 1, CandidateSet,
2379 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002380 else
John McCall9aa472c2010-03-19 07:35:19 +00002381 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002382 &Initializer, 1, CandidateSet,
2383 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002384 }
2385 }
2386 }
John McCall572fc622010-08-17 07:23:57 +00002387 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2388 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002389
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002390 const RecordType *T2RecordType = 0;
2391 if ((T2RecordType = T2->getAs<RecordType>()) &&
2392 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002393 // The type we're converting from is a class type, enumerate its conversion
2394 // functions.
2395 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2396
2397 // Determine the type we are converting to. If we are allowed to
2398 // convert to an rvalue, take the type that the destination type
2399 // refers to.
2400 QualType ToType = AllowRValues? cv1T1 : DestType;
2401
John McCalleec51cf2010-01-20 00:46:10 +00002402 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002403 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002404 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2405 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002406 NamedDecl *D = *I;
2407 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2408 if (isa<UsingShadowDecl>(D))
2409 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2410
2411 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2412 CXXConversionDecl *Conv;
2413 if (ConvTemplate)
2414 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2415 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002416 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002417
2418 // If the conversion function doesn't return a reference type,
2419 // it can't be considered for this conversion unless we're allowed to
2420 // consider rvalues.
2421 // FIXME: Do we need to make sure that we only consider conversion
2422 // candidates with reference-compatible results? That might be needed to
2423 // break recursion.
2424 if ((AllowExplicit || !Conv->isExplicit()) &&
2425 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2426 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002427 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002428 ActingDC, Initializer,
Douglas Gregor20093b42009-12-09 23:02:17 +00002429 ToType, CandidateSet);
2430 else
John McCall9aa472c2010-03-19 07:35:19 +00002431 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor692f85c2010-02-26 01:17:27 +00002432 Initializer, ToType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002433 }
2434 }
2435 }
John McCall572fc622010-08-17 07:23:57 +00002436 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2437 return OR_No_Viable_Function;
Douglas Gregor20093b42009-12-09 23:02:17 +00002438
2439 SourceLocation DeclLoc = Initializer->getLocStart();
2440
2441 // Perform overload resolution. If it fails, return the failed result.
2442 OverloadCandidateSet::iterator Best;
2443 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002444 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002445 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002446
Douglas Gregor20093b42009-12-09 23:02:17 +00002447 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002448
2449 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002450 if (isa<CXXConversionDecl>(Function))
2451 T2 = Function->getResultType();
2452 else
2453 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002454
2455 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002456 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002457 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002458
2459 // Determine whether we need to perform derived-to-base or
2460 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002461 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002462 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002463 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002464 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002465 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002466
Douglas Gregor20093b42009-12-09 23:02:17 +00002467 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002468 bool NewObjCConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002469 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregor63982352010-07-13 18:40:04 +00002470 = S.CompareReferenceRelationship(DeclLoc, T1,
2471 T2.getNonLValueExprType(S.Context),
Douglas Gregor569c3162010-08-07 11:51:51 +00002472 NewDerivedToBase, NewObjCConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002473 if (NewRefRelationship == Sema::Ref_Incompatible) {
2474 // If the type we've converted to is not reference-related to the
2475 // type we're looking for, then there is another conversion step
2476 // we need to perform to produce a temporary of the right type
2477 // that we'll be binding to.
2478 ImplicitConversionSequence ICS;
2479 ICS.setStandard();
2480 ICS.Standard = Best->FinalConversion;
2481 T2 = ICS.Standard.getToType(2);
2482 Sequence.AddConversionSequenceStep(ICS, T2);
2483 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002484 Sequence.AddDerivedToBaseCastStep(
2485 S.Context.getQualifiedType(T1,
2486 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002487 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002488 else if (NewObjCConversion)
2489 Sequence.AddObjCObjectConversionStep(
2490 S.Context.getQualifiedType(T1,
2491 T2.getNonReferenceType().getQualifiers()));
2492
Douglas Gregor20093b42009-12-09 23:02:17 +00002493 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002494 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00002495
2496 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2497 return OR_Success;
2498}
2499
Sebastian Redl4680bf22010-06-30 18:13:39 +00002500/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor20093b42009-12-09 23:02:17 +00002501static void TryReferenceInitialization(Sema &S,
2502 const InitializedEntity &Entity,
2503 const InitializationKind &Kind,
2504 Expr *Initializer,
2505 InitializationSequence &Sequence) {
2506 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002507
Douglas Gregord6542d82009-12-22 15:35:07 +00002508 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002509 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002510 Qualifiers T1Quals;
2511 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002512 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002513 Qualifiers T2Quals;
2514 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002515 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002516
Douglas Gregor20093b42009-12-09 23:02:17 +00002517 // If the initializer is the address of an overloaded function, try
2518 // to resolve the overloaded function. If all goes well, T2 is the
2519 // type of the resulting function.
2520 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002521 DeclAccessPair Found;
Douglas Gregor3afb9772010-11-08 15:20:28 +00002522 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2523 T1,
2524 false,
2525 Found)) {
2526 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2527 cv2T2 = Fn->getType();
2528 T2 = cv2T2.getUnqualifiedType();
2529 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002530 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2531 return;
2532 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002533 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002534
Douglas Gregor20093b42009-12-09 23:02:17 +00002535 // Compute some basic properties of the types and the initializer.
2536 bool isLValueRef = DestType->isLValueReferenceType();
2537 bool isRValueRef = !isLValueRef;
2538 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002539 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002540 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002541 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002542 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2543 ObjCConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002544
Douglas Gregor20093b42009-12-09 23:02:17 +00002545 // C++0x [dcl.init.ref]p5:
2546 // A reference to type "cv1 T1" is initialized by an expression of type
2547 // "cv2 T2" as follows:
2548 //
2549 // - If the reference is an lvalue reference and the initializer
2550 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002551 // Note the analogous bullet points for rvlaue refs to functions. Because
2552 // there are no function rvalues in C++, rvalue refs to functions are treated
2553 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002554 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002555 bool T1Function = T1->isFunctionType();
2556 if (isLValueRef || T1Function) {
2557 if (InitCategory.isLValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2559 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2560 // reference-compatible with "cv2 T2," or
2561 //
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002562 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002563 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002564 // can occur. However, we do pay attention to whether it is a bit-field
2565 // to decide whether we're actually binding to a temporary created from
2566 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002567 if (DerivedToBase)
2568 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002569 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002570 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002571 else if (ObjCConversion)
2572 Sequence.AddObjCObjectConversionStep(
2573 S.Context.getQualifiedType(T1, T2Quals));
2574
Chandler Carruth5535c382010-01-12 20:32:25 +00002575 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002576 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002577 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002578 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002579 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002580 return;
2581 }
2582
2583 // - has a class type (i.e., T2 is a class type), where T1 is not
2584 // reference-related to T2, and can be implicitly converted to an
2585 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2586 // with "cv3 T3" (this conversion is selected by enumerating the
2587 // applicable conversion functions (13.3.1.6) and choosing the best
2588 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002589 // If we have an rvalue ref to function type here, the rhs must be
2590 // an rvalue.
2591 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2592 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002593 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2594 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002595 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002596 Sequence);
2597 if (ConvOvlResult == OR_Success)
2598 return;
John McCall1d318332010-01-12 00:44:57 +00002599 if (ConvOvlResult != OR_No_Viable_Function) {
2600 Sequence.SetOverloadFailure(
2601 InitializationSequence::FK_ReferenceInitOverloadFailed,
2602 ConvOvlResult);
2603 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002604 }
2605 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002606
Douglas Gregor20093b42009-12-09 23:02:17 +00002607 // - Otherwise, the reference shall be an lvalue reference to a
2608 // non-volatile const type (i.e., cv1 shall be const), or the reference
2609 // shall be an rvalue reference and the initializer expression shall
Sebastian Redl4680bf22010-06-30 18:13:39 +00002610 // be an rvalue or have a function type.
2611 // We handled the function type stuff above.
Douglas Gregoref06e242010-01-29 19:39:15 +00002612 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redl4680bf22010-06-30 18:13:39 +00002613 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002614 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2615 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2616 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002617 Sequence.SetOverloadFailure(
2618 InitializationSequence::FK_ReferenceInitOverloadFailed,
2619 ConvOvlResult);
2620 else if (isLValueRef)
Sebastian Redl4680bf22010-06-30 18:13:39 +00002621 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002622 ? (RefRelationship == Sema::Ref_Related
2623 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2624 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2625 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2626 else
2627 Sequence.SetFailed(
2628 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002629
Douglas Gregor20093b42009-12-09 23:02:17 +00002630 return;
2631 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002632
2633 // - [If T1 is not a function type], if T2 is a class type and
2634 if (!T1Function && T2->isRecordType()) {
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002635 bool isXValue = InitCategory.isXValue();
Douglas Gregor20093b42009-12-09 23:02:17 +00002636 // - the initializer expression is an rvalue and "cv1 T1" is
2637 // reference-compatible with "cv2 T2", or
Sebastian Redl4680bf22010-06-30 18:13:39 +00002638 if (InitCategory.isRValue() &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002639 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002640 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2641 // compiler the freedom to perform a copy here or bind to the
2642 // object, while C++0x requires that we bind directly to the
2643 // object. Hence, we always bind to the object without making an
2644 // extra copy. However, in C++03 requires that we check for the
2645 // presence of a suitable copy constructor:
2646 //
2647 // The constructor that would be used to make the copy shall
2648 // be callable whether or not the copy is actually done.
2649 if (!S.getLangOptions().CPlusPlus0x)
2650 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2651
Douglas Gregor20093b42009-12-09 23:02:17 +00002652 if (DerivedToBase)
2653 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002654 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002655 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002656 else if (ObjCConversion)
2657 Sequence.AddObjCObjectConversionStep(
2658 S.Context.getQualifiedType(T1, T2Quals));
2659
Chandler Carruth5535c382010-01-12 20:32:25 +00002660 if (T1Quals != T2Quals)
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002661 Sequence.AddQualificationConversionStep(cv1T1,
John McCall5baba9d2010-08-25 10:28:54 +00002662 isXValue ? VK_XValue : VK_RValue);
Sebastian Redl66d0acd2010-07-26 17:52:21 +00002663 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00002664 return;
2665 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002666
Douglas Gregor20093b42009-12-09 23:02:17 +00002667 // - T1 is not reference-related to T2 and the initializer expression
2668 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2669 // conversion is selected by enumerating the applicable conversion
2670 // functions (13.3.1.6) and choosing the best one through overload
2671 // resolution (13.3)),
2672 if (RefRelationship == Sema::Ref_Incompatible) {
2673 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2674 Kind, Initializer,
2675 /*AllowRValues=*/true,
2676 Sequence);
2677 if (ConvOvlResult)
2678 Sequence.SetOverloadFailure(
2679 InitializationSequence::FK_ReferenceInitOverloadFailed,
2680 ConvOvlResult);
2681
2682 return;
2683 }
2684
2685 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2686 return;
2687 }
2688
2689 // - If the initializer expression is an rvalue, with T2 an array type,
2690 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2691 // is bound to the object represented by the rvalue (see 3.10).
2692 // FIXME: How can an array type be reference-compatible with anything?
2693 // Don't we mean the element types of T1 and T2?
2694
2695 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2696 // from the initializer expression using the rules for a non-reference
2697 // copy initialization (8.5). The reference is then bound to the
2698 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00002699
Douglas Gregor20093b42009-12-09 23:02:17 +00002700 // Determine whether we are allowed to call explicit constructors or
2701 // explicit conversion operators.
2702 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00002703
2704 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2705
2706 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2707 /*SuppressUserConversions*/ false,
2708 AllowExplicit,
2709 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002710 // FIXME: Use the conversion function set stored in ICS to turn
2711 // this into an overloading ambiguity diagnostic. However, we need
2712 // to keep that set as an OverloadCandidateSet rather than as some
2713 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002714 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2715 Sequence.SetOverloadFailure(
2716 InitializationSequence::FK_ReferenceInitOverloadFailed,
2717 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00002718 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2719 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002720 else
2721 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002722 return;
2723 }
2724
2725 // [...] If T1 is reference-related to T2, cv1 must be the
2726 // same cv-qualification as, or greater cv-qualification
2727 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002728 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2729 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002730 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002731 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002732 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2733 return;
2734 }
2735
Douglas Gregor20093b42009-12-09 23:02:17 +00002736 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2737 return;
2738}
2739
2740/// \brief Attempt character array initialization from a string literal
2741/// (C++ [dcl.init.string], C99 6.7.8).
2742static void TryStringLiteralInitialization(Sema &S,
2743 const InitializedEntity &Entity,
2744 const InitializationKind &Kind,
2745 Expr *Initializer,
2746 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002747 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002748 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002749}
2750
Douglas Gregor20093b42009-12-09 23:02:17 +00002751/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2752/// enumerates the constructors of the initialized entity and performs overload
2753/// resolution to select the best.
2754static void TryConstructorInitialization(Sema &S,
2755 const InitializedEntity &Entity,
2756 const InitializationKind &Kind,
2757 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002758 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002759 InitializationSequence &Sequence) {
Douglas Gregor2f599792010-04-02 18:24:57 +00002760 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002761
2762 // Build the candidate set directly in the initialization sequence
2763 // structure, so that it will persist if we fail.
2764 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2765 CandidateSet.clear();
2766
2767 // Determine whether we are allowed to call explicit constructors or
2768 // explicit conversion operators.
2769 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2770 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00002771 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002772
2773 // The type we're constructing needs to be complete.
2774 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002775 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002776 return;
2777 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002778
2779 // The type we're converting to is a class type. Enumerate its constructors
2780 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002781 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2782 assert(DestRecordType && "Constructor initialization requires record type");
2783 CXXRecordDecl *DestRecordDecl
2784 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2785
Douglas Gregor51c56d62009-12-14 20:49:26 +00002786 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002787 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002788 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002789 NamedDecl *D = *Con;
2790 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002791 bool SuppressUserConversions = false;
2792
Douglas Gregor51c56d62009-12-14 20:49:26 +00002793 // Find the constructor (which may be a template).
2794 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002795 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002796 if (ConstructorTmpl)
2797 Constructor = cast<CXXConstructorDecl>(
2798 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00002799 else {
John McCall9aa472c2010-03-19 07:35:19 +00002800 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00002801
2802 // If we're performing copy initialization using a copy constructor, we
2803 // suppress user-defined conversions on the arguments.
2804 // FIXME: Move constructors?
2805 if (Kind.getKind() == InitializationKind::IK_Copy &&
2806 Constructor->isCopyConstructor())
2807 SuppressUserConversions = true;
2808 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00002809
2810 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002811 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002812 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002813 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002814 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00002815 Args, NumArgs, CandidateSet,
2816 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002817 else
John McCall9aa472c2010-03-19 07:35:19 +00002818 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00002819 Args, NumArgs, CandidateSet,
2820 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002821 }
2822 }
2823
2824 SourceLocation DeclLoc = Kind.getLocation();
2825
2826 // Perform overload resolution. If it fails, return the failed result.
2827 OverloadCandidateSet::iterator Best;
2828 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00002829 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002830 Sequence.SetOverloadFailure(
2831 InitializationSequence::FK_ConstructorOverloadFailed,
2832 Result);
2833 return;
2834 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002835
2836 // C++0x [dcl.init]p6:
2837 // If a program calls for the default initialization of an object
2838 // of a const-qualified type T, T shall be a class type with a
2839 // user-provided default constructor.
2840 if (Kind.getKind() == InitializationKind::IK_Default &&
2841 Entity.getType().isConstQualified() &&
2842 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2843 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2844 return;
2845 }
2846
Douglas Gregor51c56d62009-12-14 20:49:26 +00002847 // Add the constructor initialization step. Any cv-qualification conversion is
2848 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00002849 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002850 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00002851 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002852 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002853}
2854
Douglas Gregor71d17402009-12-15 00:01:57 +00002855/// \brief Attempt value initialization (C++ [dcl.init]p7).
2856static void TryValueInitialization(Sema &S,
2857 const InitializedEntity &Entity,
2858 const InitializationKind &Kind,
2859 InitializationSequence &Sequence) {
2860 // C++ [dcl.init]p5:
2861 //
2862 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002863 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002864
2865 // -- if T is an array type, then each element is value-initialized;
2866 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2867 T = AT->getElementType();
2868
2869 if (const RecordType *RT = T->getAs<RecordType>()) {
2870 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2871 // -- if T is a class type (clause 9) with a user-declared
2872 // constructor (12.1), then the default constructor for T is
2873 // called (and the initialization is ill-formed if T has no
2874 // accessible default constructor);
2875 //
2876 // FIXME: we really want to refer to a single subobject of the array,
2877 // but Entity doesn't have a way to capture that (yet).
2878 if (ClassDecl->hasUserDeclaredConstructor())
2879 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2880
Douglas Gregor16006c92009-12-16 18:50:27 +00002881 // -- if T is a (possibly cv-qualified) non-union class type
2882 // without a user-provided constructor, then the object is
2883 // zero-initialized and, if T’s implicitly-declared default
2884 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002885 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00002886 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002887 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002888 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2889 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002890 }
2891 }
2892
Douglas Gregord6542d82009-12-22 15:35:07 +00002893 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002894 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2895}
2896
Douglas Gregor99a2e602009-12-16 01:38:02 +00002897/// \brief Attempt default initialization (C++ [dcl.init]p6).
2898static void TryDefaultInitialization(Sema &S,
2899 const InitializedEntity &Entity,
2900 const InitializationKind &Kind,
2901 InitializationSequence &Sequence) {
2902 assert(Kind.getKind() == InitializationKind::IK_Default);
2903
2904 // C++ [dcl.init]p6:
2905 // To default-initialize an object of type T means:
2906 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002907 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002908 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2909 DestType = Array->getElementType();
2910
2911 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2912 // constructor for T is called (and the initialization is ill-formed if
2913 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00002914 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00002915 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2916 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002917 }
2918
2919 // - otherwise, no initialization is performed.
2920 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2921
2922 // If a program calls for the default initialization of an object of
2923 // a const-qualified type T, T shall be a class type with a user-provided
2924 // default constructor.
Douglas Gregor60c93c92010-02-09 07:26:29 +00002925 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor99a2e602009-12-16 01:38:02 +00002926 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2927}
2928
Douglas Gregor20093b42009-12-09 23:02:17 +00002929/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2930/// which enumerates all conversion functions and performs overload resolution
2931/// to select the best.
2932static void TryUserDefinedConversion(Sema &S,
2933 const InitializedEntity &Entity,
2934 const InitializationKind &Kind,
2935 Expr *Initializer,
2936 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002937 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2938
Douglas Gregord6542d82009-12-22 15:35:07 +00002939 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002940 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2941 QualType SourceType = Initializer->getType();
2942 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2943 "Must have a class type to perform a user-defined conversion");
2944
2945 // Build the candidate set directly in the initialization sequence
2946 // structure, so that it will persist if we fail.
2947 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2948 CandidateSet.clear();
2949
2950 // Determine whether we are allowed to call explicit constructors or
2951 // explicit conversion operators.
2952 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2953
2954 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2955 // The type we're converting to is a class type. Enumerate its constructors
2956 // to see if there is a suitable conversion.
2957 CXXRecordDecl *DestRecordDecl
2958 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2959
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002960 // Try to complete the type we're converting to.
2961 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002962 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002963 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002964 Con != ConEnd; ++Con) {
2965 NamedDecl *D = *Con;
2966 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00002967
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002968 // Find the constructor (which may be a template).
2969 CXXConstructorDecl *Constructor = 0;
2970 FunctionTemplateDecl *ConstructorTmpl
2971 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00002972 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002973 Constructor = cast<CXXConstructorDecl>(
2974 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00002975 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002976 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002977
2978 if (!Constructor->isInvalidDecl() &&
2979 Constructor->isConvertingConstructor(AllowExplicit)) {
2980 if (ConstructorTmpl)
2981 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2982 /*ExplicitArgs*/ 0,
2983 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002984 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002985 else
2986 S.AddOverloadCandidate(Constructor, FoundDecl,
2987 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00002988 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00002989 }
2990 }
2991 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002992 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002993
2994 SourceLocation DeclLoc = Initializer->getLocStart();
2995
Douglas Gregor4a520a22009-12-14 17:27:33 +00002996 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2997 // The type we're converting from is a class type, enumerate its conversion
2998 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002999
Eli Friedman33c2da92009-12-20 22:12:03 +00003000 // We can only enumerate the conversion functions for a complete type; if
3001 // the type isn't complete, simply skip this step.
3002 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3003 CXXRecordDecl *SourceRecordDecl
3004 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003005
John McCalleec51cf2010-01-20 00:46:10 +00003006 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003007 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003008 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00003009 E = Conversions->end();
3010 I != E; ++I) {
3011 NamedDecl *D = *I;
3012 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3013 if (isa<UsingShadowDecl>(D))
3014 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3015
3016 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3017 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003018 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003019 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003020 else
John McCall32daa422010-03-31 01:36:47 +00003021 Conv = cast<CXXConversionDecl>(D);
Eli Friedman33c2da92009-12-20 22:12:03 +00003022
3023 if (AllowExplicit || !Conv->isExplicit()) {
3024 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003025 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003026 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003027 CandidateSet);
3028 else
John McCall9aa472c2010-03-19 07:35:19 +00003029 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003030 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003031 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003032 }
3033 }
3034 }
3035
Douglas Gregor4a520a22009-12-14 17:27:33 +00003036 // Perform overload resolution. If it fails, return the failed result.
3037 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003038 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003039 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003040 Sequence.SetOverloadFailure(
3041 InitializationSequence::FK_UserConversionOverloadFailed,
3042 Result);
3043 return;
3044 }
John McCall1d318332010-01-12 00:44:57 +00003045
Douglas Gregor4a520a22009-12-14 17:27:33 +00003046 FunctionDecl *Function = Best->Function;
3047
3048 if (isa<CXXConstructorDecl>(Function)) {
3049 // Add the user-defined conversion step. Any cv-qualification conversion is
3050 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003051 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003052 return;
3053 }
3054
3055 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003056 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003057 if (ConvType->getAs<RecordType>()) {
3058 // If we're converting to a class type, there may be an copy if
3059 // the resulting temporary object (possible to create an object of
3060 // a base class type). That copy is not a separate conversion, so
3061 // we just make a note of the actual destination type (possibly a
3062 // base class of the type returned by the conversion function) and
3063 // let the user-defined conversion step handle the conversion.
3064 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3065 return;
3066 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003067
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003068 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3069
3070 // If the conversion following the call to the conversion function
3071 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003072 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3073 Best->FinalConversion.Third) {
3074 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003075 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003076 ICS.Standard = Best->FinalConversion;
3077 Sequence.AddConversionSequenceStep(ICS, DestType);
3078 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003079}
3080
Douglas Gregor20093b42009-12-09 23:02:17 +00003081InitializationSequence::InitializationSequence(Sema &S,
3082 const InitializedEntity &Entity,
3083 const InitializationKind &Kind,
3084 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003085 unsigned NumArgs)
3086 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003087 ASTContext &Context = S.Context;
3088
3089 // C++0x [dcl.init]p16:
3090 // The semantics of initializers are as follows. The destination type is
3091 // the type of the object or reference being initialized and the source
3092 // type is the type of the initializer expression. The source type is not
3093 // defined when the initializer is a braced-init-list or when it is a
3094 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00003095 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003096
3097 if (DestType->isDependentType() ||
3098 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3099 SequenceKind = DependentSequence;
3100 return;
3101 }
3102
John McCall241d5582010-12-07 22:54:16 +00003103 for (unsigned I = 0; I != NumArgs; ++I)
3104 if (Args[I]->getObjectKind() == OK_ObjCProperty)
3105 S.ConvertPropertyForRValue(Args[I]);
3106
Douglas Gregor20093b42009-12-09 23:02:17 +00003107 QualType SourceType;
3108 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003109 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003110 Initializer = Args[0];
3111 if (!isa<InitListExpr>(Initializer))
3112 SourceType = Initializer->getType();
3113 }
3114
3115 // - If the initializer is a braced-init-list, the object is
3116 // list-initialized (8.5.4).
3117 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3118 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003119 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003120 }
3121
3122 // - If the destination type is a reference type, see 8.5.3.
3123 if (DestType->isReferenceType()) {
3124 // C++0x [dcl.init.ref]p1:
3125 // A variable declared to be a T& or T&&, that is, "reference to type T"
3126 // (8.3.2), shall be initialized by an object, or function, of type T or
3127 // by an object that can be converted into a T.
3128 // (Therefore, multiple arguments are not permitted.)
3129 if (NumArgs != 1)
3130 SetFailed(FK_TooManyInitsForReference);
3131 else
3132 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3133 return;
3134 }
3135
3136 // - If the destination type is an array of characters, an array of
3137 // char16_t, an array of char32_t, or an array of wchar_t, and the
3138 // initializer is a string literal, see 8.5.2.
3139 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3140 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3141 return;
3142 }
3143
3144 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003145 if (Kind.getKind() == InitializationKind::IK_Value ||
3146 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003147 TryValueInitialization(S, Entity, Kind, *this);
3148 return;
3149 }
3150
Douglas Gregor99a2e602009-12-16 01:38:02 +00003151 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003152 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003153 TryDefaultInitialization(S, Entity, Kind, *this);
3154 return;
3155 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003156
Douglas Gregor20093b42009-12-09 23:02:17 +00003157 // - Otherwise, if the destination type is an array, the program is
3158 // ill-formed.
3159 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3160 if (AT->getElementType()->isAnyCharacterType())
3161 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3162 else
3163 SetFailed(FK_ArrayNeedsInitList);
3164
3165 return;
3166 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003167
3168 // Handle initialization in C
3169 if (!S.getLangOptions().CPlusPlus) {
3170 setSequenceKind(CAssignment);
3171 AddCAssignmentStep(DestType);
3172 return;
3173 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003174
3175 // - If the destination type is a (possibly cv-qualified) class type:
3176 if (DestType->isRecordType()) {
3177 // - If the initialization is direct-initialization, or if it is
3178 // copy-initialization where the cv-unqualified version of the
3179 // source type is the same class as, or a derived class of, the
3180 // class of the destination, constructors are considered. [...]
3181 if (Kind.getKind() == InitializationKind::IK_Direct ||
3182 (Kind.getKind() == InitializationKind::IK_Copy &&
3183 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3184 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00003185 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00003186 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003187 // - Otherwise (i.e., for the remaining copy-initialization cases),
3188 // user-defined conversion sequences that can convert from the source
3189 // type to the destination type or (when a conversion function is
3190 // used) to a derived class thereof are enumerated as described in
3191 // 13.3.1.4, and the best one is chosen through overload resolution
3192 // (13.3).
3193 else
3194 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3195 return;
3196 }
3197
Douglas Gregor99a2e602009-12-16 01:38:02 +00003198 if (NumArgs > 1) {
3199 SetFailed(FK_TooManyInitsForScalar);
3200 return;
3201 }
3202 assert(NumArgs == 1 && "Zero-argument case handled above");
3203
Douglas Gregor20093b42009-12-09 23:02:17 +00003204 // - Otherwise, if the source type is a (possibly cv-qualified) class
3205 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003206 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003207 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3208 return;
3209 }
3210
3211 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003212 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003213 // conversions (Clause 4) will be used, if necessary, to convert the
3214 // initializer expression to the cv-unqualified version of the
3215 // destination type; no user-defined conversions are considered.
John McCall369371c2010-06-04 02:29:22 +00003216 if (S.TryImplicitConversion(*this, Entity, Initializer,
3217 /*SuppressUserConversions*/ true,
3218 /*AllowExplicitConversions*/ false,
3219 /*InOverloadResolution*/ false))
Douglas Gregor8e960432010-11-08 03:40:48 +00003220 {
John McCall241d5582010-12-07 22:54:16 +00003221 if (Initializer->getType() == Context.OverloadTy)
Douglas Gregor8e960432010-11-08 03:40:48 +00003222 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3223 else
3224 SetFailed(InitializationSequence::FK_ConversionFailed);
3225 }
John McCall369371c2010-06-04 02:29:22 +00003226 else
3227 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00003228}
3229
3230InitializationSequence::~InitializationSequence() {
3231 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3232 StepEnd = Steps.end();
3233 Step != StepEnd; ++Step)
3234 Step->Destroy();
3235}
3236
3237//===----------------------------------------------------------------------===//
3238// Perform initialization
3239//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003240static Sema::AssignmentAction
3241getAssignmentAction(const InitializedEntity &Entity) {
3242 switch(Entity.getKind()) {
3243 case InitializedEntity::EK_Variable:
3244 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003245 case InitializedEntity::EK_Exception:
3246 case InitializedEntity::EK_Base:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003247 return Sema::AA_Initializing;
3248
3249 case InitializedEntity::EK_Parameter:
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003250 if (Entity.getDecl() &&
3251 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3252 return Sema::AA_Sending;
3253
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003254 return Sema::AA_Passing;
3255
3256 case InitializedEntity::EK_Result:
3257 return Sema::AA_Returning;
3258
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003259 case InitializedEntity::EK_Temporary:
3260 // FIXME: Can we tell apart casting vs. converting?
3261 return Sema::AA_Casting;
3262
3263 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003264 case InitializedEntity::EK_ArrayElement:
3265 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003266 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003267 return Sema::AA_Initializing;
3268 }
3269
3270 return Sema::AA_Converting;
3271}
3272
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003273/// \brief Whether we should binding a created object as a temporary when
3274/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003275static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003276 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003277 case InitializedEntity::EK_ArrayElement:
3278 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003279 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003280 case InitializedEntity::EK_New:
3281 case InitializedEntity::EK_Variable:
3282 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003283 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003284 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003285 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003286 return false;
3287
3288 case InitializedEntity::EK_Parameter:
3289 case InitializedEntity::EK_Temporary:
3290 return true;
3291 }
3292
3293 llvm_unreachable("missed an InitializedEntity kind?");
3294}
3295
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003296/// \brief Whether the given entity, when initialized with an object
3297/// created for that initialization, requires destruction.
3298static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3299 switch (Entity.getKind()) {
3300 case InitializedEntity::EK_Member:
3301 case InitializedEntity::EK_Result:
3302 case InitializedEntity::EK_New:
3303 case InitializedEntity::EK_Base:
3304 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003305 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003306 return false;
3307
3308 case InitializedEntity::EK_Variable:
3309 case InitializedEntity::EK_Parameter:
3310 case InitializedEntity::EK_Temporary:
3311 case InitializedEntity::EK_ArrayElement:
3312 case InitializedEntity::EK_Exception:
3313 return true;
3314 }
3315
3316 llvm_unreachable("missed an InitializedEntity kind?");
3317}
3318
Douglas Gregor523d46a2010-04-18 07:40:54 +00003319/// \brief Make a (potentially elidable) temporary copy of the object
3320/// provided by the given initializer by calling the appropriate copy
3321/// constructor.
3322///
3323/// \param S The Sema object used for type-checking.
3324///
3325/// \param T The type of the temporary object, which must either by
3326/// the type of the initializer expression or a superclass thereof.
3327///
3328/// \param Enter The entity being initialized.
3329///
3330/// \param CurInit The initializer expression.
3331///
3332/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3333/// is permitted in C++03 (but not C++0x) when binding a reference to
3334/// an rvalue.
3335///
3336/// \returns An expression that copies the initializer expression into
3337/// a temporary object, or an error expression if a copy could not be
3338/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003339static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003340 QualType T,
3341 const InitializedEntity &Entity,
3342 ExprResult CurInit,
3343 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003344 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003345 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor2f599792010-04-02 18:24:57 +00003346 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003347 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003348 Class = cast<CXXRecordDecl>(Record->getDecl());
3349 if (!Class)
3350 return move(CurInit);
3351
3352 // C++0x [class.copy]p34:
3353 // When certain criteria are met, an implementation is allowed to
3354 // omit the copy/move construction of a class object, even if the
3355 // copy/move constructor and/or destructor for the object have
3356 // side effects. [...]
3357 // - when a temporary class object that has not been bound to a
3358 // reference (12.2) would be copied/moved to a class object
3359 // with the same cv-unqualified type, the copy/move operation
3360 // can be omitted by constructing the temporary object
3361 // directly into the target of the omitted copy/move
3362 //
3363 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003364 // elision for return statements and throw expressions are handled as part
3365 // of constructor initialization, while copy elision for exception handlers
3366 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003367 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003368 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003369 switch (Entity.getKind()) {
3370 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003371 Loc = Entity.getReturnLoc();
3372 break;
3373
3374 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003375 Loc = Entity.getThrowLoc();
3376 break;
3377
3378 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003379 Loc = Entity.getDecl()->getLocation();
3380 break;
3381
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003382 case InitializedEntity::EK_ArrayElement:
3383 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003384 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003385 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003386 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003387 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003388 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003389 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003390 Loc = CurInitExpr->getLocStart();
3391 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003392 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003393
3394 // Make sure that the type we are copying is complete.
3395 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3396 return move(CurInit);
3397
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003398 // Perform overload resolution using the class's copy constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003399 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003400 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003401 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003402 Con != ConEnd; ++Con) {
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003403 // Only consider copy constructors and constructor templates. Per
3404 // C++0x [dcl.init]p16, second bullet to class types, this
3405 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003406 CXXConstructorDecl *Constructor = 0;
3407
3408 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
3409 // Handle copy constructors, only.
3410 if (!Constructor || Constructor->isInvalidDecl() ||
3411 !Constructor->isCopyConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003412 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003413 continue;
3414
3415 DeclAccessPair FoundDecl
3416 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3417 S.AddOverloadCandidate(Constructor, FoundDecl,
3418 &CurInitExpr, 1, CandidateSet);
3419 continue;
3420 }
3421
3422 // Handle constructor templates.
3423 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3424 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003425 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003426
Douglas Gregor6493cc52010-11-08 17:16:59 +00003427 Constructor = cast<CXXConstructorDecl>(
3428 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003429 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003430 continue;
3431
3432 // FIXME: Do we need to limit this to copy-constructor-like
3433 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003434 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003435 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3436 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3437 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003438 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003439
3440 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00003441 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003442 case OR_Success:
3443 break;
3444
3445 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003446 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3447 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3448 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003449 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003450 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003451 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003452 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003453 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003454 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003455
3456 case OR_Ambiguous:
3457 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003458 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003459 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003460 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00003461 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003462
3463 case OR_Deleted:
3464 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003465 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003466 << CurInitExpr->getSourceRange();
3467 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3468 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00003469 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003470 }
3471
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003472 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00003473 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003474 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003475
Anders Carlsson9a68a672010-04-21 18:47:17 +00003476 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003477 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00003478
3479 if (IsExtraneousCopy) {
3480 // If this is a totally extraneous copy for C++03 reference
3481 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00003482 // expression. We don't generate an (elided) copy operation here
3483 // because doing so would require us to pass down a flag to avoid
3484 // infinite recursion, where each step adds another extraneous,
3485 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00003486
Douglas Gregor2559a702010-04-18 07:57:34 +00003487 // Instantiate the default arguments of any extra parameters in
3488 // the selected copy constructor, as if we were going to create a
3489 // proper call to the copy constructor.
3490 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3491 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3492 if (S.RequireCompleteType(Loc, Parm->getType(),
3493 S.PDiag(diag::err_call_incomplete_argument)))
3494 break;
3495
3496 // Build the default argument expression; we don't actually care
3497 // if this succeeds or not, because this routine will complain
3498 // if there was a problem.
3499 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3500 }
3501
Douglas Gregor523d46a2010-04-18 07:40:54 +00003502 return S.Owned(CurInitExpr);
3503 }
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003504
3505 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00003506 // constructor call (we might have derived-to-base conversions, or
3507 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00003508 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003509 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003510 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003511
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003512 // Actually perform the constructor call.
3513 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00003514 move_arg(ConstructorArgs),
3515 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003516 CXXConstructExpr::CK_Complete,
3517 SourceRange());
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003518
3519 // If we're supposed to bind temporaries, do so.
3520 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3521 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3522 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003523}
Douglas Gregor20093b42009-12-09 23:02:17 +00003524
Douglas Gregora41a8c52010-04-22 00:20:18 +00003525void InitializationSequence::PrintInitLocationNote(Sema &S,
3526 const InitializedEntity &Entity) {
3527 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3528 if (Entity.getDecl()->getLocation().isInvalid())
3529 return;
3530
3531 if (Entity.getDecl()->getDeclName())
3532 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3533 << Entity.getDecl()->getDeclName();
3534 else
3535 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3536 }
3537}
3538
John McCall60d7b3a2010-08-24 06:29:42 +00003539ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00003540InitializationSequence::Perform(Sema &S,
3541 const InitializedEntity &Entity,
3542 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00003543 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003544 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003545 if (SequenceKind == FailedSequence) {
3546 unsigned NumArgs = Args.size();
3547 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00003548 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003549 }
3550
3551 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003552 // If the declaration is a non-dependent, incomplete array type
3553 // that has an initializer, then its type will be completed once
3554 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003555 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003556 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003557 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003558 if (const IncompleteArrayType *ArrayT
3559 = S.Context.getAsIncompleteArrayType(DeclType)) {
3560 // FIXME: We don't currently have the ability to accurately
3561 // compute the length of an initializer list without
3562 // performing full type-checking of the initializer list
3563 // (since we have to determine where braces are implicitly
3564 // introduced and such). So, we fall back to making the array
3565 // type a dependently-sized array type with no specified
3566 // bound.
3567 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3568 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003569
Douglas Gregord87b61f2009-12-10 17:56:55 +00003570 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003571 if (DeclaratorDecl *DD = Entity.getDecl()) {
3572 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3573 TypeLoc TL = TInfo->getTypeLoc();
3574 if (IncompleteArrayTypeLoc *ArrayLoc
3575 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3576 Brackets = ArrayLoc->getBracketsRange();
3577 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003578 }
3579
3580 *ResultType
3581 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3582 /*NumElts=*/0,
3583 ArrayT->getSizeModifier(),
3584 ArrayT->getIndexTypeCVRQualifiers(),
3585 Brackets);
3586 }
3587
3588 }
3589 }
3590
Eli Friedman08544622009-12-22 02:35:53 +00003591 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCall60d7b3a2010-08-24 06:29:42 +00003592 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00003593
Douglas Gregor67fa05b2010-02-05 07:56:11 +00003594 if (Args.size() == 0)
3595 return S.Owned((Expr *)0);
3596
Douglas Gregor20093b42009-12-09 23:02:17 +00003597 unsigned NumArgs = Args.size();
3598 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3599 SourceLocation(),
3600 (Expr **)Args.release(),
3601 NumArgs,
3602 SourceLocation()));
3603 }
3604
Douglas Gregor99a2e602009-12-16 01:38:02 +00003605 if (SequenceKind == NoInitialization)
3606 return S.Owned((Expr *)0);
3607
Douglas Gregord6542d82009-12-22 15:35:07 +00003608 QualType DestType = Entity.getType().getNonReferenceType();
3609 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003610 // the same as Entity.getDecl()->getType() in cases involving type merging,
3611 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003612 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003613 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003614 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003615
John McCall60d7b3a2010-08-24 06:29:42 +00003616 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003617
3618 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3619
3620 // For initialization steps that start with a single initializer,
3621 // grab the only argument out the Args and place it into the "current"
3622 // initializer.
3623 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003624 case SK_ResolveAddressOfOverloadedFunction:
3625 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003626 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003627 case SK_CastDerivedToBaseLValue:
3628 case SK_BindReference:
3629 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00003630 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003631 case SK_UserConversion:
3632 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003633 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003634 case SK_QualificationConversionRValue:
3635 case SK_ConversionSequence:
3636 case SK_ListInitialization:
3637 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003638 case SK_StringInit:
John McCallf6a16482010-12-04 03:47:34 +00003639 case SK_ObjCObjectConversion: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003640 assert(Args.size() == 1);
John McCallf6a16482010-12-04 03:47:34 +00003641 Expr *CurInitExpr = Args.get()[0];
3642 if (!CurInitExpr) return ExprError();
3643
3644 // Read from a property when initializing something with it.
3645 if (CurInitExpr->getObjectKind() == OK_ObjCProperty)
3646 S.ConvertPropertyForRValue(CurInitExpr);
3647
3648 CurInit = ExprResult(CurInitExpr);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003649 break;
John McCallf6a16482010-12-04 03:47:34 +00003650 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003651
3652 case SK_ConstructorInitialization:
3653 case SK_ZeroInitialization:
3654 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003655 }
3656
3657 // Walk through the computed steps for the initialization sequence,
3658 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003659 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003660 for (step_iterator Step = step_begin(), StepEnd = step_end();
3661 Step != StepEnd; ++Step) {
3662 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003663 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003664
John McCallf6a16482010-12-04 03:47:34 +00003665 Expr *CurInitExpr = CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003666 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003667
3668 switch (Step->Kind) {
3669 case SK_ResolveAddressOfOverloadedFunction:
3670 // Overload resolution determined which function invoke; update the
3671 // initializer to reflect that choice.
John McCall6bb80172010-03-30 21:47:33 +00003672 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00003673 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003674 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00003675 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00003676 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00003677 break;
3678
3679 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003680 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00003681 case SK_CastDerivedToBaseLValue: {
3682 // We have a derived-to-base cast that produces either an rvalue or an
3683 // lvalue. Perform that cast.
3684
John McCallf871d0c2010-08-07 06:22:56 +00003685 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003686
Douglas Gregor20093b42009-12-09 23:02:17 +00003687 // Casts to inaccessible base classes are allowed with C-style casts.
3688 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3689 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3690 CurInitExpr->getLocStart(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003691 CurInitExpr->getSourceRange(),
3692 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003693 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003694
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003695 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3696 QualType T = SourceType;
3697 if (const PointerType *Pointer = T->getAs<PointerType>())
3698 T = Pointer->getPointeeType();
3699 if (const RecordType *RecordTy = T->getAs<RecordType>())
3700 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3701 cast<CXXRecordDecl>(RecordTy->getDecl()));
3702 }
3703
John McCall5baba9d2010-08-25 10:28:54 +00003704 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003705 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003706 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003707 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003708 VK_XValue :
3709 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00003710 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3711 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00003712 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00003713 CurInit.get(),
3714 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00003715 break;
3716 }
3717
3718 case SK_BindReference:
3719 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3720 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3721 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003722 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003723 << BitField->getDeclName()
3724 << CurInitExpr->getSourceRange();
3725 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00003726 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003727 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00003728
Anders Carlsson09380262010-01-31 17:18:49 +00003729 if (CurInitExpr->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00003730 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00003731 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3732 << Entity.getType().isVolatileQualified()
3733 << CurInitExpr->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00003734 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00003735 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00003736 }
3737
Douglas Gregor20093b42009-12-09 23:02:17 +00003738 // Reference binding does not have any corresponding ASTs.
3739
3740 // Check exception specifications
3741 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003742 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00003743
Douglas Gregor20093b42009-12-09 23:02:17 +00003744 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00003745
Douglas Gregor20093b42009-12-09 23:02:17 +00003746 case SK_BindReferenceToTemporary:
Anders Carlssona64a8692010-02-03 16:38:03 +00003747 // Reference binding does not have any corresponding ASTs.
3748
Douglas Gregor20093b42009-12-09 23:02:17 +00003749 // Check exception specifications
3750 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallf312b1e2010-08-26 23:41:50 +00003751 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003752
Douglas Gregor20093b42009-12-09 23:02:17 +00003753 break;
3754
Douglas Gregor523d46a2010-04-18 07:40:54 +00003755 case SK_ExtraneousCopyToTemporary:
3756 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3757 /*IsExtraneousCopy=*/true);
3758 break;
3759
Douglas Gregor20093b42009-12-09 23:02:17 +00003760 case SK_UserConversion: {
3761 // We have a user-defined conversion that invokes either a constructor
3762 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00003763 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003764 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00003765 FunctionDecl *Fn = Step->Function.Function;
3766 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003767 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003768 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00003769 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003770 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003771 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor20093b42009-12-09 23:02:17 +00003772 SourceLocation Loc = CurInitExpr->getLocStart();
3773 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00003774
Douglas Gregor20093b42009-12-09 23:02:17 +00003775 // Determine the arguments required to actually perform the constructor
3776 // call.
3777 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00003778 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00003779 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003780 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003781
3782 // Build the an expression that constructs a temporary.
3783 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00003784 move_arg(ConstructorArgs),
3785 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003786 CXXConstructExpr::CK_Complete,
3787 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00003788 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003789 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003790
Anders Carlsson9a68a672010-04-21 18:47:17 +00003791 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003792 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003793 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor20093b42009-12-09 23:02:17 +00003794
John McCall2de56d12010-08-25 11:45:40 +00003795 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003796 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3797 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3798 S.IsDerivedFrom(SourceType, Class))
3799 IsCopy = true;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003800
3801 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003802 } else {
3803 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00003804 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00003805 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall58e6f342010-03-16 05:22:47 +00003806 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCall9aa472c2010-03-19 07:35:19 +00003807 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00003808 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00003809
Douglas Gregor20093b42009-12-09 23:02:17 +00003810 // FIXME: Should we move this initialization into a separate
3811 // derived-to-base conversion? I believe the answer is "no", because
3812 // we don't want to turn off access control here for c-style casts.
Douglas Gregor5fccd362010-03-03 23:55:11 +00003813 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00003814 FoundFn, Conversion))
John McCallf312b1e2010-08-26 23:41:50 +00003815 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003816
3817 // Do a little dance to make sure that CurInit has the proper
3818 // pointer.
3819 CurInit.release();
3820
3821 // Build the actual call to the conversion function.
John McCall6bb80172010-03-30 21:47:33 +00003822 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3823 Conversion));
Douglas Gregor20093b42009-12-09 23:02:17 +00003824 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00003825 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003826
John McCall2de56d12010-08-25 11:45:40 +00003827 CastKind = CK_UserDefinedConversion;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003828
3829 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003830 }
3831
Douglas Gregor2f599792010-04-02 18:24:57 +00003832 bool RequiresCopy = !IsCopy &&
3833 getKind() != InitializationSequence::ReferenceBinding;
3834 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003835 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003836 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3837 CurInitExpr = static_cast<Expr *>(CurInit.get());
3838 QualType T = CurInitExpr->getType();
3839 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00003840 CXXDestructorDecl *Destructor
3841 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003842 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3843 S.PDiag(diag::err_access_dtor_temp) << T);
3844 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003845 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003846 }
3847 }
3848
Douglas Gregor20093b42009-12-09 23:02:17 +00003849 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redl906082e2010-07-20 04:20:21 +00003850 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00003851 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3852 CurInitExpr->getType(),
3853 CastKind, CurInitExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00003854 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003855
Douglas Gregor2f599792010-04-02 18:24:57 +00003856 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003857 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3858 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00003859
Douglas Gregor20093b42009-12-09 23:02:17 +00003860 break;
3861 }
Sebastian Redl906082e2010-07-20 04:20:21 +00003862
Douglas Gregor20093b42009-12-09 23:02:17 +00003863 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00003864 case SK_QualificationConversionXValue:
3865 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00003866 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00003867 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00003868 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003869 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00003870 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00003871 VK_XValue :
3872 VK_RValue);
John McCall2de56d12010-08-25 11:45:40 +00003873 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00003874 CurInit.release();
3875 CurInit = S.Owned(CurInitExpr);
3876 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00003877 }
3878
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003879 case SK_ConversionSequence: {
3880 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3881
3882 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
Douglas Gregora3998bd2010-12-02 21:47:04 +00003883 getAssignmentAction(Entity),
3884 IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00003885 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00003886
3887 CurInit.release();
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003888 CurInit = S.Owned(CurInitExpr);
Douglas Gregor20093b42009-12-09 23:02:17 +00003889 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00003890 }
3891
Douglas Gregord87b61f2009-12-10 17:56:55 +00003892 case SK_ListInitialization: {
3893 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3894 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003895 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00003896 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003897
3898 CurInit.release();
3899 CurInit = S.Owned(InitList);
3900 break;
3901 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003902
3903 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00003904 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003905 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00003906 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003907
Douglas Gregor51c56d62009-12-14 20:49:26 +00003908 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00003909 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00003910 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3911 ? Kind.getEqualLoc()
3912 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003913
3914 if (Kind.getKind() == InitializationKind::IK_Default) {
3915 // Force even a trivial, implicit default constructor to be
3916 // semantically checked. We do this explicitly because we don't build
3917 // the definition for completely trivial constructors.
3918 CXXRecordDecl *ClassDecl = Constructor->getParent();
3919 assert(ClassDecl && "No parent class for constructor.");
3920 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3921 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3922 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3923 }
3924
Douglas Gregor51c56d62009-12-14 20:49:26 +00003925 // Determine the arguments required to actually perform the constructor
3926 // call.
3927 if (S.CompleteConstructorCall(Constructor, move(Args),
3928 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00003929 return ExprError();
Douglas Gregor51c56d62009-12-14 20:49:26 +00003930
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003931
Douglas Gregor91be6f52010-03-02 17:18:33 +00003932 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00003933 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00003934 (Kind.getKind() == InitializationKind::IK_Direct ||
3935 Kind.getKind() == InitializationKind::IK_Value)) {
3936 // An explicitly-constructed temporary, e.g., X(1, 2).
3937 unsigned NumExprs = ConstructorArgs.size();
3938 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00003939 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00003940 S.DiagnoseUseOfDecl(Constructor, Loc);
3941
Douglas Gregorab6677e2010-09-08 00:15:04 +00003942 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3943 if (!TSInfo)
3944 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3945
Douglas Gregor91be6f52010-03-02 17:18:33 +00003946 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3947 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00003948 TSInfo,
Douglas Gregor91be6f52010-03-02 17:18:33 +00003949 Exprs,
3950 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003951 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00003952 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003953 } else {
3954 CXXConstructExpr::ConstructionKind ConstructKind =
3955 CXXConstructExpr::CK_Complete;
3956
3957 if (Entity.getKind() == InitializedEntity::EK_Base) {
3958 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3959 CXXConstructExpr::CK_VirtualBase :
3960 CXXConstructExpr::CK_NonVirtualBase;
3961 }
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003962
Chandler Carruth428edaf2010-10-25 08:47:36 +00003963 // Only get the parenthesis range if it is a direct construction.
3964 SourceRange parenRange =
3965 Kind.getKind() == InitializationKind::IK_Direct ?
3966 Kind.getParenRange() : SourceRange();
3967
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003968 // If the entity allows NRVO, mark the construction as elidable
3969 // unconditionally.
3970 if (Entity.allowsNRVO())
3971 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3972 Constructor, /*Elidable=*/true,
3973 move_arg(ConstructorArgs),
3974 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003975 ConstructKind,
3976 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003977 else
3978 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3979 Constructor,
3980 move_arg(ConstructorArgs),
3981 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00003982 ConstructKind,
3983 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00003984 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003985 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00003986 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00003987
3988 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00003989 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00003990 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00003991 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003992
Douglas Gregor2f599792010-04-02 18:24:57 +00003993 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003994 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003995
Douglas Gregor51c56d62009-12-14 20:49:26 +00003996 break;
3997 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003998
3999 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004000 step_iterator NextStep = Step;
4001 ++NextStep;
4002 if (NextStep != StepEnd &&
4003 NextStep->Kind == SK_ConstructorInitialization) {
4004 // The need for zero-initialization is recorded directly into
4005 // the call to the object's constructor within the next step.
4006 ConstructorInitRequiresZeroInit = true;
4007 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4008 S.getLangOptions().CPlusPlus &&
4009 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004010 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4011 if (!TSInfo)
4012 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
4013 Kind.getRange().getBegin());
4014
4015 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4016 TSInfo->getType().getNonLValueExprType(S.Context),
4017 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004018 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004019 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004020 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004021 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004022 break;
4023 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004024
4025 case SK_CAssignment: {
4026 QualType SourceType = CurInitExpr->getType();
4027 Sema::AssignConvertType ConvTy =
4028 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00004029
4030 // If this is a call, allow conversion to a transparent union.
4031 if (ConvTy != Sema::Compatible &&
4032 Entity.getKind() == InitializedEntity::EK_Parameter &&
4033 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4034 == Sema::Compatible)
4035 ConvTy = Sema::Compatible;
4036
Douglas Gregora41a8c52010-04-22 00:20:18 +00004037 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004038 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4039 Step->Type, SourceType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00004040 CurInitExpr,
4041 getAssignmentAction(Entity),
4042 &Complained)) {
4043 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004044 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004045 } else if (Complained)
4046 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004047
4048 CurInit.release();
4049 CurInit = S.Owned(CurInitExpr);
4050 break;
4051 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004052
4053 case SK_StringInit: {
4054 QualType Ty = Step->Type;
4055 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
4056 break;
4057 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004058
4059 case SK_ObjCObjectConversion:
4060 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004061 CK_ObjCObjectLValueCast,
Douglas Gregor569c3162010-08-07 11:51:51 +00004062 S.CastCategory(CurInitExpr));
4063 CurInit.release();
4064 CurInit = S.Owned(CurInitExpr);
4065 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004066 }
4067 }
John McCall15d7d122010-11-11 03:21:53 +00004068
4069 // Diagnose non-fatal problems with the completed initialization.
4070 if (Entity.getKind() == InitializedEntity::EK_Member &&
4071 cast<FieldDecl>(Entity.getDecl())->isBitField())
4072 S.CheckBitFieldInitialization(Kind.getLocation(),
4073 cast<FieldDecl>(Entity.getDecl()),
4074 CurInit.get());
Douglas Gregor20093b42009-12-09 23:02:17 +00004075
4076 return move(CurInit);
4077}
4078
4079//===----------------------------------------------------------------------===//
4080// Diagnose initialization failures
4081//===----------------------------------------------------------------------===//
4082bool InitializationSequence::Diagnose(Sema &S,
4083 const InitializedEntity &Entity,
4084 const InitializationKind &Kind,
4085 Expr **Args, unsigned NumArgs) {
4086 if (SequenceKind != FailedSequence)
4087 return false;
4088
Douglas Gregord6542d82009-12-22 15:35:07 +00004089 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004090 switch (Failure) {
4091 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004092 // FIXME: Customize for the initialized entity?
4093 if (NumArgs == 0)
4094 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4095 << DestType.getNonReferenceType();
4096 else // FIXME: diagnostic below could be better!
4097 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4098 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004099 break;
4100
4101 case FK_ArrayNeedsInitList:
4102 case FK_ArrayNeedsInitListOrStringLiteral:
4103 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4104 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4105 break;
4106
John McCall6bb80172010-03-30 21:47:33 +00004107 case FK_AddressOfOverloadFailed: {
4108 DeclAccessPair Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00004109 S.ResolveAddressOfOverloadedFunction(Args[0],
4110 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004111 true,
4112 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004113 break;
John McCall6bb80172010-03-30 21:47:33 +00004114 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004115
4116 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004117 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004118 switch (FailedOverloadResult) {
4119 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004120 if (Failure == FK_UserConversionOverloadFailed)
4121 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4122 << Args[0]->getType() << DestType
4123 << Args[0]->getSourceRange();
4124 else
4125 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4126 << DestType << Args[0]->getType()
4127 << Args[0]->getSourceRange();
4128
John McCall120d63c2010-08-24 20:38:10 +00004129 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004130 break;
4131
4132 case OR_No_Viable_Function:
4133 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4134 << Args[0]->getType() << DestType.getNonReferenceType()
4135 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004136 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004137 break;
4138
4139 case OR_Deleted: {
4140 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4141 << Args[0]->getType() << DestType.getNonReferenceType()
4142 << Args[0]->getSourceRange();
4143 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004144 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004145 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4146 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004147 if (Ovl == OR_Deleted) {
4148 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4149 << Best->Function->isDeleted();
4150 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004151 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004152 }
4153 break;
4154 }
4155
4156 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004157 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004158 break;
4159 }
4160 break;
4161
4162 case FK_NonConstLValueReferenceBindingToTemporary:
4163 case FK_NonConstLValueReferenceBindingToUnrelated:
4164 S.Diag(Kind.getLocation(),
4165 Failure == FK_NonConstLValueReferenceBindingToTemporary
4166 ? diag::err_lvalue_reference_bind_to_temporary
4167 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004168 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004169 << DestType.getNonReferenceType()
4170 << Args[0]->getType()
4171 << Args[0]->getSourceRange();
4172 break;
4173
4174 case FK_RValueReferenceBindingToLValue:
4175 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4176 << Args[0]->getSourceRange();
4177 break;
4178
4179 case FK_ReferenceInitDropsQualifiers:
4180 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4181 << DestType.getNonReferenceType()
4182 << Args[0]->getType()
4183 << Args[0]->getSourceRange();
4184 break;
4185
4186 case FK_ReferenceInitFailed:
4187 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4188 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004189 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004190 << Args[0]->getType()
4191 << Args[0]->getSourceRange();
4192 break;
4193
4194 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004195 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4196 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004197 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004198 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004199 << Args[0]->getType()
4200 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004201 break;
4202
4203 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004204 SourceRange R;
4205
4206 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004207 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004208 InitList->getLocEnd());
Douglas Gregor19311e72010-09-08 21:40:08 +00004209 else
4210 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004211
Douglas Gregor19311e72010-09-08 21:40:08 +00004212 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4213 if (Kind.isCStyleOrFunctionalCast())
4214 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4215 << R;
4216 else
4217 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4218 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004219 break;
4220 }
4221
4222 case FK_ReferenceBindingToInitList:
4223 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4224 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4225 break;
4226
4227 case FK_InitListBadDestinationType:
4228 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4229 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4230 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00004231
4232 case FK_ConstructorOverloadFailed: {
4233 SourceRange ArgsRange;
4234 if (NumArgs)
4235 ArgsRange = SourceRange(Args[0]->getLocStart(),
4236 Args[NumArgs - 1]->getLocEnd());
4237
4238 // FIXME: Using "DestType" for the entity we're printing is probably
4239 // bad.
4240 switch (FailedOverloadResult) {
4241 case OR_Ambiguous:
4242 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4243 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004244 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4245 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004246 break;
4247
4248 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004249 if (Kind.getKind() == InitializationKind::IK_Default &&
4250 (Entity.getKind() == InitializedEntity::EK_Base ||
4251 Entity.getKind() == InitializedEntity::EK_Member) &&
4252 isa<CXXConstructorDecl>(S.CurContext)) {
4253 // This is implicit default initialization of a member or
4254 // base within a constructor. If no viable function was
4255 // found, notify the user that she needs to explicitly
4256 // initialize this base/member.
4257 CXXConstructorDecl *Constructor
4258 = cast<CXXConstructorDecl>(S.CurContext);
4259 if (Entity.getKind() == InitializedEntity::EK_Base) {
4260 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4261 << Constructor->isImplicit()
4262 << S.Context.getTypeDeclType(Constructor->getParent())
4263 << /*base=*/0
4264 << Entity.getType();
4265
4266 RecordDecl *BaseDecl
4267 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4268 ->getDecl();
4269 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4270 << S.Context.getTagDeclType(BaseDecl);
4271 } else {
4272 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4273 << Constructor->isImplicit()
4274 << S.Context.getTypeDeclType(Constructor->getParent())
4275 << /*member=*/1
4276 << Entity.getName();
4277 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4278
4279 if (const RecordType *Record
4280 = Entity.getType()->getAs<RecordType>())
4281 S.Diag(Record->getDecl()->getLocation(),
4282 diag::note_previous_decl)
4283 << S.Context.getTagDeclType(Record->getDecl());
4284 }
4285 break;
4286 }
4287
Douglas Gregor51c56d62009-12-14 20:49:26 +00004288 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4289 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004290 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004291 break;
4292
4293 case OR_Deleted: {
4294 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4295 << true << DestType << ArgsRange;
4296 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004297 OverloadingResult Ovl
4298 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004299 if (Ovl == OR_Deleted) {
4300 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4301 << Best->Function->isDeleted();
4302 } else {
4303 llvm_unreachable("Inconsistent overload resolution?");
4304 }
4305 break;
4306 }
4307
4308 case OR_Success:
4309 llvm_unreachable("Conversion did not fail!");
4310 break;
4311 }
4312 break;
4313 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004314
4315 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004316 if (Entity.getKind() == InitializedEntity::EK_Member &&
4317 isa<CXXConstructorDecl>(S.CurContext)) {
4318 // This is implicit default-initialization of a const member in
4319 // a constructor. Complain that it needs to be explicitly
4320 // initialized.
4321 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4322 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4323 << Constructor->isImplicit()
4324 << S.Context.getTypeDeclType(Constructor->getParent())
4325 << /*const=*/1
4326 << Entity.getName();
4327 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4328 << Entity.getName();
4329 } else {
4330 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4331 << DestType << (bool)DestType->getAs<RecordType>();
4332 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004333 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004334
4335 case FK_Incomplete:
4336 S.RequireCompleteType(Kind.getLocation(), DestType,
4337 diag::err_init_incomplete_type);
4338 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004339 }
4340
Douglas Gregora41a8c52010-04-22 00:20:18 +00004341 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004342 return true;
4343}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004344
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004345void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4346 switch (SequenceKind) {
4347 case FailedSequence: {
4348 OS << "Failed sequence: ";
4349 switch (Failure) {
4350 case FK_TooManyInitsForReference:
4351 OS << "too many initializers for reference";
4352 break;
4353
4354 case FK_ArrayNeedsInitList:
4355 OS << "array requires initializer list";
4356 break;
4357
4358 case FK_ArrayNeedsInitListOrStringLiteral:
4359 OS << "array requires initializer list or string literal";
4360 break;
4361
4362 case FK_AddressOfOverloadFailed:
4363 OS << "address of overloaded function failed";
4364 break;
4365
4366 case FK_ReferenceInitOverloadFailed:
4367 OS << "overload resolution for reference initialization failed";
4368 break;
4369
4370 case FK_NonConstLValueReferenceBindingToTemporary:
4371 OS << "non-const lvalue reference bound to temporary";
4372 break;
4373
4374 case FK_NonConstLValueReferenceBindingToUnrelated:
4375 OS << "non-const lvalue reference bound to unrelated type";
4376 break;
4377
4378 case FK_RValueReferenceBindingToLValue:
4379 OS << "rvalue reference bound to an lvalue";
4380 break;
4381
4382 case FK_ReferenceInitDropsQualifiers:
4383 OS << "reference initialization drops qualifiers";
4384 break;
4385
4386 case FK_ReferenceInitFailed:
4387 OS << "reference initialization failed";
4388 break;
4389
4390 case FK_ConversionFailed:
4391 OS << "conversion failed";
4392 break;
4393
4394 case FK_TooManyInitsForScalar:
4395 OS << "too many initializers for scalar";
4396 break;
4397
4398 case FK_ReferenceBindingToInitList:
4399 OS << "referencing binding to initializer list";
4400 break;
4401
4402 case FK_InitListBadDestinationType:
4403 OS << "initializer list for non-aggregate, non-scalar type";
4404 break;
4405
4406 case FK_UserConversionOverloadFailed:
4407 OS << "overloading failed for user-defined conversion";
4408 break;
4409
4410 case FK_ConstructorOverloadFailed:
4411 OS << "constructor overloading failed";
4412 break;
4413
4414 case FK_DefaultInitOfConst:
4415 OS << "default initialization of a const variable";
4416 break;
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004417
4418 case FK_Incomplete:
4419 OS << "initialization of incomplete type";
4420 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004421 }
4422 OS << '\n';
4423 return;
4424 }
4425
4426 case DependentSequence:
4427 OS << "Dependent sequence: ";
4428 return;
4429
4430 case UserDefinedConversion:
4431 OS << "User-defined conversion sequence: ";
4432 break;
4433
4434 case ConstructorInitialization:
4435 OS << "Constructor initialization sequence: ";
4436 break;
4437
4438 case ReferenceBinding:
4439 OS << "Reference binding: ";
4440 break;
4441
4442 case ListInitialization:
4443 OS << "List initialization: ";
4444 break;
4445
4446 case ZeroInitialization:
4447 OS << "Zero initialization\n";
4448 return;
4449
4450 case NoInitialization:
4451 OS << "No initialization\n";
4452 return;
4453
4454 case StandardConversion:
4455 OS << "Standard conversion: ";
4456 break;
4457
4458 case CAssignment:
4459 OS << "C assignment: ";
4460 break;
4461
4462 case StringInit:
4463 OS << "String initialization: ";
4464 break;
4465 }
4466
4467 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4468 if (S != step_begin()) {
4469 OS << " -> ";
4470 }
4471
4472 switch (S->Kind) {
4473 case SK_ResolveAddressOfOverloadedFunction:
4474 OS << "resolve address of overloaded function";
4475 break;
4476
4477 case SK_CastDerivedToBaseRValue:
4478 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4479 break;
4480
Sebastian Redl906082e2010-07-20 04:20:21 +00004481 case SK_CastDerivedToBaseXValue:
4482 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4483 break;
4484
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004485 case SK_CastDerivedToBaseLValue:
4486 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4487 break;
4488
4489 case SK_BindReference:
4490 OS << "bind reference to lvalue";
4491 break;
4492
4493 case SK_BindReferenceToTemporary:
4494 OS << "bind reference to a temporary";
4495 break;
4496
Douglas Gregor523d46a2010-04-18 07:40:54 +00004497 case SK_ExtraneousCopyToTemporary:
4498 OS << "extraneous C++03 copy to temporary";
4499 break;
4500
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004501 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00004502 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004503 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004504
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004505 case SK_QualificationConversionRValue:
4506 OS << "qualification conversion (rvalue)";
4507
Sebastian Redl906082e2010-07-20 04:20:21 +00004508 case SK_QualificationConversionXValue:
4509 OS << "qualification conversion (xvalue)";
4510
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004511 case SK_QualificationConversionLValue:
4512 OS << "qualification conversion (lvalue)";
4513 break;
4514
4515 case SK_ConversionSequence:
4516 OS << "implicit conversion sequence (";
4517 S->ICS->DebugPrint(); // FIXME: use OS
4518 OS << ")";
4519 break;
4520
4521 case SK_ListInitialization:
4522 OS << "list initialization";
4523 break;
4524
4525 case SK_ConstructorInitialization:
4526 OS << "constructor initialization";
4527 break;
4528
4529 case SK_ZeroInitialization:
4530 OS << "zero initialization";
4531 break;
4532
4533 case SK_CAssignment:
4534 OS << "C assignment";
4535 break;
4536
4537 case SK_StringInit:
4538 OS << "string initialization";
4539 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00004540
4541 case SK_ObjCObjectConversion:
4542 OS << "Objective-C object conversion";
4543 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004544 }
4545 }
4546}
4547
4548void InitializationSequence::dump() const {
4549 dump(llvm::errs());
4550}
4551
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004552//===----------------------------------------------------------------------===//
4553// Initialization helper functions
4554//===----------------------------------------------------------------------===//
John McCall60d7b3a2010-08-24 06:29:42 +00004555ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004556Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4557 SourceLocation EqualLoc,
John McCall60d7b3a2010-08-24 06:29:42 +00004558 ExprResult Init) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004559 if (Init.isInvalid())
4560 return ExprError();
4561
John McCall15d7d122010-11-11 03:21:53 +00004562 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004563 assert(InitE && "No initialization expression?");
4564
4565 if (EqualLoc.isInvalid())
4566 EqualLoc = InitE->getLocStart();
4567
4568 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4569 EqualLoc);
4570 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4571 Init.release();
John McCallf312b1e2010-08-26 23:41:50 +00004572 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004573}