blob: e61fe2d519571b726aad88df8bae89b89f5b23c6 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000025#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000026#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000027using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000028
Chris Lattner0cb78032009-02-24 22:27:37 +000029//===----------------------------------------------------------------------===//
30// Sema Initialization Checking
31//===----------------------------------------------------------------------===//
32
John McCall66884dd2011-02-21 07:22:22 +000033static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000035 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
36 return 0;
37
Chris Lattnera9196812009-02-26 23:26:43 +000038 // See if this is a string literal or @encode.
39 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000040
Chris Lattnera9196812009-02-26 23:26:43 +000041 // Handle @encode, which is a narrow string.
42 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
43 return Init;
44
45 // Otherwise we can only handle string literals.
46 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000047 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000048
49 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-07-27 05:40:30 +000050
51 switch (SL->getKind()) {
52 case StringLiteral::Ascii:
53 case StringLiteral::UTF8:
54 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000057 case StringLiteral::UTF16:
58 return ElemTy->isChar16Type() ? Init : 0;
59 case StringLiteral::UTF32:
60 return ElemTy->isChar32Type() ? Init : 0;
61 case StringLiteral::Wide:
62 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
63 // correction from DR343): "An array with element type compatible with a
64 // qualified or unqualified version of wchar_t may be initialized by a wide
65 // string literal, optionally enclosed in braces."
66 if (Context.typesAreCompatible(Context.getWCharType(),
67 ElemTy.getUnqualifiedType()))
68 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000069
Douglas Gregorfb65e592011-07-27 05:40:30 +000070 return 0;
71 }
Mike Stump11289f42009-09-09 15:08:12 +000072
Douglas Gregorfb65e592011-07-27 05:40:30 +000073 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000074}
75
John McCall66884dd2011-02-21 07:22:22 +000076static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
77 const ArrayType *arrayType = Context.getAsArrayType(declType);
78 if (!arrayType) return 0;
79
80 return IsStringInit(init, arrayType, Context);
81}
82
John McCall5decec92011-02-21 07:57:55 +000083static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
84 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000085 // Get the length of the string as parsed.
86 uint64_t StrLength =
87 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
88
Mike Stump11289f42009-09-09 15:08:12 +000089
Chris Lattner0cb78032009-02-24 22:27:37 +000090 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000091 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000092 // being initialized to a string literal.
93 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000094 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000095 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000096 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
97 ConstVal,
98 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000099 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000100 }
Mike Stump11289f42009-09-09 15:08:12 +0000101
Eli Friedman893abe42009-05-29 18:22:49 +0000102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman554eba92011-04-11 00:23:45 +0000104 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000105 // the size may be smaller or larger than the string we are initializing.
106 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000107 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000108 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
109 // For Pascal strings it's OK to strip off the terminating null character,
110 // so the example below is valid:
111 //
112 // unsigned char a[2] = "\pa";
113 if (SL->isPascal())
114 StrLength--;
115 }
116
Eli Friedman554eba92011-04-11 00:23:45 +0000117 // [dcl.init.string]p2
118 if (StrLength > CAT->getSize().getZExtValue())
119 S.Diag(Str->getSourceRange().getBegin(),
120 diag::err_initializer_string_for_char_array_too_long)
121 << Str->getSourceRange();
122 } else {
123 // C99 6.7.8p14.
124 if (StrLength-1 > CAT->getSize().getZExtValue())
125 S.Diag(Str->getSourceRange().getBegin(),
126 diag::warn_initializer_string_for_char_array_too_long)
127 << Str->getSourceRange();
128 }
Mike Stump11289f42009-09-09 15:08:12 +0000129
Eli Friedman893abe42009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000135}
136
Chris Lattner0cb78032009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregorcde232f2009-01-29 01:05:33 +0000141/// @brief Semantic checking for initializer lists.
142///
143/// The InitListChecker class contains a set of routines that each
144/// handle the initialization of a certain kind of entity, e.g.,
145/// arrays, vectors, struct/union types, scalars, etc. The
146/// InitListChecker itself performs a recursive walk of the subobject
147/// structure of the type to be initialized, while stepping through
148/// the initializer list one element at a time. The IList and Index
149/// parameters to each of the Check* routines contain the active
150/// (syntactic) initializer list and the index into that initializer
151/// list that represents the current initializer. Each routine is
152/// responsible for moving that Index forward as it consumes elements.
153///
154/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000155/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000156/// initializer list and the index into that initializer list where we
157/// are copying initializers as we map them over to the semantic
158/// list. Once we have completed our recursive walk of the subobject
159/// structure, we will have constructed a full semantic initializer
160/// list.
161///
162/// C99 designators cause changes in the initializer list traversal,
163/// because they make the initialization "jump" into a specific
164/// subobject and then continue the initialization from that
165/// point. CheckDesignatedInitializer() recursively steps into the
166/// designated subobject and manages backing out the recursion to
167/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000168namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000172 bool VerifyOnly; // no diagnostics, no structure building
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000175
Anders Carlsson6cabf312010-01-23 23:23:01 +0000176 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000177 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000178 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000179 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000180 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000181 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000182 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000185 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000186 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000187 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000188 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000189 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000190 unsigned &StructuredIndex,
191 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000192 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000193 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000194 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000197 void CheckComplexType(const InitializedEntity &Entity,
198 InitListExpr *IList, QualType DeclType,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000202 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000203 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000204 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000205 InitListExpr *StructuredList,
206 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000207 void CheckReferenceType(const InitializedEntity &Entity,
208 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000209 unsigned &Index,
210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000212 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000213 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000216 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000217 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000218 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000220 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000221 unsigned &StructuredIndex,
222 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000223 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000224 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000225 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000226 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000227 InitListExpr *StructuredList,
228 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000229 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000230 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000231 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000232 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000233 RecordDecl::field_iterator *NextField,
234 llvm::APSInt *NextElementIndex,
235 unsigned &Index,
236 InitListExpr *StructuredList,
237 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000238 bool FinishSubobjectInit,
239 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000240 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
241 QualType CurrentObjectType,
242 InitListExpr *StructuredList,
243 unsigned StructuredIndex,
244 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000245 void UpdateStructuredListElement(InitListExpr *StructuredList,
246 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000247 Expr *expr);
248 int numArrayElements(QualType DeclType);
249 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000250
Douglas Gregor2bb07652009-12-22 00:05:34 +0000251 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
252 const InitializedEntity &ParentEntity,
253 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000254 void FillInValueInitializations(const InitializedEntity &Entity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000256 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
257 Expr *InitExpr, FieldDecl *Field,
258 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000259public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000260 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000261 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000262 bool HadError() { return hadError; }
263
264 // @brief Retrieves the fully-structured initializer list used for
265 // semantic analysis and code generation.
266 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
267};
Chris Lattner9ececce2009-02-24 22:48:58 +0000268} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000269
Douglas Gregor2bb07652009-12-22 00:05:34 +0000270void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
271 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000273 bool &RequiresSecondPass) {
274 SourceLocation Loc = ILE->getSourceRange().getBegin();
275 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000277 = InitializedEntity::InitializeMember(Field, &ParentEntity);
278 if (Init >= NumInits || !ILE->getInit(Init)) {
279 // FIXME: We probably don't need to handle references
280 // specially here, since value-initialization of references is
281 // handled in InitializationSequence.
282 if (Field->getType()->isReferenceType()) {
283 // C++ [dcl.init.aggr]p9:
284 // If an incomplete or empty initializer-list leaves a
285 // member of reference type uninitialized, the program is
286 // ill-formed.
287 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
288 << Field->getType()
289 << ILE->getSyntacticForm()->getSourceRange();
290 SemaRef.Diag(Field->getLocation(),
291 diag::note_uninit_reference_member);
292 hadError = true;
293 return;
294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295
Douglas Gregor2bb07652009-12-22 00:05:34 +0000296 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
297 true);
298 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
299 if (!InitSeq) {
300 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
301 hadError = true;
302 return;
303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000304
John McCalldadc5752010-08-24 06:29:42 +0000305 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000306 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000307 if (MemberInit.isInvalid()) {
308 hadError = true;
309 return;
310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311
Douglas Gregor2bb07652009-12-22 00:05:34 +0000312 if (hadError) {
313 // Do nothing
314 } else if (Init < NumInits) {
315 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000316 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000317 // Value-initialization requires a constructor call, so
318 // extend the initializer list to include the constructor
319 // call and make a note that we'll need to take another pass
320 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000321 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000322 RequiresSecondPass = true;
323 }
324 } else if (InitListExpr *InnerILE
325 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000326 FillInValueInitializations(MemberEntity, InnerILE,
327 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328}
329
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000330/// Recursively replaces NULL values within the given initializer list
331/// with expressions that perform value-initialization of the
332/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000333void
Douglas Gregor723796a2009-12-16 06:35:08 +0000334InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
335 InitListExpr *ILE,
336 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000337 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000338 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000339 SourceLocation Loc = ILE->getSourceRange().getBegin();
340 if (ILE->getSyntacticForm())
341 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000342
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000343 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000344 if (RType->getDecl()->isUnion() &&
345 ILE->getInitializedFieldInUnion())
346 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
347 Entity, ILE, RequiresSecondPass);
348 else {
349 unsigned Init = 0;
350 for (RecordDecl::field_iterator
351 Field = RType->getDecl()->field_begin(),
352 FieldEnd = RType->getDecl()->field_end();
353 Field != FieldEnd; ++Field) {
354 if (Field->isUnnamedBitfield())
355 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000356
Douglas Gregor2bb07652009-12-22 00:05:34 +0000357 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000358 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000359
360 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
361 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000362 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000363
Douglas Gregor2bb07652009-12-22 00:05:34 +0000364 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000365
Douglas Gregor2bb07652009-12-22 00:05:34 +0000366 // Only look at the first initialization of a union.
367 if (RType->getDecl()->isUnion())
368 break;
369 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000370 }
371
372 return;
Mike Stump11289f42009-09-09 15:08:12 +0000373 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000374
375 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000376
Douglas Gregor723796a2009-12-16 06:35:08 +0000377 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000378 unsigned NumInits = ILE->getNumInits();
379 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000380 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000381 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000382 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
383 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000385 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000386 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000387 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000388 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000390 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000391 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000392 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000393
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000395 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000396 if (hadError)
397 return;
398
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000399 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
400 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000401 ElementEntity.setElementIndex(Init);
402
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000403 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000404 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
405 true);
406 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
407 if (!InitSeq) {
408 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000409 hadError = true;
410 return;
411 }
412
John McCalldadc5752010-08-24 06:29:42 +0000413 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000414 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000415 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000416 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000417 return;
418 }
419
420 if (hadError) {
421 // Do nothing
422 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000423 // For arrays, just set the expression used for value-initialization
424 // of the "holes" in the array.
425 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
426 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
427 else
428 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000429 } else {
430 // For arrays, just set the expression used for value-initialization
431 // of the rest of elements and exit.
432 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
433 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
434 return;
435 }
436
Sebastian Redld201edf2011-06-05 13:59:11 +0000437 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000438 // Value-initialization requires a constructor call, so
439 // extend the initializer list to include the constructor
440 // call and make a note that we'll need to take another pass
441 // through the initializer list.
442 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
443 RequiresSecondPass = true;
444 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000445 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000446 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000447 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
448 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000449 }
450}
451
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000452
Douglas Gregor723796a2009-12-16 06:35:08 +0000453InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000454 InitListExpr *IL, QualType &T,
455 bool VerifyOnly)
456 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000457 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000458
Eli Friedman23a9e312008-05-19 19:16:24 +0000459 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000460 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000461 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000462 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000463 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000464 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000465 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000466
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000467 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000468 bool RequiresSecondPass = false;
469 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000470 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000471 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000472 RequiresSecondPass);
473 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000474}
475
476int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000477 // FIXME: use a proper constant
478 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000479 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000480 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000481 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
482 }
483 return maxElements;
484}
485
486int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000487 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000488 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000489 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000490 Field = structDecl->field_begin(),
491 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000492 Field != FieldEnd; ++Field) {
493 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
494 ++InitializableMembers;
495 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000496 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000497 return std::min(InitializableMembers, 1);
498 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000499}
500
Anders Carlsson6cabf312010-01-23 23:23:01 +0000501void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000502 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000503 QualType T, unsigned &Index,
504 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000505 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000506 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Steve Narofff8ecff22008-05-01 22:18:59 +0000508 if (T->isArrayType())
509 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000510 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000511 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000512 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000513 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000514 else
David Blaikie83d382b2011-09-23 05:06:16 +0000515 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000516
Eli Friedmane0f832b2008-05-25 13:49:22 +0000517 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000518 if (!VerifyOnly)
519 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
520 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000521 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000522 hadError = true;
523 return;
524 }
525
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000526 // Build a structured initializer list corresponding to this subobject.
527 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000528 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
529 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000530 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
531 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000532 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000533
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000534 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000535 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000537 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000538 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000539 StructuredSubobjectInitIndex);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000540 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000541 if (!VerifyOnly) {
542 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000543
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000544 // Update the structured sub-object initializer so that it's ending
545 // range corresponds with the end of the last initializer it used.
546 if (EndIndex < ParentIList->getNumInits()) {
547 SourceLocation EndLoc
548 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
549 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000552 // Warn about missing braces.
553 if (T->isArrayType() || T->isRecordType()) {
554 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
555 diag::warn_missing_braces)
556 << StructuredSubobjectInitList->getSourceRange()
557 << FixItHint::CreateInsertion(
558 StructuredSubobjectInitList->getLocStart(), "{")
559 << FixItHint::CreateInsertion(
560 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000561 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000562 "}");
563 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000564 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000565}
566
Anders Carlsson6cabf312010-01-23 23:23:01 +0000567void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000568 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000569 unsigned &Index,
570 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000571 unsigned &StructuredIndex,
572 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000573 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000574 if (!VerifyOnly) {
575 SyntacticToSemantic[IList] = StructuredList;
576 StructuredList->setSyntacticForm(IList);
577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000579 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000580 if (!VerifyOnly) {
581 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
582 IList->setType(ExprTy);
583 StructuredList->setType(ExprTy);
584 }
Eli Friedman85f54972008-05-25 13:22:35 +0000585 if (hadError)
586 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000587
Eli Friedman85f54972008-05-25 13:22:35 +0000588 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000589 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000590 if (VerifyOnly) {
591 if (SemaRef.getLangOptions().CPlusPlus ||
592 (SemaRef.getLangOptions().OpenCL &&
593 IList->getType()->isVectorType())) {
594 hadError = true;
595 }
596 return;
597 }
598
Eli Friedmanbd327452009-05-29 20:20:05 +0000599 if (StructuredIndex == 1 &&
600 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000601 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000602 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000603 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000604 hadError = true;
605 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000606 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000608 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000609 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000610 // Don't complain for incomplete types, since we'll get an error
611 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000612 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000613 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000614 CurrentObjectType->isArrayType()? 0 :
615 CurrentObjectType->isVectorType()? 1 :
616 CurrentObjectType->isScalarType()? 2 :
617 CurrentObjectType->isUnionType()? 3 :
618 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000619
620 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000621 if (SemaRef.getLangOptions().CPlusPlus) {
622 DK = diag::err_excess_initializers;
623 hadError = true;
624 }
Nate Begeman425038c2009-07-07 21:53:06 +0000625 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
626 DK = diag::err_excess_initializers;
627 hadError = true;
628 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000629
Chris Lattnerb0912a52009-02-24 22:50:46 +0000630 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000631 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000632 }
633 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000634
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000635 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
636 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000637 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000638 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000639 << FixItHint::CreateRemoval(IList->getLocStart())
640 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000641}
642
Anders Carlsson6cabf312010-01-23 23:23:01 +0000643void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000644 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000645 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000646 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000647 unsigned &Index,
648 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000649 unsigned &StructuredIndex,
650 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000651 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
652 // Explicitly braced initializer for complex type can be real+imaginary
653 // parts.
654 CheckComplexType(Entity, IList, DeclType, Index,
655 StructuredList, StructuredIndex);
656 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000657 CheckScalarType(Entity, IList, DeclType, Index,
658 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000659 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000660 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000661 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000662 } else if (DeclType->isAggregateType()) {
663 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000664 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000665 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000666 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000667 StructuredList, StructuredIndex,
668 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000669 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000670 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000671 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000672 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000673 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000674 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000675 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000676 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000677 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000678 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
679 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000680 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000681 if (!VerifyOnly)
682 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
683 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000684 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000685 } else if (DeclType->isRecordType()) {
686 // C++ [dcl.init]p14:
687 // [...] If the class is an aggregate (8.5.1), and the initializer
688 // is a brace-enclosed list, see 8.5.1.
689 //
690 // Note: 8.5.1 is handled below; here, we diagnose the case where
691 // we have an initializer list and a destination type that is not
692 // an aggregate.
693 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000694 if (!VerifyOnly)
695 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
696 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000697 hadError = true;
698 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000699 CheckReferenceType(Entity, IList, DeclType, Index,
700 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000701 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000702 if (!VerifyOnly)
703 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
704 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000705 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000706 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000710 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000711 }
712}
713
Anders Carlsson6cabf312010-01-23 23:23:01 +0000714void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000715 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000716 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000717 unsigned &Index,
718 InitListExpr *StructuredList,
719 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000720 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000721 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
722 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000723 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000724 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000725 = getStructuredSubobjectInit(IList, Index, ElemType,
726 StructuredList, StructuredIndex,
727 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000728 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000729 newStructuredList, newStructuredIndex);
730 ++StructuredIndex;
731 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000732 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000733 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000734 return CheckScalarType(Entity, IList, ElemType, Index,
735 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000736 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000737 return CheckReferenceType(Entity, IList, ElemType, Index,
738 StructuredList, StructuredIndex);
739 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000740
John McCall5decec92011-02-21 07:57:55 +0000741 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
742 // arrayType can be incomplete if we're initializing a flexible
743 // array member. There's nothing we can do with the completed
744 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000745
John McCall5decec92011-02-21 07:57:55 +0000746 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000747 if (!VerifyOnly) {
748 CheckStringInit(Str, ElemType, arrayType, SemaRef);
749 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
750 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000751 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000752 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000753 }
John McCall5decec92011-02-21 07:57:55 +0000754
755 // Fall through for subaggregate initialization.
756
757 } else if (SemaRef.getLangOptions().CPlusPlus) {
758 // C++ [dcl.init.aggr]p12:
759 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000760 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000761 // an initializer-list. If the initializer can initialize a
762 // member, the member is initialized. [...]
763
764 // FIXME: Better EqualLoc?
765 InitializationKind Kind =
766 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
767 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
768
769 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000770 if (!VerifyOnly) {
771 ExprResult Result =
772 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
773 if (Result.isInvalid())
774 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000775
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000776 UpdateStructuredListElement(StructuredList, StructuredIndex,
777 Result.takeAs<Expr>());
778 }
John McCall5decec92011-02-21 07:57:55 +0000779 ++Index;
780 return;
781 }
782
783 // Fall through for subaggregate initialization
784 } else {
785 // C99 6.7.8p13:
786 //
787 // The initializer for a structure or union object that has
788 // automatic storage duration shall be either an initializer
789 // list as described below, or a single expression that has
790 // compatible structure or union type. In the latter case, the
791 // initial value of the object, including unnamed members, is
792 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000793 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000794 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000795 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
796 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000797 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000798 if (ExprRes.isInvalid())
799 hadError = true;
800 else {
801 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
802 if (ExprRes.isInvalid())
803 hadError = true;
804 }
805 UpdateStructuredListElement(StructuredList, StructuredIndex,
806 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000807 ++Index;
808 return;
809 }
John Wiegley01296292011-04-08 18:41:53 +0000810 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000811 // Fall through for subaggregate initialization
812 }
813
814 // C++ [dcl.init.aggr]p12:
815 //
816 // [...] Otherwise, if the member is itself a non-empty
817 // subaggregate, brace elision is assumed and the initializer is
818 // considered for the initialization of the first member of
819 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000820 if (!SemaRef.getLangOptions().OpenCL &&
821 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000822 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
823 StructuredIndex);
824 ++StructuredIndex;
825 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000826 if (!VerifyOnly) {
827 // We cannot initialize this element, so let
828 // PerformCopyInitialization produce the appropriate diagnostic.
829 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
830 SemaRef.Owned(expr),
831 /*TopLevelOfInitList=*/true);
832 }
John McCall5decec92011-02-21 07:57:55 +0000833 hadError = true;
834 ++Index;
835 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000836 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000837}
838
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000839void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
840 InitListExpr *IList, QualType DeclType,
841 unsigned &Index,
842 InitListExpr *StructuredList,
843 unsigned &StructuredIndex) {
844 assert(Index == 0 && "Index in explicit init list must be zero");
845
846 // As an extension, clang supports complex initializers, which initialize
847 // a complex number component-wise. When an explicit initializer list for
848 // a complex number contains two two initializers, this extension kicks in:
849 // it exepcts the initializer list to contain two elements convertible to
850 // the element type of the complex type. The first element initializes
851 // the real part, and the second element intitializes the imaginary part.
852
853 if (IList->getNumInits() != 2)
854 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
855 StructuredIndex);
856
857 // This is an extension in C. (The builtin _Complex type does not exist
858 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000859 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000860 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
861 << IList->getSourceRange();
862
863 // Initialize the complex number.
864 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
865 InitializedEntity ElementEntity =
866 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
867
868 for (unsigned i = 0; i < 2; ++i) {
869 ElementEntity.setElementIndex(Index);
870 CheckSubElementType(ElementEntity, IList, elementType, Index,
871 StructuredList, StructuredIndex);
872 }
873}
874
875
Anders Carlsson6cabf312010-01-23 23:23:01 +0000876void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000877 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000878 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000879 InitListExpr *StructuredList,
880 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000881 if (Index >= IList->getNumInits()) {
Sebastian Redl12757ab2011-09-24 17:48:14 +0000882 if (!SemaRef.getLangOptions().CPlusPlus0x) {
883 if (!VerifyOnly)
884 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
885 << IList->getSourceRange();
886 hadError = true;
887 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000888 ++Index;
889 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000890 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000891 }
John McCall643169b2010-11-11 00:46:36 +0000892
893 Expr *expr = IList->getInit(Index);
894 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000895 if (!VerifyOnly)
896 SemaRef.Diag(SubIList->getLocStart(),
897 diag::warn_many_braces_around_scalar_init)
898 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000899
900 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
901 StructuredIndex);
902 return;
903 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000904 if (!VerifyOnly)
905 SemaRef.Diag(expr->getSourceRange().getBegin(),
906 diag::err_designator_for_scalar_init)
907 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000908 hadError = true;
909 ++Index;
910 ++StructuredIndex;
911 return;
912 }
913
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000914 if (VerifyOnly) {
915 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
916 hadError = true;
917 ++Index;
918 return;
919 }
920
John McCall643169b2010-11-11 00:46:36 +0000921 ExprResult Result =
922 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000923 SemaRef.Owned(expr),
924 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000925
926 Expr *ResultExpr = 0;
927
928 if (Result.isInvalid())
929 hadError = true; // types weren't compatible.
930 else {
931 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000932
John McCall643169b2010-11-11 00:46:36 +0000933 if (ResultExpr != expr) {
934 // The type was promoted, update initializer list.
935 IList->setInit(Index, ResultExpr);
936 }
937 }
938 if (hadError)
939 ++StructuredIndex;
940 else
941 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
942 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000943}
944
Anders Carlsson6cabf312010-01-23 23:23:01 +0000945void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
946 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000947 unsigned &Index,
948 InitListExpr *StructuredList,
949 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000950 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000951 // FIXME: It would be wonderful if we could point at the actual member. In
952 // general, it would be useful to pass location information down the stack,
953 // so that we know the location (or decl) of the "current object" being
954 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000955 if (!VerifyOnly)
956 SemaRef.Diag(IList->getLocStart(),
957 diag::err_init_reference_member_uninitialized)
958 << DeclType
959 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000960 hadError = true;
961 ++Index;
962 ++StructuredIndex;
963 return;
964 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000965
966 Expr *expr = IList->getInit(Index);
967 if (isa<InitListExpr>(expr)) {
968 // FIXME: Allowed in C++11.
969 if (!VerifyOnly)
970 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
971 << DeclType << IList->getSourceRange();
972 hadError = true;
973 ++Index;
974 ++StructuredIndex;
975 return;
976 }
977
978 if (VerifyOnly) {
979 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
980 hadError = true;
981 ++Index;
982 return;
983 }
984
985 ExprResult Result =
986 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
987 SemaRef.Owned(expr),
988 /*TopLevelOfInitList=*/true);
989
990 if (Result.isInvalid())
991 hadError = true;
992
993 expr = Result.takeAs<Expr>();
994 IList->setInit(Index, expr);
995
996 if (hadError)
997 ++StructuredIndex;
998 else
999 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1000 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001001}
1002
Anders Carlsson6cabf312010-01-23 23:23:01 +00001003void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001004 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001005 unsigned &Index,
1006 InitListExpr *StructuredList,
1007 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001008 if (Index >= IList->getNumInits())
1009 return;
Mike Stump11289f42009-09-09 15:08:12 +00001010
John McCall6a16b2f2010-10-30 00:11:39 +00001011 const VectorType *VT = DeclType->getAs<VectorType>();
1012 unsigned maxElements = VT->getNumElements();
1013 unsigned numEltsInit = 0;
1014 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001015
John McCall6a16b2f2010-10-30 00:11:39 +00001016 if (!SemaRef.getLangOptions().OpenCL) {
1017 // If the initializing element is a vector, try to copy-initialize
1018 // instead of breaking it apart (which is doomed to failure anyway).
1019 Expr *Init = IList->getInit(Index);
1020 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001021 if (VerifyOnly) {
1022 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1023 hadError = true;
1024 ++Index;
1025 return;
1026 }
1027
John McCall6a16b2f2010-10-30 00:11:39 +00001028 ExprResult Result =
1029 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001030 SemaRef.Owned(Init),
1031 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001032
1033 Expr *ResultExpr = 0;
1034 if (Result.isInvalid())
1035 hadError = true; // types weren't compatible.
1036 else {
1037 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001038
John McCall6a16b2f2010-10-30 00:11:39 +00001039 if (ResultExpr != Init) {
1040 // The type was promoted, update initializer list.
1041 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001042 }
1043 }
John McCall6a16b2f2010-10-30 00:11:39 +00001044 if (hadError)
1045 ++StructuredIndex;
1046 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001047 UpdateStructuredListElement(StructuredList, StructuredIndex,
1048 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001049 ++Index;
1050 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
John McCall6a16b2f2010-10-30 00:11:39 +00001053 InitializedEntity ElementEntity =
1054 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001055
John McCall6a16b2f2010-10-30 00:11:39 +00001056 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1057 // Don't attempt to go past the end of the init list
1058 if (Index >= IList->getNumInits())
1059 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001060
John McCall6a16b2f2010-10-30 00:11:39 +00001061 ElementEntity.setElementIndex(Index);
1062 CheckSubElementType(ElementEntity, IList, elementType, Index,
1063 StructuredList, StructuredIndex);
1064 }
1065 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001066 }
John McCall6a16b2f2010-10-30 00:11:39 +00001067
1068 InitializedEntity ElementEntity =
1069 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001070
John McCall6a16b2f2010-10-30 00:11:39 +00001071 // OpenCL initializers allows vectors to be constructed from vectors.
1072 for (unsigned i = 0; i < maxElements; ++i) {
1073 // Don't attempt to go past the end of the init list
1074 if (Index >= IList->getNumInits())
1075 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001076
John McCall6a16b2f2010-10-30 00:11:39 +00001077 ElementEntity.setElementIndex(Index);
1078
1079 QualType IType = IList->getInit(Index)->getType();
1080 if (!IType->isVectorType()) {
1081 CheckSubElementType(ElementEntity, IList, elementType, Index,
1082 StructuredList, StructuredIndex);
1083 ++numEltsInit;
1084 } else {
1085 QualType VecType;
1086 const VectorType *IVT = IType->getAs<VectorType>();
1087 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001088
John McCall6a16b2f2010-10-30 00:11:39 +00001089 if (IType->isExtVectorType())
1090 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1091 else
1092 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001093 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001094 CheckSubElementType(ElementEntity, IList, VecType, Index,
1095 StructuredList, StructuredIndex);
1096 numEltsInit += numIElts;
1097 }
1098 }
1099
1100 // OpenCL requires all elements to be initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001101 // FIXME: Shouldn't this set hadError to true then?
1102 if (numEltsInit != maxElements && !VerifyOnly)
1103 SemaRef.Diag(IList->getSourceRange().getBegin(),
1104 diag::err_vector_incorrect_num_initializers)
1105 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +00001106}
1107
Anders Carlsson6cabf312010-01-23 23:23:01 +00001108void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001109 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001110 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001111 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001112 unsigned &Index,
1113 InitListExpr *StructuredList,
1114 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001115 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1116
Steve Narofff8ecff22008-05-01 22:18:59 +00001117 // Check for the special-case of initializing an array with a string.
1118 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001119 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001120 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001121 // We place the string literal directly into the resulting
1122 // initializer list. This is the only place where the structure
1123 // of the structured initializer list doesn't match exactly,
1124 // because doing so would involve allocating one character
1125 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001126 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001127 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001128 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1129 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1130 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001131 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001132 return;
1133 }
1134 }
John McCall66884dd2011-02-21 07:22:22 +00001135 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001136 // Check for VLAs; in standard C it would be possible to check this
1137 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1138 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001139 if (!VerifyOnly)
1140 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1141 diag::err_variable_object_no_init)
1142 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001143 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001144 ++Index;
1145 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001146 return;
1147 }
1148
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001149 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001150 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1151 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001152 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001153 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001154 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001155 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001156 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001157 maxElementsKnown = true;
1158 }
1159
John McCall66884dd2011-02-21 07:22:22 +00001160 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001161 while (Index < IList->getNumInits()) {
1162 Expr *Init = IList->getInit(Index);
1163 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001164 // If we're not the subobject that matches up with the '{' for
1165 // the designator, we shouldn't be handling the
1166 // designator. Return immediately.
1167 if (!SubobjectIsDesignatorContext)
1168 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001169
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001170 // Handle this designated initializer. elementIndex will be
1171 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001172 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001173 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001174 StructuredList, StructuredIndex, true,
1175 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001176 hadError = true;
1177 continue;
1178 }
1179
Douglas Gregor033d1252009-01-23 16:54:12 +00001180 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001181 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001182 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001183 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001184 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001185
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001186 // If the array is of incomplete type, keep track of the number of
1187 // elements in the initializer.
1188 if (!maxElementsKnown && elementIndex > maxElements)
1189 maxElements = elementIndex;
1190
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001191 continue;
1192 }
1193
1194 // If we know the maximum number of elements, and we've already
1195 // hit it, stop consuming elements in the initializer list.
1196 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001197 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001198
Anders Carlsson6cabf312010-01-23 23:23:01 +00001199 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001200 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001201 Entity);
1202 // Check this element.
1203 CheckSubElementType(ElementEntity, IList, elementType, Index,
1204 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001205 ++elementIndex;
1206
1207 // If the array is of incomplete type, keep track of the number of
1208 // elements in the initializer.
1209 if (!maxElementsKnown && elementIndex > maxElements)
1210 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001211 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001212 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001213 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001214 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001215 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001216 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001217 // Sizing an array implicitly to zero is not allowed by ISO C,
1218 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001219 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001220 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001221 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001222
Mike Stump11289f42009-09-09 15:08:12 +00001223 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001224 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001225 }
1226}
1227
Eli Friedman3fa64df2011-08-23 22:24:57 +00001228bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1229 Expr *InitExpr,
1230 FieldDecl *Field,
1231 bool TopLevelObject) {
1232 // Handle GNU flexible array initializers.
1233 unsigned FlexArrayDiag;
1234 if (isa<InitListExpr>(InitExpr) &&
1235 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1236 // Empty flexible array init always allowed as an extension
1237 FlexArrayDiag = diag::ext_flexible_array_init;
1238 } else if (SemaRef.getLangOptions().CPlusPlus) {
1239 // Disallow flexible array init in C++; it is not required for gcc
1240 // compatibility, and it needs work to IRGen correctly in general.
1241 FlexArrayDiag = diag::err_flexible_array_init;
1242 } else if (!TopLevelObject) {
1243 // Disallow flexible array init on non-top-level object
1244 FlexArrayDiag = diag::err_flexible_array_init;
1245 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1246 // Disallow flexible array init on anything which is not a variable.
1247 FlexArrayDiag = diag::err_flexible_array_init;
1248 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1249 // Disallow flexible array init on local variables.
1250 FlexArrayDiag = diag::err_flexible_array_init;
1251 } else {
1252 // Allow other cases.
1253 FlexArrayDiag = diag::ext_flexible_array_init;
1254 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001255
1256 if (!VerifyOnly) {
1257 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1258 FlexArrayDiag)
1259 << InitExpr->getSourceRange().getBegin();
1260 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1261 << Field;
1262 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001263
1264 return FlexArrayDiag != diag::ext_flexible_array_init;
1265}
1266
Anders Carlsson6cabf312010-01-23 23:23:01 +00001267void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001268 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001269 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001270 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001271 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001272 unsigned &Index,
1273 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001274 unsigned &StructuredIndex,
1275 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001276 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001277
Eli Friedman23a9e312008-05-19 19:16:24 +00001278 // If the record is invalid, some of it's members are invalid. To avoid
1279 // confusion, we forgo checking the intializer for the entire record.
1280 if (structDecl->isInvalidDecl()) {
1281 hadError = true;
1282 return;
Mike Stump11289f42009-09-09 15:08:12 +00001283 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001284
1285 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001286 if (!VerifyOnly) {
1287 // Value-initialize the first named member of the union.
1288 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1289 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1290 Field != FieldEnd; ++Field) {
1291 if (Field->getDeclName()) {
1292 StructuredList->setInitializedFieldInUnion(*Field);
1293 break;
1294 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001295 }
1296 }
1297 return;
1298 }
1299
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001300 // If structDecl is a forward declaration, this loop won't do
1301 // anything except look at designated initializers; That's okay,
1302 // because an error should get printed out elsewhere. It might be
1303 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001304 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001305 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001306 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001307 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001308 while (Index < IList->getNumInits()) {
1309 Expr *Init = IList->getInit(Index);
1310
1311 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001312 // If we're not the subobject that matches up with the '{' for
1313 // the designator, we shouldn't be handling the
1314 // designator. Return immediately.
1315 if (!SubobjectIsDesignatorContext)
1316 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001317
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001318 // Handle this designated initializer. Field will be updated to
1319 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001320 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001321 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001322 StructuredList, StructuredIndex,
1323 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001324 hadError = true;
1325
Douglas Gregora9add4e2009-02-12 19:00:39 +00001326 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001327
1328 // Disable check for missing fields when designators are used.
1329 // This matches gcc behaviour.
1330 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001331 continue;
1332 }
1333
1334 if (Field == FieldEnd) {
1335 // We've run out of fields. We're done.
1336 break;
1337 }
1338
Douglas Gregora9add4e2009-02-12 19:00:39 +00001339 // We've already initialized a member of a union. We're done.
1340 if (InitializedSomething && DeclType->isUnionType())
1341 break;
1342
Douglas Gregor91f84212008-12-11 16:49:14 +00001343 // If we've hit the flexible array member at the end, we're done.
1344 if (Field->getType()->isIncompleteArrayType())
1345 break;
1346
Douglas Gregor51695702009-01-29 16:53:55 +00001347 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001348 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001349 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001350 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001351 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001352
Douglas Gregora82064c2011-06-29 21:51:31 +00001353 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001354 bool InvalidUse;
1355 if (VerifyOnly)
1356 InvalidUse = !SemaRef.CanUseDecl(*Field);
1357 else
1358 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1359 IList->getInit(Index)->getLocStart());
1360 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001361 ++Index;
1362 ++Field;
1363 hadError = true;
1364 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001365 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001366
Anders Carlsson6cabf312010-01-23 23:23:01 +00001367 InitializedEntity MemberEntity =
1368 InitializedEntity::InitializeMember(*Field, &Entity);
1369 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1370 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001371 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001372
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001373 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001374 // Initialize the first field within the union.
1375 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001376 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001377
1378 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001379 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001380
John McCalle40b58e2010-03-11 19:32:38 +00001381 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001382 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1383 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1384 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001385 // It is possible we have one or more unnamed bitfields remaining.
1386 // Find first (if any) named field and emit warning.
1387 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1388 it != end; ++it) {
1389 if (!it->isUnnamedBitfield()) {
1390 SemaRef.Diag(IList->getSourceRange().getEnd(),
1391 diag::warn_missing_field_initializers) << it->getName();
1392 break;
1393 }
1394 }
1395 }
1396
Mike Stump11289f42009-09-09 15:08:12 +00001397 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001398 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001399 return;
1400
Eli Friedman3fa64df2011-08-23 22:24:57 +00001401 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1402 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001403 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001404 ++Index;
1405 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001406 }
1407
Anders Carlsson6cabf312010-01-23 23:23:01 +00001408 InitializedEntity MemberEntity =
1409 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410
Anders Carlsson6cabf312010-01-23 23:23:01 +00001411 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001412 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001413 StructuredList, StructuredIndex);
1414 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001415 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001416 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001417}
Steve Narofff8ecff22008-05-01 22:18:59 +00001418
Douglas Gregord5846a12009-04-15 06:41:24 +00001419/// \brief Expand a field designator that refers to a member of an
1420/// anonymous struct or union into a series of field designators that
1421/// refers to the field within the appropriate subobject.
1422///
Douglas Gregord5846a12009-04-15 06:41:24 +00001423static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001424 DesignatedInitExpr *DIE,
1425 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001426 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001427 typedef DesignatedInitExpr::Designator Designator;
1428
Douglas Gregord5846a12009-04-15 06:41:24 +00001429 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001430 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001431 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1432 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1433 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001434 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001435 DIE->getDesignator(DesigIdx)->getDotLoc(),
1436 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1437 else
1438 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1439 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001440 assert(isa<FieldDecl>(*PI));
1441 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001442 }
1443
1444 // Expand the current designator into the set of replacement
1445 // designators, so we have a full subobject path down to where the
1446 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001447 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001448 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001449}
Mike Stump11289f42009-09-09 15:08:12 +00001450
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001451/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001452/// corresponds to FieldName.
1453static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1454 IdentifierInfo *FieldName) {
1455 assert(AnonField->isAnonymousStructOrUnion());
1456 Decl *NextDecl = AnonField->getNextDeclInContext();
1457 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1458 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1459 return IF;
1460 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001461 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001462 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001463}
1464
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001465static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1466 DesignatedInitExpr *DIE) {
1467 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1468 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1469 for (unsigned I = 0; I < NumIndexExprs; ++I)
1470 IndexExprs[I] = DIE->getSubExpr(I + 1);
1471 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1472 DIE->size(), IndexExprs.data(),
1473 NumIndexExprs, DIE->getEqualOrColonLoc(),
1474 DIE->usesGNUSyntax(), DIE->getInit());
1475}
1476
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001477/// @brief Check the well-formedness of a C99 designated initializer.
1478///
1479/// Determines whether the designated initializer @p DIE, which
1480/// resides at the given @p Index within the initializer list @p
1481/// IList, is well-formed for a current object of type @p DeclType
1482/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001483/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001484/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001485///
1486/// @param IList The initializer list in which this designated
1487/// initializer occurs.
1488///
Douglas Gregora5324162009-04-15 04:56:10 +00001489/// @param DIE The designated initializer expression.
1490///
1491/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001492///
1493/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1494/// into which the designation in @p DIE should refer.
1495///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001496/// @param NextField If non-NULL and the first designator in @p DIE is
1497/// a field, this will be set to the field declaration corresponding
1498/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001499///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001500/// @param NextElementIndex If non-NULL and the first designator in @p
1501/// DIE is an array designator or GNU array-range designator, this
1502/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001503///
1504/// @param Index Index into @p IList where the designated initializer
1505/// @p DIE occurs.
1506///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001507/// @param StructuredList The initializer list expression that
1508/// describes all of the subobject initializers in the order they'll
1509/// actually be initialized.
1510///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001511/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001512bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001513InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001514 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001515 DesignatedInitExpr *DIE,
1516 unsigned DesigIdx,
1517 QualType &CurrentObjectType,
1518 RecordDecl::field_iterator *NextField,
1519 llvm::APSInt *NextElementIndex,
1520 unsigned &Index,
1521 InitListExpr *StructuredList,
1522 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001523 bool FinishSubobjectInit,
1524 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001525 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001526 // Check the actual initialization for the designated object type.
1527 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001528
1529 // Temporarily remove the designator expression from the
1530 // initializer list that the child calls see, so that we don't try
1531 // to re-process the designator.
1532 unsigned OldIndex = Index;
1533 IList->setInit(OldIndex, DIE->getInit());
1534
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001535 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001536 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001537
1538 // Restore the designated initializer expression in the syntactic
1539 // form of the initializer list.
1540 if (IList->getInit(OldIndex) != DIE->getInit())
1541 DIE->setInit(IList->getInit(OldIndex));
1542 IList->setInit(OldIndex, DIE);
1543
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001544 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001545 }
1546
Douglas Gregora5324162009-04-15 04:56:10 +00001547 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001548 bool IsFirstDesignator = (DesigIdx == 0);
1549 if (!VerifyOnly) {
1550 assert((IsFirstDesignator || StructuredList) &&
1551 "Need a non-designated initializer list to start from");
1552
1553 // Determine the structural initializer list that corresponds to the
1554 // current subobject.
1555 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1556 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1557 StructuredList, StructuredIndex,
1558 SourceRange(D->getStartLocation(),
1559 DIE->getSourceRange().getEnd()));
1560 assert(StructuredList && "Expected a structured initializer list");
1561 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001562
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001563 if (D->isFieldDesignator()) {
1564 // C99 6.7.8p7:
1565 //
1566 // If a designator has the form
1567 //
1568 // . identifier
1569 //
1570 // then the current object (defined below) shall have
1571 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001572 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001573 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001574 if (!RT) {
1575 SourceLocation Loc = D->getDotLoc();
1576 if (Loc.isInvalid())
1577 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001578 if (!VerifyOnly)
1579 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1580 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001581 ++Index;
1582 return true;
1583 }
1584
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001585 // Note: we perform a linear search of the fields here, despite
1586 // the fact that we have a faster lookup method, because we always
1587 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001588 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001589 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001590 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001591 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001592 Field = RT->getDecl()->field_begin(),
1593 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001594 for (; Field != FieldEnd; ++Field) {
1595 if (Field->isUnnamedBitfield())
1596 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001598 // If we find a field representing an anonymous field, look in the
1599 // IndirectFieldDecl that follow for the designated initializer.
1600 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1601 if (IndirectFieldDecl *IF =
1602 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001603 // In verify mode, don't modify the original.
1604 if (VerifyOnly)
1605 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001606 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1607 D = DIE->getDesignator(DesigIdx);
1608 break;
1609 }
1610 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001611 if (KnownField && KnownField == *Field)
1612 break;
1613 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001614 break;
1615
1616 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001617 }
1618
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001619 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001620 if (VerifyOnly) {
1621 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001622 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001623 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001624
Douglas Gregord5846a12009-04-15 06:41:24 +00001625 // There was no normal field in the struct with the designated
1626 // name. Perform another lookup for this name, which may find
1627 // something that we can't designate (e.g., a member function),
1628 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001629 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001630 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001631 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001632 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001633 // Name lookup didn't find anything. Determine whether this
1634 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001635 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001636 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001637 TypoCorrection Corrected = SemaRef.CorrectTypo(
1638 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1639 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1640 RT->getDecl(), false, Sema::CTC_NoKeywords);
1641 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001642 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001643 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001644 std::string CorrectedStr(
1645 Corrected.getAsString(SemaRef.getLangOptions()));
1646 std::string CorrectedQuotedStr(
1647 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001648 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001649 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001650 << FieldName << CurrentObjectType << CorrectedQuotedStr
1651 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001652 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001653 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001654 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001655 } else {
1656 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1657 << FieldName << CurrentObjectType;
1658 ++Index;
1659 return true;
1660 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001662
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001663 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001664 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001665 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001666 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001667 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001668 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001669 ++Index;
1670 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001671 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001672
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001673 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001674 // The replacement field comes from typo correction; find it
1675 // in the list of fields.
1676 FieldIndex = 0;
1677 Field = RT->getDecl()->field_begin();
1678 for (; Field != FieldEnd; ++Field) {
1679 if (Field->isUnnamedBitfield())
1680 continue;
1681
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001682 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001683 Field->getIdentifier() == ReplacementField->getIdentifier())
1684 break;
1685
1686 ++FieldIndex;
1687 }
1688 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001689 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001690
1691 // All of the fields of a union are located at the same place in
1692 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001693 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001694 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001695 if (!VerifyOnly)
1696 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001697 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001698
Douglas Gregora82064c2011-06-29 21:51:31 +00001699 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001700 bool InvalidUse;
1701 if (VerifyOnly)
1702 InvalidUse = !SemaRef.CanUseDecl(*Field);
1703 else
1704 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1705 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001706 ++Index;
1707 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001708 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001709
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001710 if (!VerifyOnly) {
1711 // Update the designator with the field declaration.
1712 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001713
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001714 // Make sure that our non-designated initializer list has space
1715 // for a subobject corresponding to this field.
1716 if (FieldIndex >= StructuredList->getNumInits())
1717 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1718 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001719
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001720 // This designator names a flexible array member.
1721 if (Field->getType()->isIncompleteArrayType()) {
1722 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001723 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001724 // We can't designate an object within the flexible array
1725 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001726 if (!VerifyOnly) {
1727 DesignatedInitExpr::Designator *NextD
1728 = DIE->getDesignator(DesigIdx + 1);
1729 SemaRef.Diag(NextD->getStartLocation(),
1730 diag::err_designator_into_flexible_array_member)
1731 << SourceRange(NextD->getStartLocation(),
1732 DIE->getSourceRange().getEnd());
1733 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1734 << *Field;
1735 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001736 Invalid = true;
1737 }
1738
Chris Lattner001b29c2010-10-10 17:49:49 +00001739 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1740 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001741 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001742 if (!VerifyOnly) {
1743 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1744 diag::err_flexible_array_init_needs_braces)
1745 << DIE->getInit()->getSourceRange();
1746 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1747 << *Field;
1748 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001749 Invalid = true;
1750 }
1751
Eli Friedman3fa64df2011-08-23 22:24:57 +00001752 // Check GNU flexible array initializer.
1753 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1754 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001755 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001756
1757 if (Invalid) {
1758 ++Index;
1759 return true;
1760 }
1761
1762 // Initialize the array.
1763 bool prevHadError = hadError;
1764 unsigned newStructuredIndex = FieldIndex;
1765 unsigned OldIndex = Index;
1766 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001767
1768 InitializedEntity MemberEntity =
1769 InitializedEntity::InitializeMember(*Field, &Entity);
1770 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001771 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001772
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001773 IList->setInit(OldIndex, DIE);
1774 if (hadError && !prevHadError) {
1775 ++Field;
1776 ++FieldIndex;
1777 if (NextField)
1778 *NextField = Field;
1779 StructuredIndex = FieldIndex;
1780 return true;
1781 }
1782 } else {
1783 // Recurse to check later designated subobjects.
1784 QualType FieldType = (*Field)->getType();
1785 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001787 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001788 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001789 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1790 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001791 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001792 true, false))
1793 return true;
1794 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001795
1796 // Find the position of the next field to be initialized in this
1797 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001798 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001799 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001800
1801 // If this the first designator, our caller will continue checking
1802 // the rest of this struct/class/union subobject.
1803 if (IsFirstDesignator) {
1804 if (NextField)
1805 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001806 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001807 return false;
1808 }
1809
Douglas Gregor17bd0942009-01-28 23:36:17 +00001810 if (!FinishSubobjectInit)
1811 return false;
1812
Douglas Gregord5846a12009-04-15 06:41:24 +00001813 // We've already initialized something in the union; we're done.
1814 if (RT->getDecl()->isUnion())
1815 return hadError;
1816
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001817 // Check the remaining fields within this class/struct/union subobject.
1818 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001819
Anders Carlsson6cabf312010-01-23 23:23:01 +00001820 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001821 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001822 return hadError && !prevHadError;
1823 }
1824
1825 // C99 6.7.8p6:
1826 //
1827 // If a designator has the form
1828 //
1829 // [ constant-expression ]
1830 //
1831 // then the current object (defined below) shall have array
1832 // type and the expression shall be an integer constant
1833 // expression. If the array is of unknown size, any
1834 // nonnegative value is valid.
1835 //
1836 // Additionally, cope with the GNU extension that permits
1837 // designators of the form
1838 //
1839 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001840 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001841 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001842 if (!VerifyOnly)
1843 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1844 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001845 ++Index;
1846 return true;
1847 }
1848
1849 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001850 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1851 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001852 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001853 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001854 DesignatedEndIndex = DesignatedStartIndex;
1855 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001856 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001857
Mike Stump11289f42009-09-09 15:08:12 +00001858 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001859 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001860 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001861 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001862 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001863
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001864 // Codegen can't handle evaluating array range designators that have side
1865 // effects, because we replicate the AST value for each initialized element.
1866 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1867 // elements with something that has a side effect, so codegen can emit an
1868 // "error unsupported" error instead of miscompiling the app.
1869 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001870 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001871 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001872 }
1873
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001874 if (isa<ConstantArrayType>(AT)) {
1875 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001876 DesignatedStartIndex
1877 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001878 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001879 DesignatedEndIndex
1880 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001881 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1882 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001883 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001884 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1885 diag::err_array_designator_too_large)
1886 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1887 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001888 ++Index;
1889 return true;
1890 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001891 } else {
1892 // Make sure the bit-widths and signedness match.
1893 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001894 DesignatedEndIndex
1895 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001896 else if (DesignatedStartIndex.getBitWidth() <
1897 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001898 DesignatedStartIndex
1899 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001900 DesignatedStartIndex.setIsUnsigned(true);
1901 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001902 }
Mike Stump11289f42009-09-09 15:08:12 +00001903
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001904 // Make sure that our non-designated initializer list has space
1905 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001906 if (!VerifyOnly &&
1907 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001908 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001909 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001910
Douglas Gregor17bd0942009-01-28 23:36:17 +00001911 // Repeatedly perform subobject initializations in the range
1912 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001913
Douglas Gregor17bd0942009-01-28 23:36:17 +00001914 // Move to the next designator
1915 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1916 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001918 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001919 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001920
Douglas Gregor17bd0942009-01-28 23:36:17 +00001921 while (DesignatedStartIndex <= DesignatedEndIndex) {
1922 // Recurse to check later designated subobjects.
1923 QualType ElementType = AT->getElementType();
1924 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001926 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1928 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001929 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001930 (DesignatedStartIndex == DesignatedEndIndex),
1931 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001932 return true;
1933
1934 // Move to the next index in the array that we'll be initializing.
1935 ++DesignatedStartIndex;
1936 ElementIndex = DesignatedStartIndex.getZExtValue();
1937 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001938
1939 // If this the first designator, our caller will continue checking
1940 // the rest of this array subobject.
1941 if (IsFirstDesignator) {
1942 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001943 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001944 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001945 return false;
1946 }
Mike Stump11289f42009-09-09 15:08:12 +00001947
Douglas Gregor17bd0942009-01-28 23:36:17 +00001948 if (!FinishSubobjectInit)
1949 return false;
1950
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001951 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001952 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001954 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001955 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001956 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001957}
1958
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001959// Get the structured initializer list for a subobject of type
1960// @p CurrentObjectType.
1961InitListExpr *
1962InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1963 QualType CurrentObjectType,
1964 InitListExpr *StructuredList,
1965 unsigned StructuredIndex,
1966 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001967 if (VerifyOnly)
1968 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001969 Expr *ExistingInit = 0;
1970 if (!StructuredList)
1971 ExistingInit = SyntacticToSemantic[IList];
1972 else if (StructuredIndex < StructuredList->getNumInits())
1973 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001974
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001975 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1976 return Result;
1977
1978 if (ExistingInit) {
1979 // We are creating an initializer list that initializes the
1980 // subobjects of the current object, but there was already an
1981 // initialization that completely initialized the current
1982 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001983 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001984 // struct X { int a, b; };
1985 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001986 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001987 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1988 // designated initializer re-initializes the whole
1989 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001990 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001991 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001992 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001993 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001994 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001995 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001996 << ExistingInit->getSourceRange();
1997 }
1998
Mike Stump11289f42009-09-09 15:08:12 +00001999 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002000 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2001 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002002 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002003
Douglas Gregora8a089b2010-07-13 18:40:04 +00002004 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002005
Douglas Gregor6d00c992009-03-20 23:58:33 +00002006 // Pre-allocate storage for the structured initializer list.
2007 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002008 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002009 bool GotNumInits = false;
2010 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002011 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002012 GotNumInits = true;
2013 } else if (Index < IList->getNumInits()) {
2014 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002015 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002016 GotNumInits = true;
2017 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002018 }
2019
Mike Stump11289f42009-09-09 15:08:12 +00002020 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002021 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2022 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2023 NumElements = CAType->getSize().getZExtValue();
2024 // Simple heuristic so that we don't allocate a very large
2025 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002026 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002027 NumElements = 0;
2028 }
John McCall9dd450b2009-09-21 23:43:11 +00002029 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002030 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002031 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002032 RecordDecl *RDecl = RType->getDecl();
2033 if (RDecl->isUnion())
2034 NumElements = 1;
2035 else
Mike Stump11289f42009-09-09 15:08:12 +00002036 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002037 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002038 }
2039
Douglas Gregor221c9a52009-03-21 18:13:52 +00002040 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002041 NumElements = IList->getNumInits();
2042
Ted Kremenekac034612010-04-13 23:39:13 +00002043 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002044
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002045 // Link this new initializer list into the structured initializer
2046 // lists.
2047 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002048 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002049 else {
2050 Result->setSyntacticForm(IList);
2051 SyntacticToSemantic[IList] = Result;
2052 }
2053
2054 return Result;
2055}
2056
2057/// Update the initializer at index @p StructuredIndex within the
2058/// structured initializer list to the value @p expr.
2059void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2060 unsigned &StructuredIndex,
2061 Expr *expr) {
2062 // No structured initializer list to update
2063 if (!StructuredList)
2064 return;
2065
Ted Kremenekac034612010-04-13 23:39:13 +00002066 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2067 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002068 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002069 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002070 diag::warn_initializer_overrides)
2071 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002072 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002073 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002074 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002075 << PrevInit->getSourceRange();
2076 }
Mike Stump11289f42009-09-09 15:08:12 +00002077
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002078 ++StructuredIndex;
2079}
2080
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002081/// Check that the given Index expression is a valid array designator
2082/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002083/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002084/// and produces a reasonable diagnostic if there is a
2085/// failure. Returns true if there was an error, false otherwise. If
2086/// everything went okay, Value will receive the value of the constant
2087/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00002088static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002089CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002090 SourceLocation Loc = Index->getSourceRange().getBegin();
2091
2092 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002093 if (S.VerifyIntegerConstantExpression(Index, &Value))
2094 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002095
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002096 if (Value.isSigned() && Value.isNegative())
2097 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002098 << Value.toString(10) << Index->getSourceRange();
2099
Douglas Gregor51650d32009-01-23 21:04:18 +00002100 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002101 return false;
2102}
2103
John McCalldadc5752010-08-24 06:29:42 +00002104ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002105 SourceLocation Loc,
2106 bool GNUSyntax,
2107 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002108 typedef DesignatedInitExpr::Designator ASTDesignator;
2109
2110 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002111 SmallVector<ASTDesignator, 32> Designators;
2112 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002113
2114 // Build designators and check array designator expressions.
2115 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2116 const Designator &D = Desig.getDesignator(Idx);
2117 switch (D.getKind()) {
2118 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002119 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002120 D.getFieldLoc()));
2121 break;
2122
2123 case Designator::ArrayDesignator: {
2124 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2125 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002126 if (!Index->isTypeDependent() &&
2127 !Index->isValueDependent() &&
2128 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002129 Invalid = true;
2130 else {
2131 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002132 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002133 D.getRBracketLoc()));
2134 InitExpressions.push_back(Index);
2135 }
2136 break;
2137 }
2138
2139 case Designator::ArrayRangeDesignator: {
2140 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2141 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2142 llvm::APSInt StartValue;
2143 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002144 bool StartDependent = StartIndex->isTypeDependent() ||
2145 StartIndex->isValueDependent();
2146 bool EndDependent = EndIndex->isTypeDependent() ||
2147 EndIndex->isValueDependent();
2148 if ((!StartDependent &&
2149 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2150 (!EndDependent &&
2151 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002152 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002153 else {
2154 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002155 if (StartDependent || EndDependent) {
2156 // Nothing to compute.
2157 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002158 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002159 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002160 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002161
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002162 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002163 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002164 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002165 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2166 Invalid = true;
2167 } else {
2168 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002169 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002170 D.getEllipsisLoc(),
2171 D.getRBracketLoc()));
2172 InitExpressions.push_back(StartIndex);
2173 InitExpressions.push_back(EndIndex);
2174 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002175 }
2176 break;
2177 }
2178 }
2179 }
2180
2181 if (Invalid || Init.isInvalid())
2182 return ExprError();
2183
2184 // Clear out the expressions within the designation.
2185 Desig.ClearExprs(*this);
2186
2187 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002188 = DesignatedInitExpr::Create(Context,
2189 Designators.data(), Designators.size(),
2190 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002191 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002192
Douglas Gregorc124e592011-01-16 16:13:16 +00002193 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002194 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2195 << DIE->getSourceRange();
2196 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002197 Diag(DIE->getLocStart(), diag::ext_designated_init)
2198 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002199
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002200 return Owned(DIE);
2201}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002202
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002203//===----------------------------------------------------------------------===//
2204// Initialization entity
2205//===----------------------------------------------------------------------===//
2206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002208 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002209 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002210{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002211 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2212 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002213 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002214 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002215 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002216 Type = VT->getElementType();
2217 } else {
2218 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2219 assert(CT && "Unexpected type");
2220 Kind = EK_ComplexElement;
2221 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002222 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002223}
2224
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002225InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002226 CXXBaseSpecifier *Base,
2227 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002228{
2229 InitializedEntity Result;
2230 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002231 Result.Base = reinterpret_cast<uintptr_t>(Base);
2232 if (IsInheritedVirtualBase)
2233 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002234
Douglas Gregor1b303932009-12-22 15:35:07 +00002235 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002236 return Result;
2237}
2238
Douglas Gregor85dabae2009-12-16 01:38:02 +00002239DeclarationName InitializedEntity::getName() const {
2240 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002241 case EK_Parameter: {
2242 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2243 return (D ? D->getDeclName() : DeclarationName());
2244 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002245
2246 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002247 case EK_Member:
2248 return VariableOrMember->getDeclName();
2249
2250 case EK_Result:
2251 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002252 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002253 case EK_Temporary:
2254 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002255 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002256 case EK_ArrayElement:
2257 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002258 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002259 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002260 return DeclarationName();
2261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262
Douglas Gregor85dabae2009-12-16 01:38:02 +00002263 // Silence GCC warning
2264 return DeclarationName();
2265}
2266
Douglas Gregora4b592a2009-12-19 03:01:41 +00002267DeclaratorDecl *InitializedEntity::getDecl() const {
2268 switch (getKind()) {
2269 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002270 case EK_Member:
2271 return VariableOrMember;
2272
John McCall31168b02011-06-15 23:02:42 +00002273 case EK_Parameter:
2274 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2275
Douglas Gregora4b592a2009-12-19 03:01:41 +00002276 case EK_Result:
2277 case EK_Exception:
2278 case EK_New:
2279 case EK_Temporary:
2280 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002281 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002282 case EK_ArrayElement:
2283 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002284 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002285 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002286 return 0;
2287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002288
Douglas Gregora4b592a2009-12-19 03:01:41 +00002289 // Silence GCC warning
2290 return 0;
2291}
2292
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002293bool InitializedEntity::allowsNRVO() const {
2294 switch (getKind()) {
2295 case EK_Result:
2296 case EK_Exception:
2297 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002299 case EK_Variable:
2300 case EK_Parameter:
2301 case EK_Member:
2302 case EK_New:
2303 case EK_Temporary:
2304 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002305 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002306 case EK_ArrayElement:
2307 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002308 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002309 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002310 break;
2311 }
2312
2313 return false;
2314}
2315
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002316//===----------------------------------------------------------------------===//
2317// Initialization sequence
2318//===----------------------------------------------------------------------===//
2319
2320void InitializationSequence::Step::Destroy() {
2321 switch (Kind) {
2322 case SK_ResolveAddressOfOverloadedFunction:
2323 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002324 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002325 case SK_CastDerivedToBaseLValue:
2326 case SK_BindReference:
2327 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002328 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002329 case SK_UserConversion:
2330 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002331 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002332 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002333 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002334 case SK_ListConstructorCall:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002335 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002336 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002337 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002338 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002339 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002340 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002341 case SK_PassByIndirectCopyRestore:
2342 case SK_PassByIndirectRestore:
2343 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002344 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002345
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002346 case SK_ConversionSequence:
2347 delete ICS;
2348 }
2349}
2350
Douglas Gregor838fcc32010-03-26 20:14:36 +00002351bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002352 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002353}
2354
2355bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002356 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002357 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002358
Douglas Gregor838fcc32010-03-26 20:14:36 +00002359 switch (getFailureKind()) {
2360 case FK_TooManyInitsForReference:
2361 case FK_ArrayNeedsInitList:
2362 case FK_ArrayNeedsInitListOrStringLiteral:
2363 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2364 case FK_NonConstLValueReferenceBindingToTemporary:
2365 case FK_NonConstLValueReferenceBindingToUnrelated:
2366 case FK_RValueReferenceBindingToLValue:
2367 case FK_ReferenceInitDropsQualifiers:
2368 case FK_ReferenceInitFailed:
2369 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002370 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002371 case FK_TooManyInitsForScalar:
2372 case FK_ReferenceBindingToInitList:
2373 case FK_InitListBadDestinationType:
2374 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002375 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002376 case FK_ArrayTypeMismatch:
2377 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002378 case FK_ListInitializationFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002379 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002380
Douglas Gregor838fcc32010-03-26 20:14:36 +00002381 case FK_ReferenceInitOverloadFailed:
2382 case FK_UserConversionOverloadFailed:
2383 case FK_ConstructorOverloadFailed:
2384 return FailedOverloadResult == OR_Ambiguous;
2385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002386
Douglas Gregor838fcc32010-03-26 20:14:36 +00002387 return false;
2388}
2389
Douglas Gregorb33eed02010-04-16 22:09:46 +00002390bool InitializationSequence::isConstructorInitialization() const {
2391 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2392}
2393
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002394bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2395 const Expr *Initializer,
2396 bool *isInitializerConstant,
2397 APValue *ConstantValue) const {
2398 if (Steps.empty() || Initializer->isValueDependent())
2399 return false;
2400
2401 const Step &LastStep = Steps.back();
2402 if (LastStep.Kind != SK_ConversionSequence)
2403 return false;
2404
2405 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2406 const StandardConversionSequence *SCS = NULL;
2407 switch (ICS.getKind()) {
2408 case ImplicitConversionSequence::StandardConversion:
2409 SCS = &ICS.Standard;
2410 break;
2411 case ImplicitConversionSequence::UserDefinedConversion:
2412 SCS = &ICS.UserDefined.After;
2413 break;
2414 case ImplicitConversionSequence::AmbiguousConversion:
2415 case ImplicitConversionSequence::EllipsisConversion:
2416 case ImplicitConversionSequence::BadConversion:
2417 return false;
2418 }
2419
2420 // Check if SCS represents a narrowing conversion, according to C++0x
2421 // [dcl.init.list]p7:
2422 //
2423 // A narrowing conversion is an implicit conversion ...
2424 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2425 QualType FromType = SCS->getToType(0);
2426 QualType ToType = SCS->getToType(1);
2427 switch (PossibleNarrowing) {
2428 // * from a floating-point type to an integer type, or
2429 //
2430 // * from an integer type or unscoped enumeration type to a floating-point
2431 // type, except where the source is a constant expression and the actual
2432 // value after conversion will fit into the target type and will produce
2433 // the original value when converted back to the original type, or
2434 case ICK_Floating_Integral:
2435 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2436 *isInitializerConstant = false;
2437 return true;
2438 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2439 llvm::APSInt IntConstantValue;
2440 if (Initializer &&
2441 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2442 // Convert the integer to the floating type.
2443 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2444 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2445 llvm::APFloat::rmNearestTiesToEven);
2446 // And back.
2447 llvm::APSInt ConvertedValue = IntConstantValue;
2448 bool ignored;
2449 Result.convertToInteger(ConvertedValue,
2450 llvm::APFloat::rmTowardZero, &ignored);
2451 // If the resulting value is different, this was a narrowing conversion.
2452 if (IntConstantValue != ConvertedValue) {
2453 *isInitializerConstant = true;
2454 *ConstantValue = APValue(IntConstantValue);
2455 return true;
2456 }
2457 } else {
2458 // Variables are always narrowings.
2459 *isInitializerConstant = false;
2460 return true;
2461 }
2462 }
2463 return false;
2464
2465 // * from long double to double or float, or from double to float, except
2466 // where the source is a constant expression and the actual value after
2467 // conversion is within the range of values that can be represented (even
2468 // if it cannot be represented exactly), or
2469 case ICK_Floating_Conversion:
2470 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2471 // FromType is larger than ToType.
2472 Expr::EvalResult InitializerValue;
2473 // FIXME: Check whether Initializer is a constant expression according
2474 // to C++0x [expr.const], rather than just whether it can be folded.
2475 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2476 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2477 // Constant! (Except for FIXME above.)
2478 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2479 // Convert the source value into the target type.
2480 bool ignored;
2481 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2482 Ctx.getFloatTypeSemantics(ToType),
2483 llvm::APFloat::rmNearestTiesToEven, &ignored);
2484 // If there was no overflow, the source value is within the range of
2485 // values that can be represented.
2486 if (ConvertStatus & llvm::APFloat::opOverflow) {
2487 *isInitializerConstant = true;
2488 *ConstantValue = InitializerValue.Val;
2489 return true;
2490 }
2491 } else {
2492 *isInitializerConstant = false;
2493 return true;
2494 }
2495 }
2496 return false;
2497
2498 // * from an integer type or unscoped enumeration type to an integer type
2499 // that cannot represent all the values of the original type, except where
2500 // the source is a constant expression and the actual value after
2501 // conversion will fit into the target type and will produce the original
2502 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002503 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002504 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2505 // Boolean conversions can be from pointers and pointers to members
2506 // [conv.bool], and those aren't considered narrowing conversions.
2507 return false;
2508 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002509 case ICK_Integral_Conversion: {
2510 assert(FromType->isIntegralOrUnscopedEnumerationType());
2511 assert(ToType->isIntegralOrUnscopedEnumerationType());
2512 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2513 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2514 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2515 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2516
2517 if (FromWidth > ToWidth ||
2518 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2519 // Not all values of FromType can be represented in ToType.
2520 llvm::APSInt InitializerValue;
2521 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2522 *isInitializerConstant = true;
2523 *ConstantValue = APValue(InitializerValue);
2524
2525 // Add a bit to the InitializerValue so we don't have to worry about
2526 // signed vs. unsigned comparisons.
2527 InitializerValue = InitializerValue.extend(
2528 InitializerValue.getBitWidth() + 1);
2529 // Convert the initializer to and from the target width and signed-ness.
2530 llvm::APSInt ConvertedValue = InitializerValue;
2531 ConvertedValue = ConvertedValue.trunc(ToWidth);
2532 ConvertedValue.setIsSigned(ToSigned);
2533 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2534 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2535 // If the result is different, this was a narrowing conversion.
2536 return ConvertedValue != InitializerValue;
2537 } else {
2538 // Variables are always narrowings.
2539 *isInitializerConstant = false;
2540 return true;
2541 }
2542 }
2543 return false;
2544 }
2545
2546 default:
2547 // Other kinds of conversions are not narrowings.
2548 return false;
2549 }
2550}
2551
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002552void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002553 FunctionDecl *Function,
2554 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002555 Step S;
2556 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2557 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002558 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002559 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002560 Steps.push_back(S);
2561}
2562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002563void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002564 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002565 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002566 switch (VK) {
2567 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2568 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2569 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002570 default: llvm_unreachable("No such category");
2571 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002572 S.Type = BaseType;
2573 Steps.push_back(S);
2574}
2575
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002577 bool BindingTemporary) {
2578 Step S;
2579 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2580 S.Type = T;
2581 Steps.push_back(S);
2582}
2583
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002584void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2585 Step S;
2586 S.Kind = SK_ExtraneousCopyToTemporary;
2587 S.Type = T;
2588 Steps.push_back(S);
2589}
2590
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002591void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002592 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002593 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002594 Step S;
2595 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002596 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002597 S.Function.Function = Function;
2598 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002599 Steps.push_back(S);
2600}
2601
2602void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002603 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002604 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002605 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002606 switch (VK) {
2607 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002608 S.Kind = SK_QualificationConversionRValue;
2609 break;
John McCall2536c6d2010-08-25 10:28:54 +00002610 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002611 S.Kind = SK_QualificationConversionXValue;
2612 break;
John McCall2536c6d2010-08-25 10:28:54 +00002613 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002614 S.Kind = SK_QualificationConversionLValue;
2615 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002616 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002617 S.Type = Ty;
2618 Steps.push_back(S);
2619}
2620
2621void InitializationSequence::AddConversionSequenceStep(
2622 const ImplicitConversionSequence &ICS,
2623 QualType T) {
2624 Step S;
2625 S.Kind = SK_ConversionSequence;
2626 S.Type = T;
2627 S.ICS = new ImplicitConversionSequence(ICS);
2628 Steps.push_back(S);
2629}
2630
Douglas Gregor51e77d52009-12-10 17:56:55 +00002631void InitializationSequence::AddListInitializationStep(QualType T) {
2632 Step S;
2633 S.Kind = SK_ListInitialization;
2634 S.Type = T;
2635 Steps.push_back(S);
2636}
2637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002639InitializationSequence::AddConstructorInitializationStep(
2640 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002641 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002642 QualType T) {
2643 Step S;
2644 S.Kind = SK_ConstructorInitialization;
2645 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002646 S.Function.Function = Constructor;
2647 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002648 Steps.push_back(S);
2649}
2650
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002651void InitializationSequence::AddZeroInitializationStep(QualType T) {
2652 Step S;
2653 S.Kind = SK_ZeroInitialization;
2654 S.Type = T;
2655 Steps.push_back(S);
2656}
2657
Douglas Gregore1314a62009-12-18 05:02:21 +00002658void InitializationSequence::AddCAssignmentStep(QualType T) {
2659 Step S;
2660 S.Kind = SK_CAssignment;
2661 S.Type = T;
2662 Steps.push_back(S);
2663}
2664
Eli Friedman78275202009-12-19 08:11:05 +00002665void InitializationSequence::AddStringInitStep(QualType T) {
2666 Step S;
2667 S.Kind = SK_StringInit;
2668 S.Type = T;
2669 Steps.push_back(S);
2670}
2671
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002672void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2673 Step S;
2674 S.Kind = SK_ObjCObjectConversion;
2675 S.Type = T;
2676 Steps.push_back(S);
2677}
2678
Douglas Gregore2f943b2011-02-22 18:29:51 +00002679void InitializationSequence::AddArrayInitStep(QualType T) {
2680 Step S;
2681 S.Kind = SK_ArrayInit;
2682 S.Type = T;
2683 Steps.push_back(S);
2684}
2685
John McCall31168b02011-06-15 23:02:42 +00002686void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2687 bool shouldCopy) {
2688 Step s;
2689 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2690 : SK_PassByIndirectRestore);
2691 s.Type = type;
2692 Steps.push_back(s);
2693}
2694
2695void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2696 Step S;
2697 S.Kind = SK_ProduceObjCObject;
2698 S.Type = T;
2699 Steps.push_back(S);
2700}
2701
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002703 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002704 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002705 this->Failure = Failure;
2706 this->FailedOverloadResult = Result;
2707}
2708
2709//===----------------------------------------------------------------------===//
2710// Attempt initialization
2711//===----------------------------------------------------------------------===//
2712
John McCall31168b02011-06-15 23:02:42 +00002713static void MaybeProduceObjCObject(Sema &S,
2714 InitializationSequence &Sequence,
2715 const InitializedEntity &Entity) {
2716 if (!S.getLangOptions().ObjCAutoRefCount) return;
2717
2718 /// When initializing a parameter, produce the value if it's marked
2719 /// __attribute__((ns_consumed)).
2720 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2721 if (!Entity.isParameterConsumed())
2722 return;
2723
2724 assert(Entity.getType()->isObjCRetainableType() &&
2725 "consuming an object of unretainable type?");
2726 Sequence.AddProduceObjCObjectStep(Entity.getType());
2727
2728 /// When initializing a return value, if the return type is a
2729 /// retainable type, then returns need to immediately retain the
2730 /// object. If an autorelease is required, it will be done at the
2731 /// last instant.
2732 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2733 if (!Entity.getType()->isObjCRetainableType())
2734 return;
2735
2736 Sequence.AddProduceObjCObjectStep(Entity.getType());
2737 }
2738}
2739
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002740/// \brief Attempt list initialization (C++0x [dcl.init.list])
2741static void TryListInitialization(Sema &S,
2742 const InitializedEntity &Entity,
2743 const InitializationKind &Kind,
2744 InitListExpr *InitList,
2745 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002746 QualType DestType = Entity.getType();
2747
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002748 // C++ doesn't allow scalar initialization with more than one argument.
2749 // But C99 complex numbers are scalars and it makes sense there.
2750 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2751 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2752 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2753 return;
2754 }
2755 // FIXME: C++0x defines behavior for these two cases.
2756 if (DestType->isReferenceType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002757 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2758 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002759 }
2760 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002761 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002762 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002763 }
2764
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002765 InitListChecker CheckInitList(S, Entity, InitList,
2766 DestType, /*VerifyOnly=*/true);
2767 if (CheckInitList.HadError()) {
2768 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2769 return;
2770 }
2771
2772 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002773 Sequence.AddListInitializationStep(DestType);
2774}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002775
2776/// \brief Try a reference initialization that involves calling a conversion
2777/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002778static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2779 const InitializedEntity &Entity,
2780 const InitializationKind &Kind,
2781 Expr *Initializer,
2782 bool AllowRValues,
2783 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002784 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002785 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2786 QualType T1 = cv1T1.getUnqualifiedType();
2787 QualType cv2T2 = Initializer->getType();
2788 QualType T2 = cv2T2.getUnqualifiedType();
2789
2790 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002791 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002792 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002793 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002794 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002795 ObjCConversion,
2796 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002797 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002798 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002799 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002800 (void)ObjCLifetimeConversion;
2801
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002802 // Build the candidate set directly in the initialization sequence
2803 // structure, so that it will persist if we fail.
2804 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2805 CandidateSet.clear();
2806
2807 // Determine whether we are allowed to call explicit constructors or
2808 // explicit conversion operators.
2809 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002810
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002811 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002812 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2813 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002814 // The type we're converting to is a class type. Enumerate its constructors
2815 // to see if there is a suitable conversion.
2816 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002817
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002818 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002819 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002820 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002821 NamedDecl *D = *Con;
2822 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2823
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002824 // Find the constructor (which may be a template).
2825 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002826 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002827 if (ConstructorTmpl)
2828 Constructor = cast<CXXConstructorDecl>(
2829 ConstructorTmpl->getTemplatedDecl());
2830 else
John McCalla0296f72010-03-19 07:35:19 +00002831 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002832
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002833 if (!Constructor->isInvalidDecl() &&
2834 Constructor->isConvertingConstructor(AllowExplicit)) {
2835 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002836 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002837 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002838 &Initializer, 1, CandidateSet,
2839 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002840 else
John McCalla0296f72010-03-19 07:35:19 +00002841 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002842 &Initializer, 1, CandidateSet,
2843 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002845 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002846 }
John McCall3696dcb2010-08-17 07:23:57 +00002847 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2848 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002849
Douglas Gregor496e8b342010-05-07 19:42:26 +00002850 const RecordType *T2RecordType = 0;
2851 if ((T2RecordType = T2->getAs<RecordType>()) &&
2852 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002853 // The type we're converting from is a class type, enumerate its conversion
2854 // functions.
2855 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2856
John McCallad371252010-01-20 00:46:10 +00002857 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002858 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002859 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2860 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002861 NamedDecl *D = *I;
2862 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2863 if (isa<UsingShadowDecl>(D))
2864 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002865
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002866 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2867 CXXConversionDecl *Conv;
2868 if (ConvTemplate)
2869 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2870 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002871 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002872
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002873 // If the conversion function doesn't return a reference type,
2874 // it can't be considered for this conversion unless we're allowed to
2875 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002876 // FIXME: Do we need to make sure that we only consider conversion
2877 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002878 // break recursion.
2879 if ((AllowExplicit || !Conv->isExplicit()) &&
2880 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2881 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002882 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002883 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002884 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002885 else
John McCalla0296f72010-03-19 07:35:19 +00002886 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002887 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002888 }
2889 }
2890 }
John McCall3696dcb2010-08-17 07:23:57 +00002891 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2892 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002893
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002894 SourceLocation DeclLoc = Initializer->getLocStart();
2895
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002896 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002897 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002898 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002899 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002900 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002901
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002902 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002903
Chandler Carruth30141632011-02-25 19:41:05 +00002904 // This is the overload that will actually be used for the initialization, so
2905 // mark it as used.
2906 S.MarkDeclarationReferenced(DeclLoc, Function);
2907
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002908 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002909 if (isa<CXXConversionDecl>(Function))
2910 T2 = Function->getResultType();
2911 else
2912 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002913
2914 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002915 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002916 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002917
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002919 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002920 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002921 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002922 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002923 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002924 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002925
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002926 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002927 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002928 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002929 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002931 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002932 NewDerivedToBase, NewObjCConversion,
2933 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002934 if (NewRefRelationship == Sema::Ref_Incompatible) {
2935 // If the type we've converted to is not reference-related to the
2936 // type we're looking for, then there is another conversion step
2937 // we need to perform to produce a temporary of the right type
2938 // that we'll be binding to.
2939 ImplicitConversionSequence ICS;
2940 ICS.setStandard();
2941 ICS.Standard = Best->FinalConversion;
2942 T2 = ICS.Standard.getToType(2);
2943 Sequence.AddConversionSequenceStep(ICS, T2);
2944 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002945 Sequence.AddDerivedToBaseCastStep(
2946 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002948 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002949 else if (NewObjCConversion)
2950 Sequence.AddObjCObjectConversionStep(
2951 S.Context.getQualifiedType(T1,
2952 T2.getNonReferenceType().getQualifiers()));
2953
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002954 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002955 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002957 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2958 return OR_Success;
2959}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002960
2961/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2962static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002963 const InitializedEntity &Entity,
2964 const InitializationKind &Kind,
2965 Expr *Initializer,
2966 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002967 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002968 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002969 Qualifiers T1Quals;
2970 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002971 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002972 Qualifiers T2Quals;
2973 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002974 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002975
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002976 // If the initializer is the address of an overloaded function, try
2977 // to resolve the overloaded function. If all goes well, T2 is the
2978 // type of the resulting function.
2979 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002980 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002981 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002982 T1,
2983 false,
2984 Found)) {
2985 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2986 cv2T2 = Fn->getType();
2987 T2 = cv2T2.getUnqualifiedType();
2988 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002989 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2990 return;
2991 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002992 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002993
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002994 // Compute some basic properties of the types and the initializer.
2995 bool isLValueRef = DestType->isLValueReferenceType();
2996 bool isRValueRef = !isLValueRef;
2997 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002998 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002999 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003000 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003001 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003002 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003003 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003004
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003005 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003006 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003007 // "cv2 T2" as follows:
3008 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003009 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003010 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003011 // Note the analogous bullet points for rvlaue refs to functions. Because
3012 // there are no function rvalues in C++, rvalue refs to functions are treated
3013 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003014 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003015 bool T1Function = T1->isFunctionType();
3016 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003018 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003019 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003020 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003022 // reference-compatible with "cv2 T2," or
3023 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003024 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003025 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003026 // can occur. However, we do pay attention to whether it is a bit-field
3027 // to decide whether we're actually binding to a temporary created from
3028 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003029 if (DerivedToBase)
3030 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003032 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003033 else if (ObjCConversion)
3034 Sequence.AddObjCObjectConversionStep(
3035 S.Context.getQualifiedType(T1, T2Quals));
3036
Chandler Carruth04bdce62010-01-12 20:32:25 +00003037 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003038 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003039 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003040 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003041 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003042 return;
3043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003044
3045 // - has a class type (i.e., T2 is a class type), where T1 is not
3046 // reference-related to T2, and can be implicitly converted to an
3047 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3048 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003049 // applicable conversion functions (13.3.1.6) and choosing the best
3050 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003051 // If we have an rvalue ref to function type here, the rhs must be
3052 // an rvalue.
3053 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3054 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003055 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003056 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003057 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003058 Sequence);
3059 if (ConvOvlResult == OR_Success)
3060 return;
John McCall0d1da222010-01-12 00:44:57 +00003061 if (ConvOvlResult != OR_No_Viable_Function) {
3062 Sequence.SetOverloadFailure(
3063 InitializationSequence::FK_ReferenceInitOverloadFailed,
3064 ConvOvlResult);
3065 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003066 }
3067 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003068
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003069 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003070 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003071 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003072 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003073 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3074 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3075 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003076 Sequence.SetOverloadFailure(
3077 InitializationSequence::FK_ReferenceInitOverloadFailed,
3078 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003079 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003080 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003081 ? (RefRelationship == Sema::Ref_Related
3082 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3083 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3084 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003085
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003086 return;
3087 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003088
Douglas Gregor92e460e2011-01-20 16:44:54 +00003089 // - If the initializer expression
3090 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3091 // "cv1 T1" is reference-compatible with "cv2 T2"
3092 // Note: functions are handled below.
3093 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003094 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003096 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003097 (InitCategory.isXValue() ||
3098 (InitCategory.isPRValue() && T2->isRecordType()) ||
3099 (InitCategory.isPRValue() && T2->isArrayType()))) {
3100 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3101 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003102 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3103 // compiler the freedom to perform a copy here or bind to the
3104 // object, while C++0x requires that we bind directly to the
3105 // object. Hence, we always bind to the object without making an
3106 // extra copy. However, in C++03 requires that we check for the
3107 // presence of a suitable copy constructor:
3108 //
3109 // The constructor that would be used to make the copy shall
3110 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003111 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003112 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003114
Douglas Gregor92e460e2011-01-20 16:44:54 +00003115 if (DerivedToBase)
3116 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3117 ValueKind);
3118 else if (ObjCConversion)
3119 Sequence.AddObjCObjectConversionStep(
3120 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121
Douglas Gregor92e460e2011-01-20 16:44:54 +00003122 if (T1Quals != T2Quals)
3123 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003124 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00003125 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003126 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003128
3129 // - has a class type (i.e., T2 is a class type), where T1 is not
3130 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003131 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3132 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003133 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003134 if (RefRelationship == Sema::Ref_Incompatible) {
3135 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3136 Kind, Initializer,
3137 /*AllowRValues=*/true,
3138 Sequence);
3139 if (ConvOvlResult)
3140 Sequence.SetOverloadFailure(
3141 InitializationSequence::FK_ReferenceInitOverloadFailed,
3142 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003144 return;
3145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003147 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3148 return;
3149 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003150
3151 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003152 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003154 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003155
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003156 // Determine whether we are allowed to call explicit constructors or
3157 // explicit conversion operators.
3158 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003159
3160 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3161
John McCall31168b02011-06-15 23:02:42 +00003162 ImplicitConversionSequence ICS
3163 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003164 /*SuppressUserConversions*/ false,
3165 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003166 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003167 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3168 /*AllowObjCWritebackConversion=*/false);
3169
3170 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003171 // FIXME: Use the conversion function set stored in ICS to turn
3172 // this into an overloading ambiguity diagnostic. However, we need
3173 // to keep that set as an OverloadCandidateSet rather than as some
3174 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003175 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3176 Sequence.SetOverloadFailure(
3177 InitializationSequence::FK_ReferenceInitOverloadFailed,
3178 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003179 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3180 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003181 else
3182 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003183 return;
John McCall31168b02011-06-15 23:02:42 +00003184 } else {
3185 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003186 }
3187
3188 // [...] If T1 is reference-related to T2, cv1 must be the
3189 // same cv-qualification as, or greater cv-qualification
3190 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003191 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3192 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003194 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003195 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3196 return;
3197 }
3198
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003200 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003201 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003202 InitCategory.isLValue()) {
3203 Sequence.SetFailed(
3204 InitializationSequence::FK_RValueReferenceBindingToLValue);
3205 return;
3206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003208 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3209 return;
3210}
3211
3212/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213/// (C++ [dcl.init.string], C99 6.7.8).
3214static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003215 const InitializedEntity &Entity,
3216 const InitializationKind &Kind,
3217 Expr *Initializer,
3218 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003219 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003220}
3221
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003222/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3223/// enumerates the constructors of the initialized entity and performs overload
3224/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003225static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 const InitializedEntity &Entity,
3227 const InitializationKind &Kind,
3228 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003229 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003230 InitializationSequence &Sequence) {
Richard Trieua04ad1a2011-09-01 21:44:13 +00003231 // Check constructor arguments for self reference.
3232 if (DeclaratorDecl *DD = Entity.getDecl())
3233 // Parameters arguments are occassionially constructed with itself,
3234 // for instance, in recursive functions. Skip them.
3235 if (!isa<ParmVarDecl>(DD))
3236 for (unsigned i = 0; i < NumArgs; ++i)
3237 S.CheckSelfReference(DD, Args[i]);
3238
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003239 // Build the candidate set directly in the initialization sequence
3240 // structure, so that it will persist if we fail.
3241 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3242 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003244 // Determine whether we are allowed to call explicit constructors or
3245 // explicit conversion operators.
3246 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3247 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003248 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00003249
3250 // The type we're constructing needs to be complete.
3251 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003252 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00003253 return;
3254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003255
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003256 // The type we're converting to is a class type. Enumerate its constructors
3257 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003258 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003260 CXXRecordDecl *DestRecordDecl
3261 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003263 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003264 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003265 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003266 NamedDecl *D = *Con;
3267 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00003268 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003270 // Find the constructor (which may be a template).
3271 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003272 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003273 if (ConstructorTmpl)
3274 Constructor = cast<CXXConstructorDecl>(
3275 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00003276 else {
John McCalla0296f72010-03-19 07:35:19 +00003277 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00003278
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003279 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00003280 // suppress user-defined conversions on the arguments.
3281 // FIXME: Move constructors?
3282 if (Kind.getKind() == InitializationKind::IK_Copy &&
3283 Constructor->isCopyConstructor())
3284 SuppressUserConversions = true;
3285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003287 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00003288 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003289 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003290 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003291 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00003292 Args, NumArgs, CandidateSet,
3293 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003294 else
John McCalla0296f72010-03-19 07:35:19 +00003295 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00003296 Args, NumArgs, CandidateSet,
3297 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003299 }
3300
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003301 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003302
3303 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003304 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003305 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00003306 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003307 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003309 Result);
3310 return;
3311 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003312
3313 // C++0x [dcl.init]p6:
3314 // If a program calls for the default initialization of an object
3315 // of a const-qualified type T, T shall be a class type with a
3316 // user-provided default constructor.
3317 if (Kind.getKind() == InitializationKind::IK_Default &&
3318 Entity.getType().isConstQualified() &&
3319 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3320 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3321 return;
3322 }
3323
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003324 // Add the constructor initialization step. Any cv-qualification conversion is
3325 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003326 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00003328 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00003329 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003330}
3331
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003332/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003333static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003334 const InitializedEntity &Entity,
3335 const InitializationKind &Kind,
3336 InitializationSequence &Sequence) {
3337 // C++ [dcl.init]p5:
3338 //
3339 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003340 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003342 // -- if T is an array type, then each element is value-initialized;
3343 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3344 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003346 if (const RecordType *RT = T->getAs<RecordType>()) {
3347 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3348 // -- if T is a class type (clause 9) with a user-declared
3349 // constructor (12.1), then the default constructor for T is
3350 // called (and the initialization is ill-formed if T has no
3351 // accessible default constructor);
3352 //
3353 // FIXME: we really want to refer to a single subobject of the array,
3354 // but Entity doesn't have a way to capture that (yet).
3355 if (ClassDecl->hasUserDeclaredConstructor())
3356 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003358 // -- if T is a (possibly cv-qualified) non-union class type
3359 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003360 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003361 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003362 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003363 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003364 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003366 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003367 }
3368 }
3369
Douglas Gregor1b303932009-12-22 15:35:07 +00003370 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003371}
3372
Douglas Gregor85dabae2009-12-16 01:38:02 +00003373/// \brief Attempt default initialization (C++ [dcl.init]p6).
3374static void TryDefaultInitialization(Sema &S,
3375 const InitializedEntity &Entity,
3376 const InitializationKind &Kind,
3377 InitializationSequence &Sequence) {
3378 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003379
Douglas Gregor85dabae2009-12-16 01:38:02 +00003380 // C++ [dcl.init]p6:
3381 // To default-initialize an object of type T means:
3382 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003383 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3384
Douglas Gregor85dabae2009-12-16 01:38:02 +00003385 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3386 // constructor for T is called (and the initialization is ill-formed if
3387 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003388 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003389 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3390 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003391 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
Douglas Gregor85dabae2009-12-16 01:38:02 +00003393 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394
Douglas Gregor85dabae2009-12-16 01:38:02 +00003395 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003396 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003397 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003398 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003399 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003400 return;
3401 }
3402
3403 // If the destination type has a lifetime property, zero-initialize it.
3404 if (DestType.getQualifiers().hasObjCLifetime()) {
3405 Sequence.AddZeroInitializationStep(Entity.getType());
3406 return;
3407 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003408}
3409
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003410/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3411/// which enumerates all conversion functions and performs overload resolution
3412/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003414 const InitializedEntity &Entity,
3415 const InitializationKind &Kind,
3416 Expr *Initializer,
3417 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003418 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003419 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3420 QualType SourceType = Initializer->getType();
3421 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3422 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423
Douglas Gregor540c3b02009-12-14 17:27:33 +00003424 // Build the candidate set directly in the initialization sequence
3425 // structure, so that it will persist if we fail.
3426 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3427 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428
Douglas Gregor540c3b02009-12-14 17:27:33 +00003429 // Determine whether we are allowed to call explicit constructors or
3430 // explicit conversion operators.
3431 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432
Douglas Gregor540c3b02009-12-14 17:27:33 +00003433 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3434 // The type we're converting to is a class type. Enumerate its constructors
3435 // to see if there is a suitable conversion.
3436 CXXRecordDecl *DestRecordDecl
3437 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
Douglas Gregord9848152010-04-26 14:36:57 +00003439 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003441 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003442 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003443 Con != ConEnd; ++Con) {
3444 NamedDecl *D = *Con;
3445 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446
Douglas Gregord9848152010-04-26 14:36:57 +00003447 // Find the constructor (which may be a template).
3448 CXXConstructorDecl *Constructor = 0;
3449 FunctionTemplateDecl *ConstructorTmpl
3450 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003451 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003452 Constructor = cast<CXXConstructorDecl>(
3453 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003454 else
Douglas Gregord9848152010-04-26 14:36:57 +00003455 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Douglas Gregord9848152010-04-26 14:36:57 +00003457 if (!Constructor->isInvalidDecl() &&
3458 Constructor->isConvertingConstructor(AllowExplicit)) {
3459 if (ConstructorTmpl)
3460 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3461 /*ExplicitArgs*/ 0,
3462 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003463 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003464 else
3465 S.AddOverloadCandidate(Constructor, FoundDecl,
3466 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003467 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469 }
Douglas Gregord9848152010-04-26 14:36:57 +00003470 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003471 }
Eli Friedman78275202009-12-19 08:11:05 +00003472
3473 SourceLocation DeclLoc = Initializer->getLocStart();
3474
Douglas Gregor540c3b02009-12-14 17:27:33 +00003475 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3476 // The type we're converting from is a class type, enumerate its conversion
3477 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003478
Eli Friedman4afe9a32009-12-20 22:12:03 +00003479 // We can only enumerate the conversion functions for a complete type; if
3480 // the type isn't complete, simply skip this step.
3481 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3482 CXXRecordDecl *SourceRecordDecl
3483 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484
John McCallad371252010-01-20 00:46:10 +00003485 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003486 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003487 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003489 I != E; ++I) {
3490 NamedDecl *D = *I;
3491 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3492 if (isa<UsingShadowDecl>(D))
3493 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494
Eli Friedman4afe9a32009-12-20 22:12:03 +00003495 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3496 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003497 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003498 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003499 else
John McCallda4458e2010-03-31 01:36:47 +00003500 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Eli Friedman4afe9a32009-12-20 22:12:03 +00003502 if (AllowExplicit || !Conv->isExplicit()) {
3503 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003504 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003505 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003506 CandidateSet);
3507 else
John McCalla0296f72010-03-19 07:35:19 +00003508 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003509 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003510 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003511 }
3512 }
3513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514
3515 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003516 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003517 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003518 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003519 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003521 Result);
3522 return;
3523 }
John McCall0d1da222010-01-12 00:44:57 +00003524
Douglas Gregor540c3b02009-12-14 17:27:33 +00003525 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003526 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003527
Douglas Gregor540c3b02009-12-14 17:27:33 +00003528 if (isa<CXXConstructorDecl>(Function)) {
3529 // Add the user-defined conversion step. Any cv-qualification conversion is
3530 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003531 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003532 return;
3533 }
3534
3535 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003536 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003537 if (ConvType->getAs<RecordType>()) {
3538 // If we're converting to a class type, there may be an copy if
3539 // the resulting temporary object (possible to create an object of
3540 // a base class type). That copy is not a separate conversion, so
3541 // we just make a note of the actual destination type (possibly a
3542 // base class of the type returned by the conversion function) and
3543 // let the user-defined conversion step handle the conversion.
3544 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3545 return;
3546 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003547
Douglas Gregor5ab11652010-04-17 22:01:05 +00003548 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549
Douglas Gregor5ab11652010-04-17 22:01:05 +00003550 // If the conversion following the call to the conversion function
3551 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003552 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3553 Best->FinalConversion.Third) {
3554 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003555 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003556 ICS.Standard = Best->FinalConversion;
3557 Sequence.AddConversionSequenceStep(ICS, DestType);
3558 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003559}
3560
John McCall31168b02011-06-15 23:02:42 +00003561/// The non-zero enum values here are indexes into diagnostic alternatives.
3562enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3563
3564/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003565static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3566 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003567 // Skip parens.
3568 e = e->IgnoreParens();
3569
3570 // Skip address-of nodes.
3571 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3572 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003573 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003574
3575 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003576 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3577 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003578 case CK_Dependent:
3579 case CK_BitCast:
3580 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003581 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003582 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003583
3584 case CK_ArrayToPointerDecay:
3585 return IIK_nonscalar;
3586
3587 case CK_NullToPointer:
3588 return IIK_okay;
3589
3590 default:
3591 break;
3592 }
3593
3594 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003595 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3596 if (!isAddressOf) return IIK_nonlocal;
3597
3598 VarDecl *var;
3599 if (isa<DeclRefExpr>(e)) {
3600 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3601 if (!var) return IIK_nonlocal;
3602 } else {
3603 var = cast<BlockDeclRefExpr>(e)->getDecl();
3604 }
3605
3606 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003607
3608 // If we have a conditional operator, check both sides.
3609 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003610 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003611 return iik;
3612
John McCall63f84442011-06-27 23:59:58 +00003613 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003614
3615 // These are never scalar.
3616 } else if (isa<ArraySubscriptExpr>(e)) {
3617 return IIK_nonscalar;
3618
3619 // Otherwise, it needs to be a null pointer constant.
3620 } else {
3621 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3622 ? IIK_okay : IIK_nonlocal);
3623 }
3624
3625 return IIK_nonlocal;
3626}
3627
3628/// Check whether the given expression is a valid operand for an
3629/// indirect copy/restore.
3630static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3631 assert(src->isRValue());
3632
John McCall63f84442011-06-27 23:59:58 +00003633 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003634 if (iik == IIK_okay) return;
3635
3636 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3637 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3638 << src->getSourceRange();
3639}
3640
Douglas Gregore2f943b2011-02-22 18:29:51 +00003641/// \brief Determine whether we have compatible array types for the
3642/// purposes of GNU by-copy array initialization.
3643static bool hasCompatibleArrayTypes(ASTContext &Context,
3644 const ArrayType *Dest,
3645 const ArrayType *Source) {
3646 // If the source and destination array types are equivalent, we're
3647 // done.
3648 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3649 return true;
3650
3651 // Make sure that the element types are the same.
3652 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3653 return false;
3654
3655 // The only mismatch we allow is when the destination is an
3656 // incomplete array type and the source is a constant array type.
3657 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3658}
3659
John McCall31168b02011-06-15 23:02:42 +00003660static bool tryObjCWritebackConversion(Sema &S,
3661 InitializationSequence &Sequence,
3662 const InitializedEntity &Entity,
3663 Expr *Initializer) {
3664 bool ArrayDecay = false;
3665 QualType ArgType = Initializer->getType();
3666 QualType ArgPointee;
3667 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3668 ArrayDecay = true;
3669 ArgPointee = ArgArrayType->getElementType();
3670 ArgType = S.Context.getPointerType(ArgPointee);
3671 }
3672
3673 // Handle write-back conversion.
3674 QualType ConvertedArgType;
3675 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3676 ConvertedArgType))
3677 return false;
3678
3679 // We should copy unless we're passing to an argument explicitly
3680 // marked 'out'.
3681 bool ShouldCopy = true;
3682 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3683 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3684
3685 // Do we need an lvalue conversion?
3686 if (ArrayDecay || Initializer->isGLValue()) {
3687 ImplicitConversionSequence ICS;
3688 ICS.setStandard();
3689 ICS.Standard.setAsIdentityConversion();
3690
3691 QualType ResultType;
3692 if (ArrayDecay) {
3693 ICS.Standard.First = ICK_Array_To_Pointer;
3694 ResultType = S.Context.getPointerType(ArgPointee);
3695 } else {
3696 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3697 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3698 }
3699
3700 Sequence.AddConversionSequenceStep(ICS, ResultType);
3701 }
3702
3703 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3704 return true;
3705}
3706
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003707InitializationSequence::InitializationSequence(Sema &S,
3708 const InitializedEntity &Entity,
3709 const InitializationKind &Kind,
3710 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003711 unsigned NumArgs)
3712 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003713 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003715 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716 // The semantics of initializers are as follows. The destination type is
3717 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003718 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003720 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003721 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003722
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003723 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003724 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3725 SequenceKind = DependentSequence;
3726 return;
3727 }
3728
Sebastian Redld201edf2011-06-05 13:59:11 +00003729 // Almost everything is a normal sequence.
3730 setSequenceKind(NormalSequence);
3731
John McCalled75c092010-12-07 22:54:16 +00003732 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003733 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3734 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3735 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003736 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003737 return;
3738 }
3739 Args[I] = Result.take();
3740 }
John McCalled75c092010-12-07 22:54:16 +00003741
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003742 QualType SourceType;
3743 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003744 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003745 Initializer = Args[0];
3746 if (!isa<InitListExpr>(Initializer))
3747 SourceType = Initializer->getType();
3748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
3750 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003751 // list-initialized (8.5.4).
3752 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003753 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003754 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003757 // - If the destination type is a reference type, see 8.5.3.
3758 if (DestType->isReferenceType()) {
3759 // C++0x [dcl.init.ref]p1:
3760 // A variable declared to be a T& or T&&, that is, "reference to type T"
3761 // (8.3.2), shall be initialized by an object, or function, of type T or
3762 // by an object that can be converted into a T.
3763 // (Therefore, multiple arguments are not permitted.)
3764 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003765 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003766 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003767 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003768 return;
3769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003771 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003772 if (Kind.getKind() == InitializationKind::IK_Value ||
3773 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003774 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003775 return;
3776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777
Douglas Gregor85dabae2009-12-16 01:38:02 +00003778 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003779 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003780 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003781 return;
3782 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003783
John McCall66884dd2011-02-21 07:22:22 +00003784 // - If the destination type is an array of characters, an array of
3785 // char16_t, an array of char32_t, or an array of wchar_t, and the
3786 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003788 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003789 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3790 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003791 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003792 return;
3793 }
3794
Douglas Gregore2f943b2011-02-22 18:29:51 +00003795 // Note: as an GNU C extension, we allow initialization of an
3796 // array from a compound literal that creates an array of the same
3797 // type, so long as the initializer has no side effects.
3798 if (!S.getLangOptions().CPlusPlus && Initializer &&
3799 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3800 Initializer->getType()->isArrayType()) {
3801 const ArrayType *SourceAT
3802 = Context.getAsArrayType(Initializer->getType());
3803 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003804 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003805 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003806 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003807 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003808 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003809 }
3810 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003811 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003812 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003813 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003815 return;
3816 }
Eli Friedman78275202009-12-19 08:11:05 +00003817
John McCall31168b02011-06-15 23:02:42 +00003818 // Determine whether we should consider writeback conversions for
3819 // Objective-C ARC.
3820 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3821 Entity.getKind() == InitializedEntity::EK_Parameter;
3822
3823 // We're at the end of the line for C: it's either a write-back conversion
3824 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003825 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003826 // If allowed, check whether this is an Objective-C writeback conversion.
3827 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003828 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003829 return;
3830 }
3831
3832 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003833 AddCAssignmentStep(DestType);
3834 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003835 return;
3836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837
John McCall31168b02011-06-15 23:02:42 +00003838 assert(S.getLangOptions().CPlusPlus);
3839
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003840 // - If the destination type is a (possibly cv-qualified) class type:
3841 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842 // - If the initialization is direct-initialization, or if it is
3843 // copy-initialization where the cv-unqualified version of the
3844 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003845 // class of the destination, constructors are considered. [...]
3846 if (Kind.getKind() == InitializationKind::IK_Direct ||
3847 (Kind.getKind() == InitializationKind::IK_Copy &&
3848 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3849 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003851 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003852 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003853 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003855 // used) to a derived class thereof are enumerated as described in
3856 // 13.3.1.4, and the best one is chosen through overload resolution
3857 // (13.3).
3858 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003859 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003860 return;
3861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003862
Douglas Gregor85dabae2009-12-16 01:38:02 +00003863 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003864 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003865 return;
3866 }
3867 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003868
3869 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003870 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003871 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003872 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3873 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003874 return;
3875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003877 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003878 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003879 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003881 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003882
3883 ImplicitConversionSequence ICS
3884 = S.TryImplicitConversion(Initializer, Entity.getType(),
3885 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003886 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003887 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003888 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3889 allowObjCWritebackConversion);
3890
3891 if (ICS.isStandard() &&
3892 ICS.Standard.Second == ICK_Writeback_Conversion) {
3893 // Objective-C ARC writeback conversion.
3894
3895 // We should copy unless we're passing to an argument explicitly
3896 // marked 'out'.
3897 bool ShouldCopy = true;
3898 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3899 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3900
3901 // If there was an lvalue adjustment, add it as a separate conversion.
3902 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3903 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3904 ImplicitConversionSequence LvalueICS;
3905 LvalueICS.setStandard();
3906 LvalueICS.Standard.setAsIdentityConversion();
3907 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3908 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003909 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003910 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003911
3912 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003913 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003914 DeclAccessPair dap;
3915 if (Initializer->getType() == Context.OverloadTy &&
3916 !S.ResolveAddressOfOverloadedFunction(Initializer
3917 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003918 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003919 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003920 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003921 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003922 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003923
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003924 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003925 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003926}
3927
3928InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003929 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003930 StepEnd = Steps.end();
3931 Step != StepEnd; ++Step)
3932 Step->Destroy();
3933}
3934
3935//===----------------------------------------------------------------------===//
3936// Perform initialization
3937//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003938static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003939getAssignmentAction(const InitializedEntity &Entity) {
3940 switch(Entity.getKind()) {
3941 case InitializedEntity::EK_Variable:
3942 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003943 case InitializedEntity::EK_Exception:
3944 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003945 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003946 return Sema::AA_Initializing;
3947
3948 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003949 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003950 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3951 return Sema::AA_Sending;
3952
Douglas Gregore1314a62009-12-18 05:02:21 +00003953 return Sema::AA_Passing;
3954
3955 case InitializedEntity::EK_Result:
3956 return Sema::AA_Returning;
3957
Douglas Gregore1314a62009-12-18 05:02:21 +00003958 case InitializedEntity::EK_Temporary:
3959 // FIXME: Can we tell apart casting vs. converting?
3960 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003961
Douglas Gregore1314a62009-12-18 05:02:21 +00003962 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003963 case InitializedEntity::EK_ArrayElement:
3964 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003965 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003966 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003967 return Sema::AA_Initializing;
3968 }
3969
3970 return Sema::AA_Converting;
3971}
3972
Douglas Gregor95562572010-04-24 23:45:46 +00003973/// \brief Whether we should binding a created object as a temporary when
3974/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003975static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003976 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003977 case InitializedEntity::EK_ArrayElement:
3978 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003979 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003980 case InitializedEntity::EK_New:
3981 case InitializedEntity::EK_Variable:
3982 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003983 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003984 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003985 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003986 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003987 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003988 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989
Douglas Gregore1314a62009-12-18 05:02:21 +00003990 case InitializedEntity::EK_Parameter:
3991 case InitializedEntity::EK_Temporary:
3992 return true;
3993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003994
Douglas Gregore1314a62009-12-18 05:02:21 +00003995 llvm_unreachable("missed an InitializedEntity kind?");
3996}
3997
Douglas Gregor95562572010-04-24 23:45:46 +00003998/// \brief Whether the given entity, when initialized with an object
3999/// created for that initialization, requires destruction.
4000static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4001 switch (Entity.getKind()) {
4002 case InitializedEntity::EK_Member:
4003 case InitializedEntity::EK_Result:
4004 case InitializedEntity::EK_New:
4005 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004006 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004007 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004008 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004009 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004010 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004011
Douglas Gregor95562572010-04-24 23:45:46 +00004012 case InitializedEntity::EK_Variable:
4013 case InitializedEntity::EK_Parameter:
4014 case InitializedEntity::EK_Temporary:
4015 case InitializedEntity::EK_ArrayElement:
4016 case InitializedEntity::EK_Exception:
4017 return true;
4018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019
4020 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004021}
4022
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004023/// \brief Make a (potentially elidable) temporary copy of the object
4024/// provided by the given initializer by calling the appropriate copy
4025/// constructor.
4026///
4027/// \param S The Sema object used for type-checking.
4028///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004029/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004030/// the type of the initializer expression or a superclass thereof.
4031///
4032/// \param Enter The entity being initialized.
4033///
4034/// \param CurInit The initializer expression.
4035///
4036/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4037/// is permitted in C++03 (but not C++0x) when binding a reference to
4038/// an rvalue.
4039///
4040/// \returns An expression that copies the initializer expression into
4041/// a temporary object, or an error expression if a copy could not be
4042/// created.
John McCalldadc5752010-08-24 06:29:42 +00004043static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004044 QualType T,
4045 const InitializedEntity &Entity,
4046 ExprResult CurInit,
4047 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004048 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004049 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004051 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004052 Class = cast<CXXRecordDecl>(Record->getDecl());
4053 if (!Class)
4054 return move(CurInit);
4055
Douglas Gregor5d369002011-01-21 18:05:27 +00004056 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004057 // When certain criteria are met, an implementation is allowed to
4058 // omit the copy/move construction of a class object, even if the
4059 // copy/move constructor and/or destructor for the object have
4060 // side effects. [...]
4061 // - when a temporary class object that has not been bound to a
4062 // reference (12.2) would be copied/moved to a class object
4063 // with the same cv-unqualified type, the copy/move operation
4064 // can be omitted by constructing the temporary object
4065 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004067 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004068 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004070 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004071 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004072 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00004073 switch (Entity.getKind()) {
4074 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004075 Loc = Entity.getReturnLoc();
4076 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077
Douglas Gregore1314a62009-12-18 05:02:21 +00004078 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00004079 Loc = Entity.getThrowLoc();
4080 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081
Douglas Gregore1314a62009-12-18 05:02:21 +00004082 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00004083 Loc = Entity.getDecl()->getLocation();
4084 break;
4085
Anders Carlsson0bd52402010-01-24 00:19:41 +00004086 case InitializedEntity::EK_ArrayElement:
4087 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00004088 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00004089 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004090 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00004091 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004092 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004093 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004094 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004095 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004096 Loc = CurInitExpr->getLocStart();
4097 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00004098 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00004099
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004101 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4102 return move(CurInit);
4103
Douglas Gregorf282a762011-01-21 19:38:21 +00004104 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00004105 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00004106 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00004107 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004108 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004109 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00004110 // C++0x [dcl.init]p16, second bullet to class types, this
4111 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004112 CXXConstructorDecl *Constructor = 0;
4113
4114 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004115 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004116 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00004117 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00004118 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004119 continue;
4120
4121 DeclAccessPair FoundDecl
4122 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4123 S.AddOverloadCandidate(Constructor, FoundDecl,
4124 &CurInitExpr, 1, CandidateSet);
4125 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004127
4128 // Handle constructor templates.
4129 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4130 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00004131 continue;
John McCalla0296f72010-03-19 07:35:19 +00004132
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004133 Constructor = cast<CXXConstructorDecl>(
4134 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00004135 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004136 continue;
4137
4138 // FIXME: Do we need to limit this to copy-constructor-like
4139 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00004140 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004141 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4142 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4143 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145
Douglas Gregore1314a62009-12-18 05:02:21 +00004146 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004147 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004148 case OR_Success:
4149 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150
Douglas Gregore1314a62009-12-18 05:02:21 +00004151 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004152 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4153 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4154 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004155 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004156 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004157 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004158 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004159 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004160 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161
Douglas Gregore1314a62009-12-18 05:02:21 +00004162 case OR_Ambiguous:
4163 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004164 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004165 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004166 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004167 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168
Douglas Gregore1314a62009-12-18 05:02:21 +00004169 case OR_Deleted:
4170 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004171 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004172 << CurInitExpr->getSourceRange();
4173 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004174 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004175 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004176 }
4177
Douglas Gregor5ab11652010-04-17 22:01:05 +00004178 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004179 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004180 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004181
Anders Carlssona01874b2010-04-21 18:47:17 +00004182 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004183 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004184
4185 if (IsExtraneousCopy) {
4186 // If this is a totally extraneous copy for C++03 reference
4187 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004188 // expression. We don't generate an (elided) copy operation here
4189 // because doing so would require us to pass down a flag to avoid
4190 // infinite recursion, where each step adds another extraneous,
4191 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004192
Douglas Gregor30b52772010-04-18 07:57:34 +00004193 // Instantiate the default arguments of any extra parameters in
4194 // the selected copy constructor, as if we were going to create a
4195 // proper call to the copy constructor.
4196 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4197 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4198 if (S.RequireCompleteType(Loc, Parm->getType(),
4199 S.PDiag(diag::err_call_incomplete_argument)))
4200 break;
4201
4202 // Build the default argument expression; we don't actually care
4203 // if this succeeds or not, because this routine will complain
4204 // if there was a problem.
4205 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4206 }
4207
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004208 return S.Owned(CurInitExpr);
4209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
Chandler Carruth30141632011-02-25 19:41:05 +00004211 S.MarkDeclarationReferenced(Loc, Constructor);
4212
Douglas Gregor5ab11652010-04-17 22:01:05 +00004213 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004214 // constructor call (we might have derived-to-base conversions, or
4215 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004216 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004217 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004218 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004219
Douglas Gregord0ace022010-04-25 00:55:24 +00004220 // Actually perform the constructor call.
4221 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004222 move_arg(ConstructorArgs),
4223 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004224 CXXConstructExpr::CK_Complete,
4225 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
Douglas Gregord0ace022010-04-25 00:55:24 +00004227 // If we're supposed to bind temporaries, do so.
4228 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4229 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4230 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004231}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004232
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004233void InitializationSequence::PrintInitLocationNote(Sema &S,
4234 const InitializedEntity &Entity) {
4235 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4236 if (Entity.getDecl()->getLocation().isInvalid())
4237 return;
4238
4239 if (Entity.getDecl()->getDeclName())
4240 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4241 << Entity.getDecl()->getDeclName();
4242 else
4243 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4244 }
4245}
4246
Sebastian Redl112aa822011-07-14 19:07:55 +00004247static bool isReferenceBinding(const InitializationSequence::Step &s) {
4248 return s.Kind == InitializationSequence::SK_BindReference ||
4249 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4250}
4251
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004253InitializationSequence::Perform(Sema &S,
4254 const InitializedEntity &Entity,
4255 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004256 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004257 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004258 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004259 unsigned NumArgs = Args.size();
4260 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004261 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
Sebastian Redld201edf2011-06-05 13:59:11 +00004264 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004265 // If the declaration is a non-dependent, incomplete array type
4266 // that has an initializer, then its type will be completed once
4267 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004268 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004269 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004270 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004271 if (const IncompleteArrayType *ArrayT
4272 = S.Context.getAsIncompleteArrayType(DeclType)) {
4273 // FIXME: We don't currently have the ability to accurately
4274 // compute the length of an initializer list without
4275 // performing full type-checking of the initializer list
4276 // (since we have to determine where braces are implicitly
4277 // introduced and such). So, we fall back to making the array
4278 // type a dependently-sized array type with no specified
4279 // bound.
4280 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4281 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004282
Douglas Gregor51e77d52009-12-10 17:56:55 +00004283 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004284 if (DeclaratorDecl *DD = Entity.getDecl()) {
4285 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4286 TypeLoc TL = TInfo->getTypeLoc();
4287 if (IncompleteArrayTypeLoc *ArrayLoc
4288 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4289 Brackets = ArrayLoc->getBracketsRange();
4290 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004291 }
4292
4293 *ResultType
4294 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4295 /*NumElts=*/0,
4296 ArrayT->getSizeModifier(),
4297 ArrayT->getIndexTypeCVRQualifiers(),
4298 Brackets);
4299 }
4300
4301 }
4302 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004303 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4304 Kind.isExplicitCast());
4305 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004306 }
4307
Sebastian Redld201edf2011-06-05 13:59:11 +00004308 // No steps means no initialization.
4309 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004310 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311
Douglas Gregor1b303932009-12-22 15:35:07 +00004312 QualType DestType = Entity.getType().getNonReferenceType();
4313 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004314 // the same as Entity.getDecl()->getType() in cases involving type merging,
4315 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004316 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004317 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004318 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004319
John McCalldadc5752010-08-24 06:29:42 +00004320 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004323 // grab the only argument out the Args and place it into the "current"
4324 // initializer.
4325 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004326 case SK_ResolveAddressOfOverloadedFunction:
4327 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004328 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004329 case SK_CastDerivedToBaseLValue:
4330 case SK_BindReference:
4331 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004332 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004333 case SK_UserConversion:
4334 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004335 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004336 case SK_QualificationConversionRValue:
4337 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004338 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004339 case SK_ListInitialization:
4340 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004341 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004342 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004343 case SK_ArrayInit:
4344 case SK_PassByIndirectCopyRestore:
4345 case SK_PassByIndirectRestore:
4346 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004347 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004348 CurInit = Args.get()[0];
4349 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004350
4351 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004352 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4353 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4354 if (CurInit.isInvalid())
4355 return ExprError();
4356 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004357 break;
John McCall34376a62010-12-04 03:47:34 +00004358 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359
Douglas Gregore1314a62009-12-18 05:02:21 +00004360 case SK_ConstructorInitialization:
4361 case SK_ZeroInitialization:
4362 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364
4365 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004366 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004367 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004368 for (step_iterator Step = step_begin(), StepEnd = step_end();
4369 Step != StepEnd; ++Step) {
4370 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004371 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372
John Wiegley01296292011-04-08 18:41:53 +00004373 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004375 switch (Step->Kind) {
4376 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004377 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004378 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004379 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004380 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004381 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004382 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004383 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004384 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004385
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004386 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004387 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004388 case SK_CastDerivedToBaseLValue: {
4389 // We have a derived-to-base cast that produces either an rvalue or an
4390 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391
John McCallcf142162010-08-07 06:22:56 +00004392 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004393
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004394 // Casts to inaccessible base classes are allowed with C-style casts.
4395 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4396 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004397 CurInit.get()->getLocStart(),
4398 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004399 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004400 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregor88d292c2010-05-13 16:44:06 +00004402 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4403 QualType T = SourceType;
4404 if (const PointerType *Pointer = T->getAs<PointerType>())
4405 T = Pointer->getPointeeType();
4406 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004407 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004408 cast<CXXRecordDecl>(RecordTy->getDecl()));
4409 }
4410
John McCall2536c6d2010-08-25 10:28:54 +00004411 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004412 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004413 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004414 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004415 VK_XValue :
4416 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004417 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4418 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004419 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004420 CurInit.get(),
4421 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004422 break;
4423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004425 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004426 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004427 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4428 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004429 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004430 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004431 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004432 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004433 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004434 }
Anders Carlssona91be642010-01-29 02:47:33 +00004435
John Wiegley01296292011-04-08 18:41:53 +00004436 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004437 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004438 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4439 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004440 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004441 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004442 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004443 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004445 // Reference binding does not have any corresponding ASTs.
4446
4447 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004448 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004449 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004450
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004451 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004452
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004453 case SK_BindReferenceToTemporary:
4454 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004455 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004456 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004457
Douglas Gregorfe314812011-06-21 17:03:29 +00004458 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004459 CurInit = new (S.Context) MaterializeTemporaryExpr(
4460 Entity.getType().getNonReferenceType(),
4461 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004462 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004463
4464 // If we're binding to an Objective-C object that has lifetime, we
4465 // need cleanups.
4466 if (S.getLangOptions().ObjCAutoRefCount &&
4467 CurInit.get()->getType()->isObjCLifetimeType())
4468 S.ExprNeedsCleanups = true;
4469
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004470 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004472 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004474 /*IsExtraneousCopy=*/true);
4475 break;
4476
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004477 case SK_UserConversion: {
4478 // We have a user-defined conversion that invokes either a constructor
4479 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004480 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004481 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004482 FunctionDecl *Fn = Step->Function.Function;
4483 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004484 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004485 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004486 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004487 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004488 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004489 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004490
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004491 // Determine the arguments required to actually perform the constructor
4492 // call.
John Wiegley01296292011-04-08 18:41:53 +00004493 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004494 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004495 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004496 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004497 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004499 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004500 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004501 move_arg(ConstructorArgs),
4502 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004503 CXXConstructExpr::CK_Complete,
4504 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004505 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004506 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004507
Anders Carlssona01874b2010-04-21 18:47:17 +00004508 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004509 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004510 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
John McCalle3027922010-08-25 11:45:40 +00004512 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004513 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4514 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4515 S.IsDerivedFrom(SourceType, Class))
4516 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Douglas Gregor95562572010-04-24 23:45:46 +00004518 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004519 } else {
4520 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004521 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004522 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004523 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004524 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
4526 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004527 // derived-to-base conversion? I believe the answer is "no", because
4528 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004529 ExprResult CurInitExprRes =
4530 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4531 FoundFn, Conversion);
4532 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004533 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004534 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004536 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004537 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004538 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004539 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540
John McCalle3027922010-08-25 11:45:40 +00004541 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542
Douglas Gregor95562572010-04-24 23:45:46 +00004543 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545
Sebastian Redl112aa822011-07-14 19:07:55 +00004546 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004547 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004548 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004549 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004550 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004551 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004553 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004554 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004555 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004556 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4557 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004558 }
4559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004560
John McCallcf142162010-08-07 06:22:56 +00004561 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004562 CurInit.get()->getType(),
4563 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00004564 CurInit.get()->getValueKind()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004566 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004567 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4568 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004569
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004570 break;
4571 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004572
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004573 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004574 case SK_QualificationConversionXValue:
4575 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004576 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004577 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004578 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004579 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004580 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004581 VK_XValue :
4582 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004583 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004584 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004585 }
4586
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004587 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004588 Sema::CheckedConversionKind CCK
4589 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4590 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4591 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4592 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004593 ExprResult CurInitExprRes =
4594 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004595 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004596 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004597 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004598 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004599 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601
Douglas Gregor51e77d52009-12-10 17:56:55 +00004602 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004603 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004604 QualType Ty = Step->Type;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004605 InitListChecker PerformInitList(S, Entity, InitList,
4606 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false);
4607 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004608 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004609
4610 CurInit.release();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004611 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004612 break;
4613 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004614
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004615 case SK_ListConstructorCall:
4616 assert(false && "List constructor calls not yet supported.");
4617
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004618 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004619 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004620 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004621 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004623 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004624 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004625 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4626 ? Kind.getEqualLoc()
4627 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004628
4629 if (Kind.getKind() == InitializationKind::IK_Default) {
4630 // Force even a trivial, implicit default constructor to be
4631 // semantically checked. We do this explicitly because we don't build
4632 // the definition for completely trivial constructors.
4633 CXXRecordDecl *ClassDecl = Constructor->getParent();
4634 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004635 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004636 ClassDecl->hasTrivialDefaultConstructor() &&
4637 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004638 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4639 }
4640
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004641 // Determine the arguments required to actually perform the constructor
4642 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004643 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004644 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004645 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004646
4647
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004648 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004649 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004650 (Kind.getKind() == InitializationKind::IK_Direct ||
4651 Kind.getKind() == InitializationKind::IK_Value)) {
4652 // An explicitly-constructed temporary, e.g., X(1, 2).
4653 unsigned NumExprs = ConstructorArgs.size();
4654 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004655 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004656 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657
Douglas Gregor2b88c112010-09-08 00:15:04 +00004658 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4659 if (!TSInfo)
4660 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004662 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4663 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004664 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004665 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004666 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004667 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004668 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004669 } else {
4670 CXXConstructExpr::ConstructionKind ConstructKind =
4671 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004672
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004673 if (Entity.getKind() == InitializedEntity::EK_Base) {
4674 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004675 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004676 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004677 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004678 ConstructKind = CXXConstructExpr::CK_Delegating;
4679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680
Chandler Carruth01718152010-10-25 08:47:36 +00004681 // Only get the parenthesis range if it is a direct construction.
4682 SourceRange parenRange =
4683 Kind.getKind() == InitializationKind::IK_Direct ?
4684 Kind.getParenRange() : SourceRange();
4685
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004686 // If the entity allows NRVO, mark the construction as elidable
4687 // unconditionally.
4688 if (Entity.allowsNRVO())
4689 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4690 Constructor, /*Elidable=*/true,
4691 move_arg(ConstructorArgs),
4692 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004693 ConstructKind,
4694 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004695 else
4696 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004697 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004698 move_arg(ConstructorArgs),
4699 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004700 ConstructKind,
4701 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004702 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004703 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004704 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004705
4706 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004707 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004708 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004709 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004711 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004712 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004714 break;
4715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004717 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004718 step_iterator NextStep = Step;
4719 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004721 NextStep->Kind == SK_ConstructorInitialization) {
4722 // The need for zero-initialization is recorded directly into
4723 // the call to the object's constructor within the next step.
4724 ConstructorInitRequiresZeroInit = true;
4725 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4726 S.getLangOptions().CPlusPlus &&
4727 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004728 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4729 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004730 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004731 Kind.getRange().getBegin());
4732
4733 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4734 TSInfo->getType().getNonLValueExprType(S.Context),
4735 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004736 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004737 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004738 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004739 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004740 break;
4741 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004742
4743 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004744 QualType SourceType = CurInit.get()->getType();
4745 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004746 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004747 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4748 if (Result.isInvalid())
4749 return ExprError();
4750 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004751
4752 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004753 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004754 if (ConvTy != Sema::Compatible &&
4755 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004756 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004757 == Sema::Compatible)
4758 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004759 if (CurInitExprRes.isInvalid())
4760 return ExprError();
4761 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004762
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004763 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004764 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4765 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004766 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004767 getAssignmentAction(Entity),
4768 &Complained)) {
4769 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004770 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004771 } else if (Complained)
4772 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004773 break;
4774 }
Eli Friedman78275202009-12-19 08:11:05 +00004775
4776 case SK_StringInit: {
4777 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004778 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004779 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004780 break;
4781 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004782
4783 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004784 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004785 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004786 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004787 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004788
4789 case SK_ArrayInit:
4790 // Okay: we checked everything before creating this step. Note that
4791 // this is a GNU extension.
4792 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004793 << Step->Type << CurInit.get()->getType()
4794 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004795
4796 // If the destination type is an incomplete array type, update the
4797 // type accordingly.
4798 if (ResultType) {
4799 if (const IncompleteArrayType *IncompleteDest
4800 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4801 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004802 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004803 *ResultType = S.Context.getConstantArrayType(
4804 IncompleteDest->getElementType(),
4805 ConstantSource->getSize(),
4806 ArrayType::Normal, 0);
4807 }
4808 }
4809 }
John McCall31168b02011-06-15 23:02:42 +00004810 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004811
John McCall31168b02011-06-15 23:02:42 +00004812 case SK_PassByIndirectCopyRestore:
4813 case SK_PassByIndirectRestore:
4814 checkIndirectCopyRestoreSource(S, CurInit.get());
4815 CurInit = S.Owned(new (S.Context)
4816 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4817 Step->Kind == SK_PassByIndirectCopyRestore));
4818 break;
4819
4820 case SK_ProduceObjCObject:
4821 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00004822 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00004823 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004824 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004825 }
4826 }
John McCall1f425642010-11-11 03:21:53 +00004827
4828 // Diagnose non-fatal problems with the completed initialization.
4829 if (Entity.getKind() == InitializedEntity::EK_Member &&
4830 cast<FieldDecl>(Entity.getDecl())->isBitField())
4831 S.CheckBitFieldInitialization(Kind.getLocation(),
4832 cast<FieldDecl>(Entity.getDecl()),
4833 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004835 return move(CurInit);
4836}
4837
4838//===----------------------------------------------------------------------===//
4839// Diagnose initialization failures
4840//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004842 const InitializedEntity &Entity,
4843 const InitializationKind &Kind,
4844 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004845 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004847
Douglas Gregor1b303932009-12-22 15:35:07 +00004848 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004849 switch (Failure) {
4850 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004851 // FIXME: Customize for the initialized entity?
4852 if (NumArgs == 0)
4853 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4854 << DestType.getNonReferenceType();
4855 else // FIXME: diagnostic below could be better!
4856 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4857 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004858 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004860 case FK_ArrayNeedsInitList:
4861 case FK_ArrayNeedsInitListOrStringLiteral:
4862 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4863 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4864 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865
Douglas Gregore2f943b2011-02-22 18:29:51 +00004866 case FK_ArrayTypeMismatch:
4867 case FK_NonConstantArrayInit:
4868 S.Diag(Kind.getLocation(),
4869 (Failure == FK_ArrayTypeMismatch
4870 ? diag::err_array_init_different_type
4871 : diag::err_array_init_non_constant_array))
4872 << DestType.getNonReferenceType()
4873 << Args[0]->getType()
4874 << Args[0]->getSourceRange();
4875 break;
4876
John McCall16df1e52010-03-30 21:47:33 +00004877 case FK_AddressOfOverloadFailed: {
4878 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004880 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004881 true,
4882 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004883 break;
John McCall16df1e52010-03-30 21:47:33 +00004884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004886 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004887 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004888 switch (FailedOverloadResult) {
4889 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004890 if (Failure == FK_UserConversionOverloadFailed)
4891 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4892 << Args[0]->getType() << DestType
4893 << Args[0]->getSourceRange();
4894 else
4895 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4896 << DestType << Args[0]->getType()
4897 << Args[0]->getSourceRange();
4898
John McCall5c32be02010-08-24 20:38:10 +00004899 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004900 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004902 case OR_No_Viable_Function:
4903 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4904 << Args[0]->getType() << DestType.getNonReferenceType()
4905 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004906 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004907 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004909 case OR_Deleted: {
4910 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4911 << Args[0]->getType() << DestType.getNonReferenceType()
4912 << Args[0]->getSourceRange();
4913 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004914 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004915 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4916 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004917 if (Ovl == OR_Deleted) {
4918 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004919 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004920 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004921 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004922 }
4923 break;
4924 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004926 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004927 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004928 break;
4929 }
4930 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004932 case FK_NonConstLValueReferenceBindingToTemporary:
4933 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004934 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004935 Failure == FK_NonConstLValueReferenceBindingToTemporary
4936 ? diag::err_lvalue_reference_bind_to_temporary
4937 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004938 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004939 << DestType.getNonReferenceType()
4940 << Args[0]->getType()
4941 << Args[0]->getSourceRange();
4942 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004943
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004944 case FK_RValueReferenceBindingToLValue:
4945 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004946 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004947 << Args[0]->getSourceRange();
4948 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004949
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004950 case FK_ReferenceInitDropsQualifiers:
4951 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4952 << DestType.getNonReferenceType()
4953 << Args[0]->getType()
4954 << Args[0]->getSourceRange();
4955 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004957 case FK_ReferenceInitFailed:
4958 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4959 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004960 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004961 << Args[0]->getType()
4962 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004963 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4964 Args[0]->getType()->isObjCObjectPointerType())
4965 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004966 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004967
Douglas Gregorb491ed32011-02-19 21:32:49 +00004968 case FK_ConversionFailed: {
4969 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004970 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4971 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004972 << DestType
John McCall086a4642010-11-24 05:12:34 +00004973 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004974 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004975 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004976 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4977 Args[0]->getType()->isObjCObjectPointerType())
4978 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004979 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004980 }
John Wiegley01296292011-04-08 18:41:53 +00004981
4982 case FK_ConversionFromPropertyFailed:
4983 // No-op. This error has already been reported.
4984 break;
4985
Douglas Gregor51e77d52009-12-10 17:56:55 +00004986 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004987 SourceRange R;
4988
4989 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004990 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004991 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004992 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004993 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004994
Douglas Gregor8ec51732010-09-08 21:40:08 +00004995 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4996 if (Kind.isCStyleOrFunctionalCast())
4997 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4998 << R;
4999 else
5000 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5001 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005002 break;
5003 }
5004
5005 case FK_ReferenceBindingToInitList:
5006 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5007 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5008 break;
5009
5010 case FK_InitListBadDestinationType:
5011 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5012 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5013 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005015 case FK_ConstructorOverloadFailed: {
5016 SourceRange ArgsRange;
5017 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005018 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005019 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005020
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005021 // FIXME: Using "DestType" for the entity we're printing is probably
5022 // bad.
5023 switch (FailedOverloadResult) {
5024 case OR_Ambiguous:
5025 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5026 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005027 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5028 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005029 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005031 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005032 if (Kind.getKind() == InitializationKind::IK_Default &&
5033 (Entity.getKind() == InitializedEntity::EK_Base ||
5034 Entity.getKind() == InitializedEntity::EK_Member) &&
5035 isa<CXXConstructorDecl>(S.CurContext)) {
5036 // This is implicit default initialization of a member or
5037 // base within a constructor. If no viable function was
5038 // found, notify the user that she needs to explicitly
5039 // initialize this base/member.
5040 CXXConstructorDecl *Constructor
5041 = cast<CXXConstructorDecl>(S.CurContext);
5042 if (Entity.getKind() == InitializedEntity::EK_Base) {
5043 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5044 << Constructor->isImplicit()
5045 << S.Context.getTypeDeclType(Constructor->getParent())
5046 << /*base=*/0
5047 << Entity.getType();
5048
5049 RecordDecl *BaseDecl
5050 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5051 ->getDecl();
5052 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5053 << S.Context.getTagDeclType(BaseDecl);
5054 } else {
5055 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5056 << Constructor->isImplicit()
5057 << S.Context.getTypeDeclType(Constructor->getParent())
5058 << /*member=*/1
5059 << Entity.getName();
5060 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5061
5062 if (const RecordType *Record
5063 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005065 diag::note_previous_decl)
5066 << S.Context.getTagDeclType(Record->getDecl());
5067 }
5068 break;
5069 }
5070
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005071 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5072 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005073 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005074 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005075
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005076 case OR_Deleted: {
5077 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5078 << true << DestType << ArgsRange;
5079 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005080 OverloadingResult Ovl
5081 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005082 if (Ovl == OR_Deleted) {
5083 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005084 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005085 } else {
5086 llvm_unreachable("Inconsistent overload resolution?");
5087 }
5088 break;
5089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005090
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005091 case OR_Success:
5092 llvm_unreachable("Conversion did not fail!");
5093 break;
5094 }
5095 break;
5096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
Douglas Gregor85dabae2009-12-16 01:38:02 +00005098 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005099 if (Entity.getKind() == InitializedEntity::EK_Member &&
5100 isa<CXXConstructorDecl>(S.CurContext)) {
5101 // This is implicit default-initialization of a const member in
5102 // a constructor. Complain that it needs to be explicitly
5103 // initialized.
5104 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5105 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5106 << Constructor->isImplicit()
5107 << S.Context.getTypeDeclType(Constructor->getParent())
5108 << /*const=*/1
5109 << Entity.getName();
5110 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5111 << Entity.getName();
5112 } else {
5113 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5114 << DestType << (bool)DestType->getAs<RecordType>();
5115 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005116 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005118 case FK_Incomplete:
5119 S.RequireCompleteType(Kind.getLocation(), DestType,
5120 diag::err_init_incomplete_type);
5121 break;
5122
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005123 case FK_ListInitializationFailed: {
5124 // Run the init list checker again to emit diagnostics.
5125 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5126 QualType DestType = Entity.getType();
5127 InitListChecker DiagnoseInitList(S, Entity, InitList,
5128 DestType, /*VerifyOnly=*/false);
5129 assert(DiagnoseInitList.HadError() &&
5130 "Inconsistent init list check result.");
5131 break;
5132 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005134
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005135 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005136 return true;
5137}
Douglas Gregore1314a62009-12-18 05:02:21 +00005138
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005139void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005140 switch (SequenceKind) {
5141 case FailedSequence: {
5142 OS << "Failed sequence: ";
5143 switch (Failure) {
5144 case FK_TooManyInitsForReference:
5145 OS << "too many initializers for reference";
5146 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005148 case FK_ArrayNeedsInitList:
5149 OS << "array requires initializer list";
5150 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005152 case FK_ArrayNeedsInitListOrStringLiteral:
5153 OS << "array requires initializer list or string literal";
5154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155
Douglas Gregore2f943b2011-02-22 18:29:51 +00005156 case FK_ArrayTypeMismatch:
5157 OS << "array type mismatch";
5158 break;
5159
5160 case FK_NonConstantArrayInit:
5161 OS << "non-constant array initializer";
5162 break;
5163
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005164 case FK_AddressOfOverloadFailed:
5165 OS << "address of overloaded function failed";
5166 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005168 case FK_ReferenceInitOverloadFailed:
5169 OS << "overload resolution for reference initialization failed";
5170 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005172 case FK_NonConstLValueReferenceBindingToTemporary:
5173 OS << "non-const lvalue reference bound to temporary";
5174 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005175
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005176 case FK_NonConstLValueReferenceBindingToUnrelated:
5177 OS << "non-const lvalue reference bound to unrelated type";
5178 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005179
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005180 case FK_RValueReferenceBindingToLValue:
5181 OS << "rvalue reference bound to an lvalue";
5182 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005183
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005184 case FK_ReferenceInitDropsQualifiers:
5185 OS << "reference initialization drops qualifiers";
5186 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005187
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005188 case FK_ReferenceInitFailed:
5189 OS << "reference initialization failed";
5190 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005191
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005192 case FK_ConversionFailed:
5193 OS << "conversion failed";
5194 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195
John Wiegley01296292011-04-08 18:41:53 +00005196 case FK_ConversionFromPropertyFailed:
5197 OS << "conversion from property failed";
5198 break;
5199
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005200 case FK_TooManyInitsForScalar:
5201 OS << "too many initializers for scalar";
5202 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005204 case FK_ReferenceBindingToInitList:
5205 OS << "referencing binding to initializer list";
5206 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005208 case FK_InitListBadDestinationType:
5209 OS << "initializer list for non-aggregate, non-scalar type";
5210 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005211
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005212 case FK_UserConversionOverloadFailed:
5213 OS << "overloading failed for user-defined conversion";
5214 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005215
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005216 case FK_ConstructorOverloadFailed:
5217 OS << "constructor overloading failed";
5218 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005219
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005220 case FK_DefaultInitOfConst:
5221 OS << "default initialization of a const variable";
5222 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005223
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005224 case FK_Incomplete:
5225 OS << "initialization of incomplete type";
5226 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005227
5228 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005229 OS << "list initialization checker failure";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005231 OS << '\n';
5232 return;
5233 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005234
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005235 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005236 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005237 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005238
Sebastian Redld201edf2011-06-05 13:59:11 +00005239 case NormalSequence:
5240 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005241 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005242 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005243
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005244 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5245 if (S != step_begin()) {
5246 OS << " -> ";
5247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005248
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005249 switch (S->Kind) {
5250 case SK_ResolveAddressOfOverloadedFunction:
5251 OS << "resolve address of overloaded function";
5252 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005253
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005254 case SK_CastDerivedToBaseRValue:
5255 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5256 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005257
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005258 case SK_CastDerivedToBaseXValue:
5259 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5260 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005261
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005262 case SK_CastDerivedToBaseLValue:
5263 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5264 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005265
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005266 case SK_BindReference:
5267 OS << "bind reference to lvalue";
5268 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005269
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005270 case SK_BindReferenceToTemporary:
5271 OS << "bind reference to a temporary";
5272 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005273
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005274 case SK_ExtraneousCopyToTemporary:
5275 OS << "extraneous C++03 copy to temporary";
5276 break;
5277
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005278 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00005279 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005280 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005281
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005282 case SK_QualificationConversionRValue:
5283 OS << "qualification conversion (rvalue)";
5284
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005285 case SK_QualificationConversionXValue:
5286 OS << "qualification conversion (xvalue)";
5287
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005288 case SK_QualificationConversionLValue:
5289 OS << "qualification conversion (lvalue)";
5290 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005291
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005292 case SK_ConversionSequence:
5293 OS << "implicit conversion sequence (";
5294 S->ICS->DebugPrint(); // FIXME: use OS
5295 OS << ")";
5296 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005297
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005298 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005299 OS << "list aggregate initialization";
5300 break;
5301
5302 case SK_ListConstructorCall:
5303 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005304 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005305
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005306 case SK_ConstructorInitialization:
5307 OS << "constructor initialization";
5308 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005309
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005310 case SK_ZeroInitialization:
5311 OS << "zero initialization";
5312 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005313
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005314 case SK_CAssignment:
5315 OS << "C assignment";
5316 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005317
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005318 case SK_StringInit:
5319 OS << "string initialization";
5320 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005321
5322 case SK_ObjCObjectConversion:
5323 OS << "Objective-C object conversion";
5324 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005325
5326 case SK_ArrayInit:
5327 OS << "array initialization";
5328 break;
John McCall31168b02011-06-15 23:02:42 +00005329
5330 case SK_PassByIndirectCopyRestore:
5331 OS << "pass by indirect copy and restore";
5332 break;
5333
5334 case SK_PassByIndirectRestore:
5335 OS << "pass by indirect restore";
5336 break;
5337
5338 case SK_ProduceObjCObject:
5339 OS << "Objective-C object retension";
5340 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005341 }
5342 }
5343}
5344
5345void InitializationSequence::dump() const {
5346 dump(llvm::errs());
5347}
5348
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005349static void DiagnoseNarrowingInInitList(
5350 Sema& S, QualType EntityType, const Expr *InitE,
5351 bool Constant, const APValue &ConstantValue) {
5352 if (Constant) {
5353 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005354 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005355 ? diag::err_init_list_constant_narrowing
5356 : diag::warn_init_list_constant_narrowing)
5357 << InitE->getSourceRange()
5358 << ConstantValue
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005359 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005360 } else
5361 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005362 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005363 ? diag::err_init_list_variable_narrowing
5364 : diag::warn_init_list_variable_narrowing)
5365 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005366 << InitE->getType().getLocalUnqualifiedType()
5367 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005368
5369 llvm::SmallString<128> StaticCast;
5370 llvm::raw_svector_ostream OS(StaticCast);
5371 OS << "static_cast<";
5372 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5373 // It's important to use the typedef's name if there is one so that the
5374 // fixit doesn't break code using types like int64_t.
5375 //
5376 // FIXME: This will break if the typedef requires qualification. But
5377 // getQualifiedNameAsString() includes non-machine-parsable components.
5378 OS << TT->getDecl();
5379 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5380 OS << BT->getName(S.getLangOptions());
5381 else {
5382 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5383 // with a broken cast.
5384 return;
5385 }
5386 OS << ">(";
5387 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5388 << InitE->getSourceRange()
5389 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5390 << FixItHint::CreateInsertion(
5391 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5392}
5393
Douglas Gregore1314a62009-12-18 05:02:21 +00005394//===----------------------------------------------------------------------===//
5395// Initialization helper functions
5396//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005397bool
5398Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5399 ExprResult Init) {
5400 if (Init.isInvalid())
5401 return false;
5402
5403 Expr *InitE = Init.get();
5404 assert(InitE && "No initialization expression");
5405
5406 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5407 SourceLocation());
5408 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005409 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005410}
5411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005412ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005413Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5414 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005415 ExprResult Init,
5416 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005417 if (Init.isInvalid())
5418 return ExprError();
5419
John McCall1f425642010-11-11 03:21:53 +00005420 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005421 assert(InitE && "No initialization expression?");
5422
5423 if (EqualLoc.isInvalid())
5424 EqualLoc = InitE->getLocStart();
5425
5426 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5427 EqualLoc);
5428 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5429 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005430
5431 bool Constant = false;
5432 APValue Result;
5433 if (TopLevelOfInitList &&
5434 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5435 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5436 Constant, Result);
5437 }
John McCallfaf5fb42010-08-26 23:41:50 +00005438 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005439}