blob: cd8505932b4e656fe3d1ceae1f729d40c2881b4b [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
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000173 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000176
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000180 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000183 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000188 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000189 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000191 unsigned &StructuredIndex,
192 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000194 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000198 void CheckComplexType(const InitializedEntity &Entity,
199 InitListExpr *IList, QualType DeclType,
200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000203 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000204 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
207 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000208 void CheckReferenceType(const InitializedEntity &Entity,
209 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000210 unsigned &Index,
211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000213 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000214 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000215 InitListExpr *StructuredList,
216 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000217 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000218 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000219 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000221 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000222 unsigned &StructuredIndex,
223 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000224 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000225 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000226 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000228 InitListExpr *StructuredList,
229 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000230 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000231 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000232 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000233 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234 RecordDecl::field_iterator *NextField,
235 llvm::APSInt *NextElementIndex,
236 unsigned &Index,
237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000239 bool FinishSubobjectInit,
240 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000241 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
242 QualType CurrentObjectType,
243 InitListExpr *StructuredList,
244 unsigned StructuredIndex,
245 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000246 void UpdateStructuredListElement(InitListExpr *StructuredList,
247 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000248 Expr *expr);
249 int numArrayElements(QualType DeclType);
250 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000251
Douglas Gregor2bb07652009-12-22 00:05:34 +0000252 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
253 const InitializedEntity &ParentEntity,
254 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000255 void FillInValueInitializations(const InitializedEntity &Entity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000257 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
258 Expr *InitExpr, FieldDecl *Field,
259 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000260 void CheckValueInitializable(const InitializedEntity &Entity);
261
Douglas Gregor85df8d82009-01-29 00:45:39 +0000262public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000263 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000264 InitListExpr *IL, QualType &T, bool VerifyOnly,
265 bool AllowBraceElision);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000266 bool HadError() { return hadError; }
267
268 // @brief Retrieves the fully-structured initializer list used for
269 // semantic analysis and code generation.
270 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
271};
Chris Lattner9ececce2009-02-24 22:48:58 +0000272} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000273
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000274void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
275 assert(VerifyOnly &&
276 "CheckValueInitializable is only inteded for verification mode.");
277
278 SourceLocation Loc;
279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
282 if (InitSeq.Failed())
283 hadError = true;
284}
285
Douglas Gregor2bb07652009-12-22 00:05:34 +0000286void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
287 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000289 bool &RequiresSecondPass) {
290 SourceLocation Loc = ILE->getSourceRange().getBegin();
291 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000293 = InitializedEntity::InitializeMember(Field, &ParentEntity);
294 if (Init >= NumInits || !ILE->getInit(Init)) {
295 // FIXME: We probably don't need to handle references
296 // specially here, since value-initialization of references is
297 // handled in InitializationSequence.
298 if (Field->getType()->isReferenceType()) {
299 // C++ [dcl.init.aggr]p9:
300 // If an incomplete or empty initializer-list leaves a
301 // member of reference type uninitialized, the program is
302 // ill-formed.
303 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
304 << Field->getType()
305 << ILE->getSyntacticForm()->getSourceRange();
306 SemaRef.Diag(Field->getLocation(),
307 diag::note_uninit_reference_member);
308 hadError = true;
309 return;
310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311
Douglas Gregor2bb07652009-12-22 00:05:34 +0000312 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
313 true);
314 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
315 if (!InitSeq) {
316 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
317 hadError = true;
318 return;
319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000320
John McCalldadc5752010-08-24 06:29:42 +0000321 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000322 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000323 if (MemberInit.isInvalid()) {
324 hadError = true;
325 return;
326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 if (hadError) {
329 // Do nothing
330 } else if (Init < NumInits) {
331 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000332 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000333 // Value-initialization requires a constructor call, so
334 // extend the initializer list to include the constructor
335 // call and make a note that we'll need to take another pass
336 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000337 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000338 RequiresSecondPass = true;
339 }
340 } else if (InitListExpr *InnerILE
341 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000342 FillInValueInitializations(MemberEntity, InnerILE,
343 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000344}
345
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000346/// Recursively replaces NULL values within the given initializer list
347/// with expressions that perform value-initialization of the
348/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000349void
Douglas Gregor723796a2009-12-16 06:35:08 +0000350InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
351 InitListExpr *ILE,
352 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000353 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000354 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000355 SourceLocation Loc = ILE->getSourceRange().getBegin();
356 if (ILE->getSyntacticForm())
357 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000358
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000359 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000360 if (RType->getDecl()->isUnion() &&
361 ILE->getInitializedFieldInUnion())
362 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
363 Entity, ILE, RequiresSecondPass);
364 else {
365 unsigned Init = 0;
366 for (RecordDecl::field_iterator
367 Field = RType->getDecl()->field_begin(),
368 FieldEnd = RType->getDecl()->field_end();
369 Field != FieldEnd; ++Field) {
370 if (Field->isUnnamedBitfield())
371 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000372
Douglas Gregor2bb07652009-12-22 00:05:34 +0000373 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000374 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000375
376 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
377 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000378 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379
Douglas Gregor2bb07652009-12-22 00:05:34 +0000380 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000381
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382 // Only look at the first initialization of a union.
383 if (RType->getDecl()->isUnion())
384 break;
385 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000386 }
387
388 return;
Mike Stump11289f42009-09-09 15:08:12 +0000389 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000390
391 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Douglas Gregor723796a2009-12-16 06:35:08 +0000393 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000394 unsigned NumInits = ILE->getNumInits();
395 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000396 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000397 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000398 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
399 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000401 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000402 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000403 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000404 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000406 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000407 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000408 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000409
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000411 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000412 if (hadError)
413 return;
414
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000415 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
416 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000417 ElementEntity.setElementIndex(Init);
418
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000419 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
420 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000421 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
422 true);
423 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
424 if (!InitSeq) {
425 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000426 hadError = true;
427 return;
428 }
429
John McCalldadc5752010-08-24 06:29:42 +0000430 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000431 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000432 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000433 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000434 return;
435 }
436
437 if (hadError) {
438 // Do nothing
439 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000440 // For arrays, just set the expression used for value-initialization
441 // of the "holes" in the array.
442 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
443 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
444 else
445 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000446 } else {
447 // For arrays, just set the expression used for value-initialization
448 // of the rest of elements and exit.
449 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
450 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
451 return;
452 }
453
Sebastian Redld201edf2011-06-05 13:59:11 +0000454 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000455 // Value-initialization requires a constructor call, so
456 // extend the initializer list to include the constructor
457 // call and make a note that we'll need to take another pass
458 // through the initializer list.
459 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
460 RequiresSecondPass = true;
461 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000462 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000463 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000464 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000465 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000466 }
467}
468
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000469
Douglas Gregor723796a2009-12-16 06:35:08 +0000470InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000471 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000472 bool VerifyOnly, bool AllowBraceElision)
Richard Smith0f8ede12011-12-20 04:00:21 +0000473 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000474 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000475
Eli Friedman23a9e312008-05-19 19:16:24 +0000476 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000477 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000478 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000479 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000480 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000481 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000482 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000483
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000484 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000485 bool RequiresSecondPass = false;
486 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000487 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000489 RequiresSecondPass);
490 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000491}
492
493int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000494 // FIXME: use a proper constant
495 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000496 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000497 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000498 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
499 }
500 return maxElements;
501}
502
503int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000504 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000505 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000506 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000507 Field = structDecl->field_begin(),
508 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000509 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000510 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 ++InitializableMembers;
512 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000513 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000514 return std::min(InitializableMembers, 1);
515 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000516}
517
Anders Carlsson6cabf312010-01-23 23:23:01 +0000518void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000519 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000520 QualType T, unsigned &Index,
521 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000522 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000523 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000524
Steve Narofff8ecff22008-05-01 22:18:59 +0000525 if (T->isArrayType())
526 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000527 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000528 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000529 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000530 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000531 else
David Blaikie83d382b2011-09-23 05:06:16 +0000532 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000533
Eli Friedmane0f832b2008-05-25 13:49:22 +0000534 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000535 if (!VerifyOnly)
536 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
537 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000538 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000539 hadError = true;
540 return;
541 }
542
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000543 // Build a structured initializer list corresponding to this subobject.
544 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000545 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
546 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000547 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
548 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000549 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000550
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000551 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000552 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000554 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000555 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000556 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000557
558 if (VerifyOnly) {
559 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
560 hadError = true;
561 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000562 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000563
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000564 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000565 // Update the structured sub-object initializer so that it's ending
566 // range corresponds with the end of the last initializer it used.
567 if (EndIndex < ParentIList->getNumInits()) {
568 SourceLocation EndLoc
569 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
570 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000573 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000574 if (T->isArrayType() || T->isRecordType()) {
575 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000576 AllowBraceElision ? diag::warn_missing_braces :
577 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000578 << StructuredSubobjectInitList->getSourceRange()
579 << FixItHint::CreateInsertion(
580 StructuredSubobjectInitList->getLocStart(), "{")
581 << FixItHint::CreateInsertion(
582 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000584 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000585 if (!AllowBraceElision)
586 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000587 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000588 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000589}
590
Anders Carlsson6cabf312010-01-23 23:23:01 +0000591void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000592 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000593 unsigned &Index,
594 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 unsigned &StructuredIndex,
596 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000597 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000598 if (!VerifyOnly) {
599 SyntacticToSemantic[IList] = StructuredList;
600 StructuredList->setSyntacticForm(IList);
601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000603 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000604 if (!VerifyOnly) {
605 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
606 IList->setType(ExprTy);
607 StructuredList->setType(ExprTy);
608 }
Eli Friedman85f54972008-05-25 13:22:35 +0000609 if (hadError)
610 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000611
Eli Friedman85f54972008-05-25 13:22:35 +0000612 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000614 if (VerifyOnly) {
615 if (SemaRef.getLangOptions().CPlusPlus ||
616 (SemaRef.getLangOptions().OpenCL &&
617 IList->getType()->isVectorType())) {
618 hadError = true;
619 }
620 return;
621 }
622
Eli Friedmanbd327452009-05-29 20:20:05 +0000623 if (StructuredIndex == 1 &&
624 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000625 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000626 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000627 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000628 hadError = true;
629 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000630 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000631 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000632 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000633 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000634 // Don't complain for incomplete types, since we'll get an error
635 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000636 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000637 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000638 CurrentObjectType->isArrayType()? 0 :
639 CurrentObjectType->isVectorType()? 1 :
640 CurrentObjectType->isScalarType()? 2 :
641 CurrentObjectType->isUnionType()? 3 :
642 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000643
644 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000645 if (SemaRef.getLangOptions().CPlusPlus) {
646 DK = diag::err_excess_initializers;
647 hadError = true;
648 }
Nate Begeman425038c2009-07-07 21:53:06 +0000649 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
650 DK = diag::err_excess_initializers;
651 hadError = true;
652 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000653
Chris Lattnerb0912a52009-02-24 22:50:46 +0000654 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000655 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000656 }
657 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000658
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000659 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
660 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000661 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000662 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000663 << FixItHint::CreateRemoval(IList->getLocStart())
664 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000665}
666
Anders Carlsson6cabf312010-01-23 23:23:01 +0000667void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000668 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000669 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000670 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000671 unsigned &Index,
672 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000673 unsigned &StructuredIndex,
674 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000675 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
676 // Explicitly braced initializer for complex type can be real+imaginary
677 // parts.
678 CheckComplexType(Entity, IList, DeclType, Index,
679 StructuredList, StructuredIndex);
680 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000681 CheckScalarType(Entity, IList, DeclType, Index,
682 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000683 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000685 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000686 } else if (DeclType->isAggregateType()) {
687 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000688 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000689 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000690 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000691 StructuredList, StructuredIndex,
692 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000693 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000694 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000695 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000696 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000698 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000699 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000700 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000701 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000702 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
703 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000704 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000705 if (!VerifyOnly)
706 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
707 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000708 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000709 } else if (DeclType->isRecordType()) {
710 // C++ [dcl.init]p14:
711 // [...] If the class is an aggregate (8.5.1), and the initializer
712 // is a brace-enclosed list, see 8.5.1.
713 //
714 // Note: 8.5.1 is handled below; here, we diagnose the case where
715 // we have an initializer list and a destination type that is not
716 // an aggregate.
717 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000718 if (!VerifyOnly)
719 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
720 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000721 hadError = true;
722 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000723 CheckReferenceType(Entity, IList, DeclType, Index,
724 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000725 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000726 if (!VerifyOnly)
727 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
728 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000729 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000730 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000731 if (!VerifyOnly)
732 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
733 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000734 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000735 }
736}
737
Anders Carlsson6cabf312010-01-23 23:23:01 +0000738void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000739 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000740 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000741 unsigned &Index,
742 InitListExpr *StructuredList,
743 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000744 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000745 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
746 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000747 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000748 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000749 = getStructuredSubobjectInit(IList, Index, ElemType,
750 StructuredList, StructuredIndex,
751 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000752 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000753 newStructuredList, newStructuredIndex);
754 ++StructuredIndex;
755 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000756 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000757 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000758 return CheckScalarType(Entity, IList, ElemType, Index,
759 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000760 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000761 return CheckReferenceType(Entity, IList, ElemType, Index,
762 StructuredList, StructuredIndex);
763 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000764
John McCall5decec92011-02-21 07:57:55 +0000765 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
766 // arrayType can be incomplete if we're initializing a flexible
767 // array member. There's nothing we can do with the completed
768 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769
John McCall5decec92011-02-21 07:57:55 +0000770 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000771 if (!VerifyOnly) {
772 CheckStringInit(Str, ElemType, arrayType, SemaRef);
773 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
774 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000775 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000776 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 }
John McCall5decec92011-02-21 07:57:55 +0000778
779 // Fall through for subaggregate initialization.
780
781 } else if (SemaRef.getLangOptions().CPlusPlus) {
782 // C++ [dcl.init.aggr]p12:
783 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000784 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000785 // an initializer-list. If the initializer can initialize a
786 // member, the member is initialized. [...]
787
788 // FIXME: Better EqualLoc?
789 InitializationKind Kind =
790 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
791 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
792
793 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000794 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000795 ExprResult Result =
796 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
797 if (Result.isInvalid())
798 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000799
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000800 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000801 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000802 }
John McCall5decec92011-02-21 07:57:55 +0000803 ++Index;
804 return;
805 }
806
807 // Fall through for subaggregate initialization
808 } else {
809 // C99 6.7.8p13:
810 //
811 // The initializer for a structure or union object that has
812 // automatic storage duration shall be either an initializer
813 // list as described below, or a single expression that has
814 // compatible structure or union type. In the latter case, the
815 // initial value of the object, including unnamed members, is
816 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000817 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000818 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000819 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
820 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000821 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000822 if (ExprRes.isInvalid())
823 hadError = true;
824 else {
825 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
826 if (ExprRes.isInvalid())
827 hadError = true;
828 }
829 UpdateStructuredListElement(StructuredList, StructuredIndex,
830 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000831 ++Index;
832 return;
833 }
John Wiegley01296292011-04-08 18:41:53 +0000834 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000835 // Fall through for subaggregate initialization
836 }
837
838 // C++ [dcl.init.aggr]p12:
839 //
840 // [...] Otherwise, if the member is itself a non-empty
841 // subaggregate, brace elision is assumed and the initializer is
842 // considered for the initialization of the first member of
843 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000844 if (!SemaRef.getLangOptions().OpenCL &&
845 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000846 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
847 StructuredIndex);
848 ++StructuredIndex;
849 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000850 if (!VerifyOnly) {
851 // We cannot initialize this element, so let
852 // PerformCopyInitialization produce the appropriate diagnostic.
853 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
854 SemaRef.Owned(expr),
855 /*TopLevelOfInitList=*/true);
856 }
John McCall5decec92011-02-21 07:57:55 +0000857 hadError = true;
858 ++Index;
859 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000860 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000861}
862
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000863void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
864 InitListExpr *IList, QualType DeclType,
865 unsigned &Index,
866 InitListExpr *StructuredList,
867 unsigned &StructuredIndex) {
868 assert(Index == 0 && "Index in explicit init list must be zero");
869
870 // As an extension, clang supports complex initializers, which initialize
871 // a complex number component-wise. When an explicit initializer list for
872 // a complex number contains two two initializers, this extension kicks in:
873 // it exepcts the initializer list to contain two elements convertible to
874 // the element type of the complex type. The first element initializes
875 // the real part, and the second element intitializes the imaginary part.
876
877 if (IList->getNumInits() != 2)
878 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
879 StructuredIndex);
880
881 // This is an extension in C. (The builtin _Complex type does not exist
882 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000883 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000884 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
885 << IList->getSourceRange();
886
887 // Initialize the complex number.
888 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
889 InitializedEntity ElementEntity =
890 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
891
892 for (unsigned i = 0; i < 2; ++i) {
893 ElementEntity.setElementIndex(Index);
894 CheckSubElementType(ElementEntity, IList, elementType, Index,
895 StructuredList, StructuredIndex);
896 }
897}
898
899
Anders Carlsson6cabf312010-01-23 23:23:01 +0000900void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000901 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000902 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 InitListExpr *StructuredList,
904 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000905 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000906 if (!VerifyOnly)
907 SemaRef.Diag(IList->getLocStart(),
908 SemaRef.getLangOptions().CPlusPlus0x ?
909 diag::warn_cxx98_compat_empty_scalar_initializer :
910 diag::err_empty_scalar_initializer)
911 << IList->getSourceRange();
912 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000913 ++Index;
914 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000915 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000916 }
John McCall643169b2010-11-11 00:46:36 +0000917
918 Expr *expr = IList->getInit(Index);
919 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000920 if (!VerifyOnly)
921 SemaRef.Diag(SubIList->getLocStart(),
922 diag::warn_many_braces_around_scalar_init)
923 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000924
925 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
926 StructuredIndex);
927 return;
928 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000929 if (!VerifyOnly)
930 SemaRef.Diag(expr->getSourceRange().getBegin(),
931 diag::err_designator_for_scalar_init)
932 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000933 hadError = true;
934 ++Index;
935 ++StructuredIndex;
936 return;
937 }
938
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000939 if (VerifyOnly) {
940 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
941 hadError = true;
942 ++Index;
943 return;
944 }
945
John McCall643169b2010-11-11 00:46:36 +0000946 ExprResult Result =
947 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000948 SemaRef.Owned(expr),
949 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000950
951 Expr *ResultExpr = 0;
952
953 if (Result.isInvalid())
954 hadError = true; // types weren't compatible.
955 else {
956 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000957
John McCall643169b2010-11-11 00:46:36 +0000958 if (ResultExpr != expr) {
959 // The type was promoted, update initializer list.
960 IList->setInit(Index, ResultExpr);
961 }
962 }
963 if (hadError)
964 ++StructuredIndex;
965 else
966 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
967 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000968}
969
Anders Carlsson6cabf312010-01-23 23:23:01 +0000970void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
971 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000972 unsigned &Index,
973 InitListExpr *StructuredList,
974 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000975 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000976 // FIXME: It would be wonderful if we could point at the actual member. In
977 // general, it would be useful to pass location information down the stack,
978 // so that we know the location (or decl) of the "current object" being
979 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000980 if (!VerifyOnly)
981 SemaRef.Diag(IList->getLocStart(),
982 diag::err_init_reference_member_uninitialized)
983 << DeclType
984 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000985 hadError = true;
986 ++Index;
987 ++StructuredIndex;
988 return;
989 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000990
991 Expr *expr = IList->getInit(Index);
Sebastian Redl29526f02011-11-27 16:50:07 +0000992 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000993 if (!VerifyOnly)
994 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
995 << DeclType << IList->getSourceRange();
996 hadError = true;
997 ++Index;
998 ++StructuredIndex;
999 return;
1000 }
1001
1002 if (VerifyOnly) {
1003 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1004 hadError = true;
1005 ++Index;
1006 return;
1007 }
1008
1009 ExprResult Result =
1010 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1011 SemaRef.Owned(expr),
1012 /*TopLevelOfInitList=*/true);
1013
1014 if (Result.isInvalid())
1015 hadError = true;
1016
1017 expr = Result.takeAs<Expr>();
1018 IList->setInit(Index, expr);
1019
1020 if (hadError)
1021 ++StructuredIndex;
1022 else
1023 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1024 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001025}
1026
Anders Carlsson6cabf312010-01-23 23:23:01 +00001027void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001028 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001029 unsigned &Index,
1030 InitListExpr *StructuredList,
1031 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001032 const VectorType *VT = DeclType->getAs<VectorType>();
1033 unsigned maxElements = VT->getNumElements();
1034 unsigned numEltsInit = 0;
1035 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001036
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001037 if (Index >= IList->getNumInits()) {
1038 // Make sure the element type can be value-initialized.
1039 if (VerifyOnly)
1040 CheckValueInitializable(
1041 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1042 return;
1043 }
1044
John McCall6a16b2f2010-10-30 00:11:39 +00001045 if (!SemaRef.getLangOptions().OpenCL) {
1046 // If the initializing element is a vector, try to copy-initialize
1047 // instead of breaking it apart (which is doomed to failure anyway).
1048 Expr *Init = IList->getInit(Index);
1049 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001050 if (VerifyOnly) {
1051 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1052 hadError = true;
1053 ++Index;
1054 return;
1055 }
1056
John McCall6a16b2f2010-10-30 00:11:39 +00001057 ExprResult Result =
1058 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001059 SemaRef.Owned(Init),
1060 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001061
1062 Expr *ResultExpr = 0;
1063 if (Result.isInvalid())
1064 hadError = true; // types weren't compatible.
1065 else {
1066 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001067
John McCall6a16b2f2010-10-30 00:11:39 +00001068 if (ResultExpr != Init) {
1069 // The type was promoted, update initializer list.
1070 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001071 }
1072 }
John McCall6a16b2f2010-10-30 00:11:39 +00001073 if (hadError)
1074 ++StructuredIndex;
1075 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001076 UpdateStructuredListElement(StructuredList, StructuredIndex,
1077 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001078 ++Index;
1079 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
John McCall6a16b2f2010-10-30 00:11:39 +00001082 InitializedEntity ElementEntity =
1083 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
John McCall6a16b2f2010-10-30 00:11:39 +00001085 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1086 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001087 if (Index >= IList->getNumInits()) {
1088 if (VerifyOnly)
1089 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001090 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001091 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001092
John McCall6a16b2f2010-10-30 00:11:39 +00001093 ElementEntity.setElementIndex(Index);
1094 CheckSubElementType(ElementEntity, IList, elementType, Index,
1095 StructuredList, StructuredIndex);
1096 }
1097 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001098 }
John McCall6a16b2f2010-10-30 00:11:39 +00001099
1100 InitializedEntity ElementEntity =
1101 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
John McCall6a16b2f2010-10-30 00:11:39 +00001103 // OpenCL initializers allows vectors to be constructed from vectors.
1104 for (unsigned i = 0; i < maxElements; ++i) {
1105 // Don't attempt to go past the end of the init list
1106 if (Index >= IList->getNumInits())
1107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
John McCall6a16b2f2010-10-30 00:11:39 +00001109 ElementEntity.setElementIndex(Index);
1110
1111 QualType IType = IList->getInit(Index)->getType();
1112 if (!IType->isVectorType()) {
1113 CheckSubElementType(ElementEntity, IList, elementType, Index,
1114 StructuredList, StructuredIndex);
1115 ++numEltsInit;
1116 } else {
1117 QualType VecType;
1118 const VectorType *IVT = IType->getAs<VectorType>();
1119 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
John McCall6a16b2f2010-10-30 00:11:39 +00001121 if (IType->isExtVectorType())
1122 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1123 else
1124 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001125 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001126 CheckSubElementType(ElementEntity, IList, VecType, Index,
1127 StructuredList, StructuredIndex);
1128 numEltsInit += numIElts;
1129 }
1130 }
1131
1132 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001133 if (numEltsInit != maxElements) {
1134 if (!VerifyOnly)
1135 SemaRef.Diag(IList->getSourceRange().getBegin(),
1136 diag::err_vector_incorrect_num_initializers)
1137 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1138 hadError = true;
1139 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001140}
1141
Anders Carlsson6cabf312010-01-23 23:23:01 +00001142void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001143 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001144 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001145 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001146 unsigned &Index,
1147 InitListExpr *StructuredList,
1148 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001149 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1150
Steve Narofff8ecff22008-05-01 22:18:59 +00001151 // Check for the special-case of initializing an array with a string.
1152 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001153 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001154 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001155 // We place the string literal directly into the resulting
1156 // initializer list. This is the only place where the structure
1157 // of the structured initializer list doesn't match exactly,
1158 // because doing so would involve allocating one character
1159 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001160 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001161 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001162 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1163 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1164 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001165 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001166 return;
1167 }
1168 }
John McCall66884dd2011-02-21 07:22:22 +00001169 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001170 // Check for VLAs; in standard C it would be possible to check this
1171 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1172 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001173 if (!VerifyOnly)
1174 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1175 diag::err_variable_object_no_init)
1176 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001177 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001178 ++Index;
1179 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001180 return;
1181 }
1182
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001183 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001184 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1185 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001186 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001187 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001188 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001189 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001190 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001191 maxElementsKnown = true;
1192 }
1193
John McCall66884dd2011-02-21 07:22:22 +00001194 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001195 while (Index < IList->getNumInits()) {
1196 Expr *Init = IList->getInit(Index);
1197 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001198 // If we're not the subobject that matches up with the '{' for
1199 // the designator, we shouldn't be handling the
1200 // designator. Return immediately.
1201 if (!SubobjectIsDesignatorContext)
1202 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001203
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001204 // Handle this designated initializer. elementIndex will be
1205 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001206 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001207 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001208 StructuredList, StructuredIndex, true,
1209 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001210 hadError = true;
1211 continue;
1212 }
1213
Douglas Gregor033d1252009-01-23 16:54:12 +00001214 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001215 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001216 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001217 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001218 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001219
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001220 // If the array is of incomplete type, keep track of the number of
1221 // elements in the initializer.
1222 if (!maxElementsKnown && elementIndex > maxElements)
1223 maxElements = elementIndex;
1224
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001225 continue;
1226 }
1227
1228 // If we know the maximum number of elements, and we've already
1229 // hit it, stop consuming elements in the initializer list.
1230 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001231 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001232
Anders Carlsson6cabf312010-01-23 23:23:01 +00001233 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001235 Entity);
1236 // Check this element.
1237 CheckSubElementType(ElementEntity, IList, elementType, Index,
1238 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001239 ++elementIndex;
1240
1241 // If the array is of incomplete type, keep track of the number of
1242 // elements in the initializer.
1243 if (!maxElementsKnown && elementIndex > maxElements)
1244 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001245 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001246 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001247 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001248 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001249 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001250 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001251 // Sizing an array implicitly to zero is not allowed by ISO C,
1252 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001253 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001254 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001255 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001256
Mike Stump11289f42009-09-09 15:08:12 +00001257 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001258 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001259 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001260 if (!hadError && VerifyOnly) {
1261 // Check if there are any members of the array that get value-initialized.
1262 // If so, check if doing that is possible.
1263 // FIXME: This needs to detect holes left by designated initializers too.
1264 if (maxElementsKnown && elementIndex < maxElements)
1265 CheckValueInitializable(InitializedEntity::InitializeElement(
1266 SemaRef.Context, 0, Entity));
1267 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001268}
1269
Eli Friedman3fa64df2011-08-23 22:24:57 +00001270bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1271 Expr *InitExpr,
1272 FieldDecl *Field,
1273 bool TopLevelObject) {
1274 // Handle GNU flexible array initializers.
1275 unsigned FlexArrayDiag;
1276 if (isa<InitListExpr>(InitExpr) &&
1277 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1278 // Empty flexible array init always allowed as an extension
1279 FlexArrayDiag = diag::ext_flexible_array_init;
1280 } else if (SemaRef.getLangOptions().CPlusPlus) {
1281 // Disallow flexible array init in C++; it is not required for gcc
1282 // compatibility, and it needs work to IRGen correctly in general.
1283 FlexArrayDiag = diag::err_flexible_array_init;
1284 } else if (!TopLevelObject) {
1285 // Disallow flexible array init on non-top-level object
1286 FlexArrayDiag = diag::err_flexible_array_init;
1287 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1288 // Disallow flexible array init on anything which is not a variable.
1289 FlexArrayDiag = diag::err_flexible_array_init;
1290 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1291 // Disallow flexible array init on local variables.
1292 FlexArrayDiag = diag::err_flexible_array_init;
1293 } else {
1294 // Allow other cases.
1295 FlexArrayDiag = diag::ext_flexible_array_init;
1296 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001297
1298 if (!VerifyOnly) {
1299 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1300 FlexArrayDiag)
1301 << InitExpr->getSourceRange().getBegin();
1302 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1303 << Field;
1304 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001305
1306 return FlexArrayDiag != diag::ext_flexible_array_init;
1307}
1308
Anders Carlsson6cabf312010-01-23 23:23:01 +00001309void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001310 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001311 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001312 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001313 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001314 unsigned &Index,
1315 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001316 unsigned &StructuredIndex,
1317 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001318 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001319
Eli Friedman23a9e312008-05-19 19:16:24 +00001320 // If the record is invalid, some of it's members are invalid. To avoid
1321 // confusion, we forgo checking the intializer for the entire record.
1322 if (structDecl->isInvalidDecl()) {
1323 hadError = true;
1324 return;
Mike Stump11289f42009-09-09 15:08:12 +00001325 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001326
1327 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001328 // Value-initialize the first named member of the union.
1329 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1330 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1331 Field != FieldEnd; ++Field) {
1332 if (Field->getDeclName()) {
1333 if (VerifyOnly)
1334 CheckValueInitializable(
1335 InitializedEntity::InitializeMember(*Field, &Entity));
1336 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001337 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001338 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001339 }
1340 }
1341 return;
1342 }
1343
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001344 // If structDecl is a forward declaration, this loop won't do
1345 // anything except look at designated initializers; That's okay,
1346 // because an error should get printed out elsewhere. It might be
1347 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001348 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001349 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001350 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001351 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001352 while (Index < IList->getNumInits()) {
1353 Expr *Init = IList->getInit(Index);
1354
1355 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001356 // If we're not the subobject that matches up with the '{' for
1357 // the designator, we shouldn't be handling the
1358 // designator. Return immediately.
1359 if (!SubobjectIsDesignatorContext)
1360 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001361
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001362 // Handle this designated initializer. Field will be updated to
1363 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001364 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001365 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001366 StructuredList, StructuredIndex,
1367 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001368 hadError = true;
1369
Douglas Gregora9add4e2009-02-12 19:00:39 +00001370 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001371
1372 // Disable check for missing fields when designators are used.
1373 // This matches gcc behaviour.
1374 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001375 continue;
1376 }
1377
1378 if (Field == FieldEnd) {
1379 // We've run out of fields. We're done.
1380 break;
1381 }
1382
Douglas Gregora9add4e2009-02-12 19:00:39 +00001383 // We've already initialized a member of a union. We're done.
1384 if (InitializedSomething && DeclType->isUnionType())
1385 break;
1386
Douglas Gregor91f84212008-12-11 16:49:14 +00001387 // If we've hit the flexible array member at the end, we're done.
1388 if (Field->getType()->isIncompleteArrayType())
1389 break;
1390
Douglas Gregor51695702009-01-29 16:53:55 +00001391 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001392 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001393 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001394 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001395 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001396
Douglas Gregora82064c2011-06-29 21:51:31 +00001397 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001398 bool InvalidUse;
1399 if (VerifyOnly)
1400 InvalidUse = !SemaRef.CanUseDecl(*Field);
1401 else
1402 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1403 IList->getInit(Index)->getLocStart());
1404 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001405 ++Index;
1406 ++Field;
1407 hadError = true;
1408 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001409 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001410
Anders Carlsson6cabf312010-01-23 23:23:01 +00001411 InitializedEntity MemberEntity =
1412 InitializedEntity::InitializeMember(*Field, &Entity);
1413 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1414 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001415 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001416
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001417 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001418 // Initialize the first field within the union.
1419 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001420 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001421
1422 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001423 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001424
John McCalle40b58e2010-03-11 19:32:38 +00001425 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001426 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1427 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1428 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001429 // It is possible we have one or more unnamed bitfields remaining.
1430 // Find first (if any) named field and emit warning.
1431 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1432 it != end; ++it) {
1433 if (!it->isUnnamedBitfield()) {
1434 SemaRef.Diag(IList->getSourceRange().getEnd(),
1435 diag::warn_missing_field_initializers) << it->getName();
1436 break;
1437 }
1438 }
1439 }
1440
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001441 // Check that any remaining fields can be value-initialized.
1442 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1443 !Field->getType()->isIncompleteArrayType()) {
1444 // FIXME: Should check for holes left by designated initializers too.
1445 for (; Field != FieldEnd && !hadError; ++Field) {
1446 if (!Field->isUnnamedBitfield())
1447 CheckValueInitializable(
1448 InitializedEntity::InitializeMember(*Field, &Entity));
1449 }
1450 }
1451
Mike Stump11289f42009-09-09 15:08:12 +00001452 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001453 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001454 return;
1455
Eli Friedman3fa64df2011-08-23 22:24:57 +00001456 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1457 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001458 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001459 ++Index;
1460 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001461 }
1462
Anders Carlsson6cabf312010-01-23 23:23:01 +00001463 InitializedEntity MemberEntity =
1464 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001465
Anders Carlsson6cabf312010-01-23 23:23:01 +00001466 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001468 StructuredList, StructuredIndex);
1469 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001471 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001472}
Steve Narofff8ecff22008-05-01 22:18:59 +00001473
Douglas Gregord5846a12009-04-15 06:41:24 +00001474/// \brief Expand a field designator that refers to a member of an
1475/// anonymous struct or union into a series of field designators that
1476/// refers to the field within the appropriate subobject.
1477///
Douglas Gregord5846a12009-04-15 06:41:24 +00001478static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001479 DesignatedInitExpr *DIE,
1480 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001481 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001482 typedef DesignatedInitExpr::Designator Designator;
1483
Douglas Gregord5846a12009-04-15 06:41:24 +00001484 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001485 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001486 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1487 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1488 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001489 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001490 DIE->getDesignator(DesigIdx)->getDotLoc(),
1491 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1492 else
1493 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1494 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001495 assert(isa<FieldDecl>(*PI));
1496 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001497 }
1498
1499 // Expand the current designator into the set of replacement
1500 // designators, so we have a full subobject path down to where the
1501 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001502 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001503 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001504}
Mike Stump11289f42009-09-09 15:08:12 +00001505
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001506/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001507/// corresponds to FieldName.
1508static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1509 IdentifierInfo *FieldName) {
1510 assert(AnonField->isAnonymousStructOrUnion());
1511 Decl *NextDecl = AnonField->getNextDeclInContext();
1512 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1513 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1514 return IF;
1515 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001516 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001517 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001518}
1519
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001520static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1521 DesignatedInitExpr *DIE) {
1522 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1523 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1524 for (unsigned I = 0; I < NumIndexExprs; ++I)
1525 IndexExprs[I] = DIE->getSubExpr(I + 1);
1526 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1527 DIE->size(), IndexExprs.data(),
1528 NumIndexExprs, DIE->getEqualOrColonLoc(),
1529 DIE->usesGNUSyntax(), DIE->getInit());
1530}
1531
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001532namespace {
1533
1534// Callback to only accept typo corrections that are for field members of
1535// the given struct or union.
1536class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1537 public:
1538 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1539 : Record(RD) {}
1540
1541 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1542 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1543 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1544 }
1545
1546 private:
1547 RecordDecl *Record;
1548};
1549
1550}
1551
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001552/// @brief Check the well-formedness of a C99 designated initializer.
1553///
1554/// Determines whether the designated initializer @p DIE, which
1555/// resides at the given @p Index within the initializer list @p
1556/// IList, is well-formed for a current object of type @p DeclType
1557/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001558/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001559/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001560///
1561/// @param IList The initializer list in which this designated
1562/// initializer occurs.
1563///
Douglas Gregora5324162009-04-15 04:56:10 +00001564/// @param DIE The designated initializer expression.
1565///
1566/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001567///
1568/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1569/// into which the designation in @p DIE should refer.
1570///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571/// @param NextField If non-NULL and the first designator in @p DIE is
1572/// a field, this will be set to the field declaration corresponding
1573/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001574///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001575/// @param NextElementIndex If non-NULL and the first designator in @p
1576/// DIE is an array designator or GNU array-range designator, this
1577/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001578///
1579/// @param Index Index into @p IList where the designated initializer
1580/// @p DIE occurs.
1581///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001582/// @param StructuredList The initializer list expression that
1583/// describes all of the subobject initializers in the order they'll
1584/// actually be initialized.
1585///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001586/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001587bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001588InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001589 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001590 DesignatedInitExpr *DIE,
1591 unsigned DesigIdx,
1592 QualType &CurrentObjectType,
1593 RecordDecl::field_iterator *NextField,
1594 llvm::APSInt *NextElementIndex,
1595 unsigned &Index,
1596 InitListExpr *StructuredList,
1597 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001598 bool FinishSubobjectInit,
1599 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001600 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001601 // Check the actual initialization for the designated object type.
1602 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001603
1604 // Temporarily remove the designator expression from the
1605 // initializer list that the child calls see, so that we don't try
1606 // to re-process the designator.
1607 unsigned OldIndex = Index;
1608 IList->setInit(OldIndex, DIE->getInit());
1609
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001610 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001611 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001612
1613 // Restore the designated initializer expression in the syntactic
1614 // form of the initializer list.
1615 if (IList->getInit(OldIndex) != DIE->getInit())
1616 DIE->setInit(IList->getInit(OldIndex));
1617 IList->setInit(OldIndex, DIE);
1618
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001619 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001620 }
1621
Douglas Gregora5324162009-04-15 04:56:10 +00001622 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001623 bool IsFirstDesignator = (DesigIdx == 0);
1624 if (!VerifyOnly) {
1625 assert((IsFirstDesignator || StructuredList) &&
1626 "Need a non-designated initializer list to start from");
1627
1628 // Determine the structural initializer list that corresponds to the
1629 // current subobject.
1630 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1631 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1632 StructuredList, StructuredIndex,
1633 SourceRange(D->getStartLocation(),
1634 DIE->getSourceRange().getEnd()));
1635 assert(StructuredList && "Expected a structured initializer list");
1636 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001637
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001638 if (D->isFieldDesignator()) {
1639 // C99 6.7.8p7:
1640 //
1641 // If a designator has the form
1642 //
1643 // . identifier
1644 //
1645 // then the current object (defined below) shall have
1646 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001647 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001648 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001649 if (!RT) {
1650 SourceLocation Loc = D->getDotLoc();
1651 if (Loc.isInvalid())
1652 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001653 if (!VerifyOnly)
1654 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1655 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001656 ++Index;
1657 return true;
1658 }
1659
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001660 // Note: we perform a linear search of the fields here, despite
1661 // the fact that we have a faster lookup method, because we always
1662 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001663 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001664 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001665 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001666 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001667 Field = RT->getDecl()->field_begin(),
1668 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001669 for (; Field != FieldEnd; ++Field) {
1670 if (Field->isUnnamedBitfield())
1671 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001672
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001673 // If we find a field representing an anonymous field, look in the
1674 // IndirectFieldDecl that follow for the designated initializer.
1675 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1676 if (IndirectFieldDecl *IF =
1677 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001678 // In verify mode, don't modify the original.
1679 if (VerifyOnly)
1680 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001681 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1682 D = DIE->getDesignator(DesigIdx);
1683 break;
1684 }
1685 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001686 if (KnownField && KnownField == *Field)
1687 break;
1688 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001689 break;
1690
1691 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001692 }
1693
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001694 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001695 if (VerifyOnly) {
1696 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001697 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001698 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001699
Douglas Gregord5846a12009-04-15 06:41:24 +00001700 // There was no normal field in the struct with the designated
1701 // name. Perform another lookup for this name, which may find
1702 // something that we can't designate (e.g., a member function),
1703 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001704 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001705 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001706 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001707 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001708 // Name lookup didn't find anything. Determine whether this
1709 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001710 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001711 TypoCorrection Corrected = SemaRef.CorrectTypo(
1712 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001713 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, &Validator,
1714 RT->getDecl());
1715 if (Corrected) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001716 std::string CorrectedStr(
1717 Corrected.getAsString(SemaRef.getLangOptions()));
1718 std::string CorrectedQuotedStr(
1719 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001720 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001722 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001723 << FieldName << CurrentObjectType << CorrectedQuotedStr
1724 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001726 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001727 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001728 } else {
1729 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1730 << FieldName << CurrentObjectType;
1731 ++Index;
1732 return true;
1733 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001736 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001737 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001738 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001739 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001740 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001742 ++Index;
1743 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001744 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001745
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001746 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001747 // The replacement field comes from typo correction; find it
1748 // in the list of fields.
1749 FieldIndex = 0;
1750 Field = RT->getDecl()->field_begin();
1751 for (; Field != FieldEnd; ++Field) {
1752 if (Field->isUnnamedBitfield())
1753 continue;
1754
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001756 Field->getIdentifier() == ReplacementField->getIdentifier())
1757 break;
1758
1759 ++FieldIndex;
1760 }
1761 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001762 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001763
1764 // All of the fields of a union are located at the same place in
1765 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001766 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001767 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001768 if (!VerifyOnly)
1769 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001770 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001771
Douglas Gregora82064c2011-06-29 21:51:31 +00001772 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001773 bool InvalidUse;
1774 if (VerifyOnly)
1775 InvalidUse = !SemaRef.CanUseDecl(*Field);
1776 else
1777 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1778 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001779 ++Index;
1780 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001781 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001782
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001783 if (!VerifyOnly) {
1784 // Update the designator with the field declaration.
1785 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001786
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001787 // Make sure that our non-designated initializer list has space
1788 // for a subobject corresponding to this field.
1789 if (FieldIndex >= StructuredList->getNumInits())
1790 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1791 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001792
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001793 // This designator names a flexible array member.
1794 if (Field->getType()->isIncompleteArrayType()) {
1795 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001796 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001797 // We can't designate an object within the flexible array
1798 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001799 if (!VerifyOnly) {
1800 DesignatedInitExpr::Designator *NextD
1801 = DIE->getDesignator(DesigIdx + 1);
1802 SemaRef.Diag(NextD->getStartLocation(),
1803 diag::err_designator_into_flexible_array_member)
1804 << SourceRange(NextD->getStartLocation(),
1805 DIE->getSourceRange().getEnd());
1806 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1807 << *Field;
1808 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001809 Invalid = true;
1810 }
1811
Chris Lattner001b29c2010-10-10 17:49:49 +00001812 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1813 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001814 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001815 if (!VerifyOnly) {
1816 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1817 diag::err_flexible_array_init_needs_braces)
1818 << DIE->getInit()->getSourceRange();
1819 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1820 << *Field;
1821 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001822 Invalid = true;
1823 }
1824
Eli Friedman3fa64df2011-08-23 22:24:57 +00001825 // Check GNU flexible array initializer.
1826 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1827 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001828 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001829
1830 if (Invalid) {
1831 ++Index;
1832 return true;
1833 }
1834
1835 // Initialize the array.
1836 bool prevHadError = hadError;
1837 unsigned newStructuredIndex = FieldIndex;
1838 unsigned OldIndex = Index;
1839 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001840
1841 InitializedEntity MemberEntity =
1842 InitializedEntity::InitializeMember(*Field, &Entity);
1843 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001844 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001845
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001846 IList->setInit(OldIndex, DIE);
1847 if (hadError && !prevHadError) {
1848 ++Field;
1849 ++FieldIndex;
1850 if (NextField)
1851 *NextField = Field;
1852 StructuredIndex = FieldIndex;
1853 return true;
1854 }
1855 } else {
1856 // Recurse to check later designated subobjects.
1857 QualType FieldType = (*Field)->getType();
1858 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001860 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001861 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1863 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001864 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001865 true, false))
1866 return true;
1867 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001868
1869 // Find the position of the next field to be initialized in this
1870 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001871 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001872 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001873
1874 // If this the first designator, our caller will continue checking
1875 // the rest of this struct/class/union subobject.
1876 if (IsFirstDesignator) {
1877 if (NextField)
1878 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001879 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001880 return false;
1881 }
1882
Douglas Gregor17bd0942009-01-28 23:36:17 +00001883 if (!FinishSubobjectInit)
1884 return false;
1885
Douglas Gregord5846a12009-04-15 06:41:24 +00001886 // We've already initialized something in the union; we're done.
1887 if (RT->getDecl()->isUnion())
1888 return hadError;
1889
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001890 // Check the remaining fields within this class/struct/union subobject.
1891 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892
Anders Carlsson6cabf312010-01-23 23:23:01 +00001893 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001894 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001895 return hadError && !prevHadError;
1896 }
1897
1898 // C99 6.7.8p6:
1899 //
1900 // If a designator has the form
1901 //
1902 // [ constant-expression ]
1903 //
1904 // then the current object (defined below) shall have array
1905 // type and the expression shall be an integer constant
1906 // expression. If the array is of unknown size, any
1907 // nonnegative value is valid.
1908 //
1909 // Additionally, cope with the GNU extension that permits
1910 // designators of the form
1911 //
1912 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001913 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001914 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001915 if (!VerifyOnly)
1916 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1917 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001918 ++Index;
1919 return true;
1920 }
1921
1922 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001923 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1924 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001925 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001926 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001927 DesignatedEndIndex = DesignatedStartIndex;
1928 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001929 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001930
Mike Stump11289f42009-09-09 15:08:12 +00001931 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001932 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001933 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001934 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001935 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001936
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001937 // Codegen can't handle evaluating array range designators that have side
1938 // effects, because we replicate the AST value for each initialized element.
1939 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1940 // elements with something that has a side effect, so codegen can emit an
1941 // "error unsupported" error instead of miscompiling the app.
1942 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001943 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001944 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001945 }
1946
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001947 if (isa<ConstantArrayType>(AT)) {
1948 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001949 DesignatedStartIndex
1950 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001951 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001952 DesignatedEndIndex
1953 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001954 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1955 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001956 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001957 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1958 diag::err_array_designator_too_large)
1959 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1960 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001961 ++Index;
1962 return true;
1963 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001964 } else {
1965 // Make sure the bit-widths and signedness match.
1966 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001967 DesignatedEndIndex
1968 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001969 else if (DesignatedStartIndex.getBitWidth() <
1970 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001971 DesignatedStartIndex
1972 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001973 DesignatedStartIndex.setIsUnsigned(true);
1974 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001975 }
Mike Stump11289f42009-09-09 15:08:12 +00001976
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001977 // Make sure that our non-designated initializer list has space
1978 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001979 if (!VerifyOnly &&
1980 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001981 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001982 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001983
Douglas Gregor17bd0942009-01-28 23:36:17 +00001984 // Repeatedly perform subobject initializations in the range
1985 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001986
Douglas Gregor17bd0942009-01-28 23:36:17 +00001987 // Move to the next designator
1988 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1989 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001991 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001992 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001993
Douglas Gregor17bd0942009-01-28 23:36:17 +00001994 while (DesignatedStartIndex <= DesignatedEndIndex) {
1995 // Recurse to check later designated subobjects.
1996 QualType ElementType = AT->getElementType();
1997 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001999 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2001 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002002 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002003 (DesignatedStartIndex == DesignatedEndIndex),
2004 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002005 return true;
2006
2007 // Move to the next index in the array that we'll be initializing.
2008 ++DesignatedStartIndex;
2009 ElementIndex = DesignatedStartIndex.getZExtValue();
2010 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002011
2012 // If this the first designator, our caller will continue checking
2013 // the rest of this array subobject.
2014 if (IsFirstDesignator) {
2015 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002016 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002017 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002018 return false;
2019 }
Mike Stump11289f42009-09-09 15:08:12 +00002020
Douglas Gregor17bd0942009-01-28 23:36:17 +00002021 if (!FinishSubobjectInit)
2022 return false;
2023
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002024 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002025 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002026 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002027 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002028 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002029 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002030}
2031
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002032// Get the structured initializer list for a subobject of type
2033// @p CurrentObjectType.
2034InitListExpr *
2035InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2036 QualType CurrentObjectType,
2037 InitListExpr *StructuredList,
2038 unsigned StructuredIndex,
2039 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002040 if (VerifyOnly)
2041 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002042 Expr *ExistingInit = 0;
2043 if (!StructuredList)
2044 ExistingInit = SyntacticToSemantic[IList];
2045 else if (StructuredIndex < StructuredList->getNumInits())
2046 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002047
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002048 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2049 return Result;
2050
2051 if (ExistingInit) {
2052 // We are creating an initializer list that initializes the
2053 // subobjects of the current object, but there was already an
2054 // initialization that completely initialized the current
2055 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002056 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002057 // struct X { int a, b; };
2058 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002059 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002060 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2061 // designated initializer re-initializes the whole
2062 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002063 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002064 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002065 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002066 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002067 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002068 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002069 << ExistingInit->getSourceRange();
2070 }
2071
Mike Stump11289f42009-09-09 15:08:12 +00002072 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002073 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2074 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002075 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002076
Douglas Gregora8a089b2010-07-13 18:40:04 +00002077 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002078
Douglas Gregor6d00c992009-03-20 23:58:33 +00002079 // Pre-allocate storage for the structured initializer list.
2080 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002081 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002082 bool GotNumInits = false;
2083 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002084 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002085 GotNumInits = true;
2086 } else if (Index < IList->getNumInits()) {
2087 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002088 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002089 GotNumInits = true;
2090 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002091 }
2092
Mike Stump11289f42009-09-09 15:08:12 +00002093 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002094 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2095 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2096 NumElements = CAType->getSize().getZExtValue();
2097 // Simple heuristic so that we don't allocate a very large
2098 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002099 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002100 NumElements = 0;
2101 }
John McCall9dd450b2009-09-21 23:43:11 +00002102 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002103 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002104 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002105 RecordDecl *RDecl = RType->getDecl();
2106 if (RDecl->isUnion())
2107 NumElements = 1;
2108 else
Mike Stump11289f42009-09-09 15:08:12 +00002109 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002110 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002111 }
2112
Ted Kremenekac034612010-04-13 23:39:13 +00002113 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002114
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002115 // Link this new initializer list into the structured initializer
2116 // lists.
2117 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002118 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002119 else {
2120 Result->setSyntacticForm(IList);
2121 SyntacticToSemantic[IList] = Result;
2122 }
2123
2124 return Result;
2125}
2126
2127/// Update the initializer at index @p StructuredIndex within the
2128/// structured initializer list to the value @p expr.
2129void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2130 unsigned &StructuredIndex,
2131 Expr *expr) {
2132 // No structured initializer list to update
2133 if (!StructuredList)
2134 return;
2135
Ted Kremenekac034612010-04-13 23:39:13 +00002136 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2137 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002138 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002139 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002140 diag::warn_initializer_overrides)
2141 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002142 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002143 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002144 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002145 << PrevInit->getSourceRange();
2146 }
Mike Stump11289f42009-09-09 15:08:12 +00002147
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002148 ++StructuredIndex;
2149}
2150
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002151/// Check that the given Index expression is a valid array designator
2152/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002153/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002154/// and produces a reasonable diagnostic if there is a
2155/// failure. Returns true if there was an error, false otherwise. If
2156/// everything went okay, Value will receive the value of the constant
2157/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00002158static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002159CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002160 SourceLocation Loc = Index->getSourceRange().getBegin();
2161
2162 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002163 if (S.VerifyIntegerConstantExpression(Index, &Value))
2164 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002165
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002166 if (Value.isSigned() && Value.isNegative())
2167 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002168 << Value.toString(10) << Index->getSourceRange();
2169
Douglas Gregor51650d32009-01-23 21:04:18 +00002170 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002171 return false;
2172}
2173
John McCalldadc5752010-08-24 06:29:42 +00002174ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002175 SourceLocation Loc,
2176 bool GNUSyntax,
2177 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002178 typedef DesignatedInitExpr::Designator ASTDesignator;
2179
2180 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002181 SmallVector<ASTDesignator, 32> Designators;
2182 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002183
2184 // Build designators and check array designator expressions.
2185 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2186 const Designator &D = Desig.getDesignator(Idx);
2187 switch (D.getKind()) {
2188 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002189 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002190 D.getFieldLoc()));
2191 break;
2192
2193 case Designator::ArrayDesignator: {
2194 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2195 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002196 if (!Index->isTypeDependent() &&
2197 !Index->isValueDependent() &&
2198 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002199 Invalid = true;
2200 else {
2201 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002202 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002203 D.getRBracketLoc()));
2204 InitExpressions.push_back(Index);
2205 }
2206 break;
2207 }
2208
2209 case Designator::ArrayRangeDesignator: {
2210 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2211 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2212 llvm::APSInt StartValue;
2213 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002214 bool StartDependent = StartIndex->isTypeDependent() ||
2215 StartIndex->isValueDependent();
2216 bool EndDependent = EndIndex->isTypeDependent() ||
2217 EndIndex->isValueDependent();
2218 if ((!StartDependent &&
2219 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2220 (!EndDependent &&
2221 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002222 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002223 else {
2224 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002225 if (StartDependent || EndDependent) {
2226 // Nothing to compute.
2227 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002228 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002229 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002230 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002231
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002232 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002233 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002234 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002235 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2236 Invalid = true;
2237 } else {
2238 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002239 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002240 D.getEllipsisLoc(),
2241 D.getRBracketLoc()));
2242 InitExpressions.push_back(StartIndex);
2243 InitExpressions.push_back(EndIndex);
2244 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002245 }
2246 break;
2247 }
2248 }
2249 }
2250
2251 if (Invalid || Init.isInvalid())
2252 return ExprError();
2253
2254 // Clear out the expressions within the designation.
2255 Desig.ClearExprs(*this);
2256
2257 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002258 = DesignatedInitExpr::Create(Context,
2259 Designators.data(), Designators.size(),
2260 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002261 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262
Richard Smithe4345902011-12-29 21:57:33 +00002263 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002264 Diag(DIE->getLocStart(), diag::ext_designated_init)
2265 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002266
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002267 return Owned(DIE);
2268}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002269
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002270//===----------------------------------------------------------------------===//
2271// Initialization entity
2272//===----------------------------------------------------------------------===//
2273
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002275 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002276 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002277{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002278 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2279 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002280 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002281 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002282 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002283 Type = VT->getElementType();
2284 } else {
2285 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2286 assert(CT && "Unexpected type");
2287 Kind = EK_ComplexElement;
2288 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002289 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002290}
2291
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002292InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002293 CXXBaseSpecifier *Base,
2294 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002295{
2296 InitializedEntity Result;
2297 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002298 Result.Base = reinterpret_cast<uintptr_t>(Base);
2299 if (IsInheritedVirtualBase)
2300 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301
Douglas Gregor1b303932009-12-22 15:35:07 +00002302 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002303 return Result;
2304}
2305
Douglas Gregor85dabae2009-12-16 01:38:02 +00002306DeclarationName InitializedEntity::getName() const {
2307 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002308 case EK_Parameter: {
2309 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2310 return (D ? D->getDeclName() : DeclarationName());
2311 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002312
2313 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002314 case EK_Member:
2315 return VariableOrMember->getDeclName();
2316
2317 case EK_Result:
2318 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002319 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002320 case EK_Temporary:
2321 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002322 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002323 case EK_ArrayElement:
2324 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002325 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002326 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002327 return DeclarationName();
2328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329
Douglas Gregor85dabae2009-12-16 01:38:02 +00002330 // Silence GCC warning
2331 return DeclarationName();
2332}
2333
Douglas Gregora4b592a2009-12-19 03:01:41 +00002334DeclaratorDecl *InitializedEntity::getDecl() const {
2335 switch (getKind()) {
2336 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002337 case EK_Member:
2338 return VariableOrMember;
2339
John McCall31168b02011-06-15 23:02:42 +00002340 case EK_Parameter:
2341 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2342
Douglas Gregora4b592a2009-12-19 03:01:41 +00002343 case EK_Result:
2344 case EK_Exception:
2345 case EK_New:
2346 case EK_Temporary:
2347 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002348 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002349 case EK_ArrayElement:
2350 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002351 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002352 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002353 return 0;
2354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002355
Douglas Gregora4b592a2009-12-19 03:01:41 +00002356 // Silence GCC warning
2357 return 0;
2358}
2359
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002360bool InitializedEntity::allowsNRVO() const {
2361 switch (getKind()) {
2362 case EK_Result:
2363 case EK_Exception:
2364 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002365
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002366 case EK_Variable:
2367 case EK_Parameter:
2368 case EK_Member:
2369 case EK_New:
2370 case EK_Temporary:
2371 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002372 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002373 case EK_ArrayElement:
2374 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002375 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002376 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002377 break;
2378 }
2379
2380 return false;
2381}
2382
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002383//===----------------------------------------------------------------------===//
2384// Initialization sequence
2385//===----------------------------------------------------------------------===//
2386
2387void InitializationSequence::Step::Destroy() {
2388 switch (Kind) {
2389 case SK_ResolveAddressOfOverloadedFunction:
2390 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002391 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002392 case SK_CastDerivedToBaseLValue:
2393 case SK_BindReference:
2394 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002395 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 case SK_UserConversion:
2397 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002398 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002399 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002400 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002401 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002402 case SK_UnwrapInitList:
2403 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002404 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002405 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002406 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002407 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002408 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002409 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002410 case SK_PassByIndirectCopyRestore:
2411 case SK_PassByIndirectRestore:
2412 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002413 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002414
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002415 case SK_ConversionSequence:
2416 delete ICS;
2417 }
2418}
2419
Douglas Gregor838fcc32010-03-26 20:14:36 +00002420bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002421 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002422}
2423
2424bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002425 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002426 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002427
Douglas Gregor838fcc32010-03-26 20:14:36 +00002428 switch (getFailureKind()) {
2429 case FK_TooManyInitsForReference:
2430 case FK_ArrayNeedsInitList:
2431 case FK_ArrayNeedsInitListOrStringLiteral:
2432 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2433 case FK_NonConstLValueReferenceBindingToTemporary:
2434 case FK_NonConstLValueReferenceBindingToUnrelated:
2435 case FK_RValueReferenceBindingToLValue:
2436 case FK_ReferenceInitDropsQualifiers:
2437 case FK_ReferenceInitFailed:
2438 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002439 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002440 case FK_TooManyInitsForScalar:
2441 case FK_ReferenceBindingToInitList:
2442 case FK_InitListBadDestinationType:
2443 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002444 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002445 case FK_ArrayTypeMismatch:
2446 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002447 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002448 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002449 case FK_PlaceholderType:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002450 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Douglas Gregor838fcc32010-03-26 20:14:36 +00002452 case FK_ReferenceInitOverloadFailed:
2453 case FK_UserConversionOverloadFailed:
2454 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002455 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002456 return FailedOverloadResult == OR_Ambiguous;
2457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458
Douglas Gregor838fcc32010-03-26 20:14:36 +00002459 return false;
2460}
2461
Douglas Gregorb33eed02010-04-16 22:09:46 +00002462bool InitializationSequence::isConstructorInitialization() const {
2463 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2464}
2465
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002466bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2467 const Expr *Initializer,
2468 bool *isInitializerConstant,
2469 APValue *ConstantValue) const {
2470 if (Steps.empty() || Initializer->isValueDependent())
2471 return false;
2472
2473 const Step &LastStep = Steps.back();
2474 if (LastStep.Kind != SK_ConversionSequence)
2475 return false;
2476
2477 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2478 const StandardConversionSequence *SCS = NULL;
2479 switch (ICS.getKind()) {
2480 case ImplicitConversionSequence::StandardConversion:
2481 SCS = &ICS.Standard;
2482 break;
2483 case ImplicitConversionSequence::UserDefinedConversion:
2484 SCS = &ICS.UserDefined.After;
2485 break;
2486 case ImplicitConversionSequence::AmbiguousConversion:
2487 case ImplicitConversionSequence::EllipsisConversion:
2488 case ImplicitConversionSequence::BadConversion:
2489 return false;
2490 }
2491
2492 // Check if SCS represents a narrowing conversion, according to C++0x
2493 // [dcl.init.list]p7:
2494 //
2495 // A narrowing conversion is an implicit conversion ...
2496 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2497 QualType FromType = SCS->getToType(0);
2498 QualType ToType = SCS->getToType(1);
2499 switch (PossibleNarrowing) {
2500 // * from a floating-point type to an integer type, or
2501 //
2502 // * from an integer type or unscoped enumeration type to a floating-point
2503 // type, except where the source is a constant expression and the actual
2504 // value after conversion will fit into the target type and will produce
2505 // the original value when converted back to the original type, or
2506 case ICK_Floating_Integral:
2507 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2508 *isInitializerConstant = false;
2509 return true;
2510 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2511 llvm::APSInt IntConstantValue;
2512 if (Initializer &&
2513 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2514 // Convert the integer to the floating type.
2515 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2516 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2517 llvm::APFloat::rmNearestTiesToEven);
2518 // And back.
2519 llvm::APSInt ConvertedValue = IntConstantValue;
2520 bool ignored;
2521 Result.convertToInteger(ConvertedValue,
2522 llvm::APFloat::rmTowardZero, &ignored);
2523 // If the resulting value is different, this was a narrowing conversion.
2524 if (IntConstantValue != ConvertedValue) {
2525 *isInitializerConstant = true;
2526 *ConstantValue = APValue(IntConstantValue);
2527 return true;
2528 }
2529 } else {
2530 // Variables are always narrowings.
2531 *isInitializerConstant = false;
2532 return true;
2533 }
2534 }
2535 return false;
2536
2537 // * from long double to double or float, or from double to float, except
2538 // where the source is a constant expression and the actual value after
2539 // conversion is within the range of values that can be represented (even
2540 // if it cannot be represented exactly), or
2541 case ICK_Floating_Conversion:
2542 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2543 // FromType is larger than ToType.
2544 Expr::EvalResult InitializerValue;
2545 // FIXME: Check whether Initializer is a constant expression according
2546 // to C++0x [expr.const], rather than just whether it can be folded.
Richard Smith7b553f12011-10-29 00:50:52 +00002547 if (Initializer->EvaluateAsRValue(InitializerValue, Ctx) &&
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002548 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2549 // Constant! (Except for FIXME above.)
2550 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2551 // Convert the source value into the target type.
2552 bool ignored;
2553 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2554 Ctx.getFloatTypeSemantics(ToType),
2555 llvm::APFloat::rmNearestTiesToEven, &ignored);
2556 // If there was no overflow, the source value is within the range of
2557 // values that can be represented.
2558 if (ConvertStatus & llvm::APFloat::opOverflow) {
2559 *isInitializerConstant = true;
2560 *ConstantValue = InitializerValue.Val;
2561 return true;
2562 }
2563 } else {
2564 *isInitializerConstant = false;
2565 return true;
2566 }
2567 }
2568 return false;
2569
2570 // * from an integer type or unscoped enumeration type to an integer type
2571 // that cannot represent all the values of the original type, except where
2572 // the source is a constant expression and the actual value after
2573 // conversion will fit into the target type and will produce the original
2574 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002575 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002576 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2577 // Boolean conversions can be from pointers and pointers to members
2578 // [conv.bool], and those aren't considered narrowing conversions.
2579 return false;
2580 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002581 case ICK_Integral_Conversion: {
2582 assert(FromType->isIntegralOrUnscopedEnumerationType());
2583 assert(ToType->isIntegralOrUnscopedEnumerationType());
2584 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2585 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2586 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2587 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2588
2589 if (FromWidth > ToWidth ||
2590 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2591 // Not all values of FromType can be represented in ToType.
2592 llvm::APSInt InitializerValue;
2593 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2594 *isInitializerConstant = true;
2595 *ConstantValue = APValue(InitializerValue);
2596
2597 // Add a bit to the InitializerValue so we don't have to worry about
2598 // signed vs. unsigned comparisons.
2599 InitializerValue = InitializerValue.extend(
2600 InitializerValue.getBitWidth() + 1);
2601 // Convert the initializer to and from the target width and signed-ness.
2602 llvm::APSInt ConvertedValue = InitializerValue;
2603 ConvertedValue = ConvertedValue.trunc(ToWidth);
2604 ConvertedValue.setIsSigned(ToSigned);
2605 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2606 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2607 // If the result is different, this was a narrowing conversion.
2608 return ConvertedValue != InitializerValue;
2609 } else {
2610 // Variables are always narrowings.
2611 *isInitializerConstant = false;
2612 return true;
2613 }
2614 }
2615 return false;
2616 }
2617
2618 default:
2619 // Other kinds of conversions are not narrowings.
2620 return false;
2621 }
2622}
2623
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002624void
2625InitializationSequence
2626::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2627 DeclAccessPair Found,
2628 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002629 Step S;
2630 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2631 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002632 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002633 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002634 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002635 Steps.push_back(S);
2636}
2637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002638void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002639 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002640 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002641 switch (VK) {
2642 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2643 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2644 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002645 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002646 S.Type = BaseType;
2647 Steps.push_back(S);
2648}
2649
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002650void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002651 bool BindingTemporary) {
2652 Step S;
2653 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2654 S.Type = T;
2655 Steps.push_back(S);
2656}
2657
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002658void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2659 Step S;
2660 S.Kind = SK_ExtraneousCopyToTemporary;
2661 S.Type = T;
2662 Steps.push_back(S);
2663}
2664
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002665void
2666InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2667 DeclAccessPair FoundDecl,
2668 QualType T,
2669 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002670 Step S;
2671 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002672 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002673 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002674 S.Function.Function = Function;
2675 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002676 Steps.push_back(S);
2677}
2678
2679void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002680 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002681 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002682 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002683 switch (VK) {
2684 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002685 S.Kind = SK_QualificationConversionRValue;
2686 break;
John McCall2536c6d2010-08-25 10:28:54 +00002687 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002688 S.Kind = SK_QualificationConversionXValue;
2689 break;
John McCall2536c6d2010-08-25 10:28:54 +00002690 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002691 S.Kind = SK_QualificationConversionLValue;
2692 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002693 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002694 S.Type = Ty;
2695 Steps.push_back(S);
2696}
2697
2698void InitializationSequence::AddConversionSequenceStep(
2699 const ImplicitConversionSequence &ICS,
2700 QualType T) {
2701 Step S;
2702 S.Kind = SK_ConversionSequence;
2703 S.Type = T;
2704 S.ICS = new ImplicitConversionSequence(ICS);
2705 Steps.push_back(S);
2706}
2707
Douglas Gregor51e77d52009-12-10 17:56:55 +00002708void InitializationSequence::AddListInitializationStep(QualType T) {
2709 Step S;
2710 S.Kind = SK_ListInitialization;
2711 S.Type = T;
2712 Steps.push_back(S);
2713}
2714
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002716InitializationSequence
2717::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2718 AccessSpecifier Access,
2719 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002720 bool HadMultipleCandidates,
2721 bool FromInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002722 Step S;
Sebastian Redled2e5322011-12-22 14:44:04 +00002723 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002724 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002725 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002726 S.Function.Function = Constructor;
2727 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002728 Steps.push_back(S);
2729}
2730
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002731void InitializationSequence::AddZeroInitializationStep(QualType T) {
2732 Step S;
2733 S.Kind = SK_ZeroInitialization;
2734 S.Type = T;
2735 Steps.push_back(S);
2736}
2737
Douglas Gregore1314a62009-12-18 05:02:21 +00002738void InitializationSequence::AddCAssignmentStep(QualType T) {
2739 Step S;
2740 S.Kind = SK_CAssignment;
2741 S.Type = T;
2742 Steps.push_back(S);
2743}
2744
Eli Friedman78275202009-12-19 08:11:05 +00002745void InitializationSequence::AddStringInitStep(QualType T) {
2746 Step S;
2747 S.Kind = SK_StringInit;
2748 S.Type = T;
2749 Steps.push_back(S);
2750}
2751
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002752void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2753 Step S;
2754 S.Kind = SK_ObjCObjectConversion;
2755 S.Type = T;
2756 Steps.push_back(S);
2757}
2758
Douglas Gregore2f943b2011-02-22 18:29:51 +00002759void InitializationSequence::AddArrayInitStep(QualType T) {
2760 Step S;
2761 S.Kind = SK_ArrayInit;
2762 S.Type = T;
2763 Steps.push_back(S);
2764}
2765
John McCall31168b02011-06-15 23:02:42 +00002766void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2767 bool shouldCopy) {
2768 Step s;
2769 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2770 : SK_PassByIndirectRestore);
2771 s.Type = type;
2772 Steps.push_back(s);
2773}
2774
2775void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2776 Step S;
2777 S.Kind = SK_ProduceObjCObject;
2778 S.Type = T;
2779 Steps.push_back(S);
2780}
2781
Sebastian Redl29526f02011-11-27 16:50:07 +00002782void InitializationSequence::RewrapReferenceInitList(QualType T,
2783 InitListExpr *Syntactic) {
2784 assert(Syntactic->getNumInits() == 1 &&
2785 "Can only rewrap trivial init lists.");
2786 Step S;
2787 S.Kind = SK_UnwrapInitList;
2788 S.Type = Syntactic->getInit(0)->getType();
2789 Steps.insert(Steps.begin(), S);
2790
2791 S.Kind = SK_RewrapInitList;
2792 S.Type = T;
2793 S.WrappingSyntacticList = Syntactic;
2794 Steps.push_back(S);
2795}
2796
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002797void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002798 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002799 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002800 this->Failure = Failure;
2801 this->FailedOverloadResult = Result;
2802}
2803
2804//===----------------------------------------------------------------------===//
2805// Attempt initialization
2806//===----------------------------------------------------------------------===//
2807
John McCall31168b02011-06-15 23:02:42 +00002808static void MaybeProduceObjCObject(Sema &S,
2809 InitializationSequence &Sequence,
2810 const InitializedEntity &Entity) {
2811 if (!S.getLangOptions().ObjCAutoRefCount) return;
2812
2813 /// When initializing a parameter, produce the value if it's marked
2814 /// __attribute__((ns_consumed)).
2815 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2816 if (!Entity.isParameterConsumed())
2817 return;
2818
2819 assert(Entity.getType()->isObjCRetainableType() &&
2820 "consuming an object of unretainable type?");
2821 Sequence.AddProduceObjCObjectStep(Entity.getType());
2822
2823 /// When initializing a return value, if the return type is a
2824 /// retainable type, then returns need to immediately retain the
2825 /// object. If an autorelease is required, it will be done at the
2826 /// last instant.
2827 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2828 if (!Entity.getType()->isObjCRetainableType())
2829 return;
2830
2831 Sequence.AddProduceObjCObjectStep(Entity.getType());
2832 }
2833}
2834
Sebastian Redled2e5322011-12-22 14:44:04 +00002835/// \brief When initializing from init list via constructor, deal with the
2836/// empty init list and std::initializer_list special cases.
2837///
2838/// \return True if this was a special case, false otherwise.
2839static bool TryListConstructionSpecialCases(Sema &S,
2840 Expr **Args, unsigned NumArgs,
2841 CXXRecordDecl *DestRecordDecl,
2842 QualType DestType,
2843 InitializationSequence &Sequence) {
2844 // C++0x [dcl.init.list]p3:
2845 // List-initialization of an object of type T is defined as follows:
2846 // - If the initializer list has no elements and T is a class type with
2847 // a default constructor, the object is value-initialized.
2848 if (NumArgs == 0) {
2849 if (CXXConstructorDecl *DefaultConstructor =
2850 S.LookupDefaultConstructor(DestRecordDecl)) {
2851 if (DefaultConstructor->isDeleted() ||
2852 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2853 // Fake an overload resolution failure.
2854 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2855 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2856 DefaultConstructor->getAccess());
2857 if (FunctionTemplateDecl *ConstructorTmpl =
2858 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2859 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2860 /*ExplicitArgs*/ 0,
2861 Args, NumArgs, CandidateSet,
2862 /*SuppressUserConversions*/ false);
2863 else
2864 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2865 Args, NumArgs, CandidateSet,
2866 /*SuppressUserConversions*/ false);
2867 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002868 InitializationSequence::FK_ListConstructorOverloadFailed,
2869 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002870 } else
2871 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2872 DefaultConstructor->getAccess(),
2873 DestType,
2874 /*MultipleCandidates=*/false,
2875 /*FromInitList=*/true);
2876 return true;
2877 }
2878 }
2879
2880 // - Otherwise, if T is a specialization of std::initializer_list, [...]
2881 // FIXME: Implement.
2882
2883 // Not a special case.
2884 return false;
2885}
2886
2887/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2888/// enumerates the constructors of the initialized entity and performs overload
2889/// resolution to select the best.
2890/// If FromInitList is true, this is list-initialization of a non-aggregate
2891/// class type.
2892static void TryConstructorInitialization(Sema &S,
2893 const InitializedEntity &Entity,
2894 const InitializationKind &Kind,
2895 Expr **Args, unsigned NumArgs,
2896 QualType DestType,
2897 InitializationSequence &Sequence,
2898 bool FromInitList = false) {
2899 // Check constructor arguments for self reference.
2900 if (DeclaratorDecl *DD = Entity.getDecl())
2901 // Parameters arguments are occassionially constructed with itself,
2902 // for instance, in recursive functions. Skip them.
2903 if (!isa<ParmVarDecl>(DD))
2904 for (unsigned i = 0; i < NumArgs; ++i)
2905 S.CheckSelfReference(DD, Args[i]);
2906
2907 // Build the candidate set directly in the initialization sequence
2908 // structure, so that it will persist if we fail.
2909 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2910 CandidateSet.clear();
2911
2912 // Determine whether we are allowed to call explicit constructors or
2913 // explicit conversion operators.
2914 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2915 Kind.getKind() == InitializationKind::IK_Value ||
2916 Kind.getKind() == InitializationKind::IK_Default);
2917
2918 // The type we're constructing needs to be complete.
2919 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2920 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2921 }
2922
2923 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2924 assert(DestRecordType && "Constructor initialization requires record type");
2925 CXXRecordDecl *DestRecordDecl
2926 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2927
2928 if (FromInitList &&
2929 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2930 DestType, Sequence))
2931 return;
2932
2933 // - Otherwise, if T is a class type, constructors are considered. The
2934 // applicable constructors are enumerated, and the best one is chosen
2935 // through overload resolution.
2936 DeclContext::lookup_iterator Con, ConEnd;
2937 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2938 Con != ConEnd; ++Con) {
2939 NamedDecl *D = *Con;
2940 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2941 bool SuppressUserConversions = false;
2942
2943 // Find the constructor (which may be a template).
2944 CXXConstructorDecl *Constructor = 0;
2945 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2946 if (ConstructorTmpl)
2947 Constructor = cast<CXXConstructorDecl>(
2948 ConstructorTmpl->getTemplatedDecl());
2949 else {
2950 Constructor = cast<CXXConstructorDecl>(D);
2951
2952 // If we're performing copy initialization using a copy constructor, we
2953 // suppress user-defined conversions on the arguments.
2954 // FIXME: Move constructors?
2955 if (Kind.getKind() == InitializationKind::IK_Copy &&
2956 Constructor->isCopyConstructor())
2957 SuppressUserConversions = true;
2958 }
2959
2960 if (!Constructor->isInvalidDecl() &&
2961 (AllowExplicit || !Constructor->isExplicit())) {
2962 if (ConstructorTmpl)
2963 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2964 /*ExplicitArgs*/ 0,
2965 Args, NumArgs, CandidateSet,
2966 SuppressUserConversions);
2967 else
2968 S.AddOverloadCandidate(Constructor, FoundDecl,
2969 Args, NumArgs, CandidateSet,
2970 SuppressUserConversions);
2971 }
2972 }
2973
2974 SourceLocation DeclLoc = Kind.getLocation();
2975
2976 // Perform overload resolution. If it fails, return the failed result.
2977 OverloadCandidateSet::iterator Best;
2978 if (OverloadingResult Result
2979 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002980 Sequence.SetOverloadFailure(FromInitList ?
2981 InitializationSequence::FK_ListConstructorOverloadFailed :
2982 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002983 Result);
2984 return;
2985 }
2986
2987 // C++0x [dcl.init]p6:
2988 // If a program calls for the default initialization of an object
2989 // of a const-qualified type T, T shall be a class type with a
2990 // user-provided default constructor.
2991 if (Kind.getKind() == InitializationKind::IK_Default &&
2992 Entity.getType().isConstQualified() &&
2993 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2994 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2995 return;
2996 }
2997
2998 // Add the constructor initialization step. Any cv-qualification conversion is
2999 // subsumed by the initialization.
3000 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3001 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3002 Sequence.AddConstructorInitializationStep(CtorDecl,
3003 Best->FoundDecl.getAccess(),
3004 DestType, HadMultipleCandidates,
3005 FromInitList);
3006}
3007
Sebastian Redl29526f02011-11-27 16:50:07 +00003008static bool
3009ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3010 Expr *Initializer,
3011 QualType &SourceType,
3012 QualType &UnqualifiedSourceType,
3013 QualType UnqualifiedTargetType,
3014 InitializationSequence &Sequence) {
3015 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3016 S.Context.OverloadTy) {
3017 DeclAccessPair Found;
3018 bool HadMultipleCandidates = false;
3019 if (FunctionDecl *Fn
3020 = S.ResolveAddressOfOverloadedFunction(Initializer,
3021 UnqualifiedTargetType,
3022 false, Found,
3023 &HadMultipleCandidates)) {
3024 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3025 HadMultipleCandidates);
3026 SourceType = Fn->getType();
3027 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3028 } else if (!UnqualifiedTargetType->isRecordType()) {
3029 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3030 return true;
3031 }
3032 }
3033 return false;
3034}
3035
3036static void TryReferenceInitializationCore(Sema &S,
3037 const InitializedEntity &Entity,
3038 const InitializationKind &Kind,
3039 Expr *Initializer,
3040 QualType cv1T1, QualType T1,
3041 Qualifiers T1Quals,
3042 QualType cv2T2, QualType T2,
3043 Qualifiers T2Quals,
3044 InitializationSequence &Sequence);
3045
3046static void TryListInitialization(Sema &S,
3047 const InitializedEntity &Entity,
3048 const InitializationKind &Kind,
3049 InitListExpr *InitList,
3050 InitializationSequence &Sequence);
3051
3052/// \brief Attempt list initialization of a reference.
3053static void TryReferenceListInitialization(Sema &S,
3054 const InitializedEntity &Entity,
3055 const InitializationKind &Kind,
3056 InitListExpr *InitList,
3057 InitializationSequence &Sequence)
3058{
3059 // First, catch C++03 where this isn't possible.
3060 if (!S.getLangOptions().CPlusPlus0x) {
3061 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3062 return;
3063 }
3064
3065 QualType DestType = Entity.getType();
3066 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3067 Qualifiers T1Quals;
3068 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3069
3070 // Reference initialization via an initializer list works thus:
3071 // If the initializer list consists of a single element that is
3072 // reference-related to the referenced type, bind directly to that element
3073 // (possibly creating temporaries).
3074 // Otherwise, initialize a temporary with the initializer list and
3075 // bind to that.
3076 if (InitList->getNumInits() == 1) {
3077 Expr *Initializer = InitList->getInit(0);
3078 QualType cv2T2 = Initializer->getType();
3079 Qualifiers T2Quals;
3080 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3081
3082 // If this fails, creating a temporary wouldn't work either.
3083 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3084 T1, Sequence))
3085 return;
3086
3087 SourceLocation DeclLoc = Initializer->getLocStart();
3088 bool dummy1, dummy2, dummy3;
3089 Sema::ReferenceCompareResult RefRelationship
3090 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3091 dummy2, dummy3);
3092 if (RefRelationship >= Sema::Ref_Related) {
3093 // Try to bind the reference here.
3094 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3095 T1Quals, cv2T2, T2, T2Quals, Sequence);
3096 if (Sequence)
3097 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3098 return;
3099 }
3100 }
3101
3102 // Not reference-related. Create a temporary and bind to that.
3103 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3104
3105 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3106 if (Sequence) {
3107 if (DestType->isRValueReferenceType() ||
3108 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3109 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3110 else
3111 Sequence.SetFailed(
3112 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3113 }
3114}
3115
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003116/// \brief Attempt list initialization (C++0x [dcl.init.list])
3117static void TryListInitialization(Sema &S,
3118 const InitializedEntity &Entity,
3119 const InitializationKind &Kind,
3120 InitListExpr *InitList,
3121 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003122 QualType DestType = Entity.getType();
3123
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003124 // C++ doesn't allow scalar initialization with more than one argument.
3125 // But C99 complex numbers are scalars and it makes sense there.
3126 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3127 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3128 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3129 return;
3130 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003131 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003132 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003133 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003134 }
3135 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003136 if (S.getLangOptions().CPlusPlus0x)
3137 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3138 InitList->getNumInits(), DestType, Sequence,
3139 /*FromInitList=*/true);
3140 else
3141 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003142 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003143 }
3144
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003145 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003146 DestType, /*VerifyOnly=*/true,
3147 Kind.getKind() != InitializationKind::IK_Direct ||
3148 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003149 if (CheckInitList.HadError()) {
3150 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3151 return;
3152 }
3153
3154 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003155 Sequence.AddListInitializationStep(DestType);
3156}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003157
3158/// \brief Try a reference initialization that involves calling a conversion
3159/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003160static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3161 const InitializedEntity &Entity,
3162 const InitializationKind &Kind,
3163 Expr *Initializer,
3164 bool AllowRValues,
3165 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003166 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003167 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3168 QualType T1 = cv1T1.getUnqualifiedType();
3169 QualType cv2T2 = Initializer->getType();
3170 QualType T2 = cv2T2.getUnqualifiedType();
3171
3172 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003173 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003174 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003176 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003177 ObjCConversion,
3178 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003179 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003180 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003181 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003182 (void)ObjCLifetimeConversion;
3183
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003184 // Build the candidate set directly in the initialization sequence
3185 // structure, so that it will persist if we fail.
3186 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3187 CandidateSet.clear();
3188
3189 // Determine whether we are allowed to call explicit constructors or
3190 // explicit conversion operators.
3191 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003193 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003194 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3195 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003196 // The type we're converting to is a class type. Enumerate its constructors
3197 // to see if there is a suitable conversion.
3198 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003199
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003200 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003201 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003202 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003203 NamedDecl *D = *Con;
3204 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3205
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003206 // Find the constructor (which may be a template).
3207 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003208 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003209 if (ConstructorTmpl)
3210 Constructor = cast<CXXConstructorDecl>(
3211 ConstructorTmpl->getTemplatedDecl());
3212 else
John McCalla0296f72010-03-19 07:35:19 +00003213 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003214
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003215 if (!Constructor->isInvalidDecl() &&
3216 Constructor->isConvertingConstructor(AllowExplicit)) {
3217 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003218 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003219 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003220 &Initializer, 1, CandidateSet,
3221 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003222 else
John McCalla0296f72010-03-19 07:35:19 +00003223 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003224 &Initializer, 1, CandidateSet,
3225 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003227 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003228 }
John McCall3696dcb2010-08-17 07:23:57 +00003229 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3230 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231
Douglas Gregor496e8b342010-05-07 19:42:26 +00003232 const RecordType *T2RecordType = 0;
3233 if ((T2RecordType = T2->getAs<RecordType>()) &&
3234 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003235 // The type we're converting from is a class type, enumerate its conversion
3236 // functions.
3237 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3238
John McCallad371252010-01-20 00:46:10 +00003239 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003240 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003241 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3242 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243 NamedDecl *D = *I;
3244 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3245 if (isa<UsingShadowDecl>(D))
3246 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003247
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003248 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3249 CXXConversionDecl *Conv;
3250 if (ConvTemplate)
3251 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3252 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003253 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003255 // If the conversion function doesn't return a reference type,
3256 // it can't be considered for this conversion unless we're allowed to
3257 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258 // FIXME: Do we need to make sure that we only consider conversion
3259 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003260 // break recursion.
3261 if ((AllowExplicit || !Conv->isExplicit()) &&
3262 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3263 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003264 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003265 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003266 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 else
John McCalla0296f72010-03-19 07:35:19 +00003268 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003269 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003270 }
3271 }
3272 }
John McCall3696dcb2010-08-17 07:23:57 +00003273 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3274 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003275
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003276 SourceLocation DeclLoc = Initializer->getLocStart();
3277
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003279 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003281 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003282 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003283
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003284 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003285
Chandler Carruth30141632011-02-25 19:41:05 +00003286 // This is the overload that will actually be used for the initialization, so
3287 // mark it as used.
3288 S.MarkDeclarationReferenced(DeclLoc, Function);
3289
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003290 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003291 if (isa<CXXConversionDecl>(Function))
3292 T2 = Function->getResultType();
3293 else
3294 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003295
3296 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003297 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003298 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003299 T2.getNonLValueExprType(S.Context),
3300 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003301
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003302 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003303 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003304 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003305 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003306 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003307 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003308 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003309
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003310 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003311 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003312 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003313 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003315 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003316 NewDerivedToBase, NewObjCConversion,
3317 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003318 if (NewRefRelationship == Sema::Ref_Incompatible) {
3319 // If the type we've converted to is not reference-related to the
3320 // type we're looking for, then there is another conversion step
3321 // we need to perform to produce a temporary of the right type
3322 // that we'll be binding to.
3323 ImplicitConversionSequence ICS;
3324 ICS.setStandard();
3325 ICS.Standard = Best->FinalConversion;
3326 T2 = ICS.Standard.getToType(2);
3327 Sequence.AddConversionSequenceStep(ICS, T2);
3328 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003329 Sequence.AddDerivedToBaseCastStep(
3330 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003332 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003333 else if (NewObjCConversion)
3334 Sequence.AddObjCObjectConversionStep(
3335 S.Context.getQualifiedType(T1,
3336 T2.getNonReferenceType().getQualifiers()));
3337
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003338 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003339 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003340
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003341 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3342 return OR_Success;
3343}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344
Richard Smithc620f552011-10-19 16:55:56 +00003345static void CheckCXX98CompatAccessibleCopy(Sema &S,
3346 const InitializedEntity &Entity,
3347 Expr *CurInitExpr);
3348
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003349/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3350static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003351 const InitializedEntity &Entity,
3352 const InitializationKind &Kind,
3353 Expr *Initializer,
3354 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003355 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003356 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003357 Qualifiers T1Quals;
3358 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003359 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003360 Qualifiers T2Quals;
3361 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003362
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003363 // If the initializer is the address of an overloaded function, try
3364 // to resolve the overloaded function. If all goes well, T2 is the
3365 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003366 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3367 T1, Sequence))
3368 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003369
Sebastian Redl29526f02011-11-27 16:50:07 +00003370 // Delegate everything else to a subfunction.
3371 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3372 T1Quals, cv2T2, T2, T2Quals, Sequence);
3373}
3374
3375/// \brief Reference initialization without resolving overloaded functions.
3376static void TryReferenceInitializationCore(Sema &S,
3377 const InitializedEntity &Entity,
3378 const InitializationKind &Kind,
3379 Expr *Initializer,
3380 QualType cv1T1, QualType T1,
3381 Qualifiers T1Quals,
3382 QualType cv2T2, QualType T2,
3383 Qualifiers T2Quals,
3384 InitializationSequence &Sequence) {
3385 QualType DestType = Entity.getType();
3386 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003387 // Compute some basic properties of the types and the initializer.
3388 bool isLValueRef = DestType->isLValueReferenceType();
3389 bool isRValueRef = !isLValueRef;
3390 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003391 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003392 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003393 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003394 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003395 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003396 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003397
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003398 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003400 // "cv2 T2" as follows:
3401 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003403 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003404 // Note the analogous bullet points for rvlaue refs to functions. Because
3405 // there are no function rvalues in C++, rvalue refs to functions are treated
3406 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003407 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003408 bool T1Function = T1->isFunctionType();
3409 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003411 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003413 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003415 // reference-compatible with "cv2 T2," or
3416 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003418 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003419 // can occur. However, we do pay attention to whether it is a bit-field
3420 // to decide whether we're actually binding to a temporary created from
3421 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003422 if (DerivedToBase)
3423 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003425 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003426 else if (ObjCConversion)
3427 Sequence.AddObjCObjectConversionStep(
3428 S.Context.getQualifiedType(T1, T2Quals));
3429
Chandler Carruth04bdce62010-01-12 20:32:25 +00003430 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003431 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003432 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003433 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003434 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003435 return;
3436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437
3438 // - has a class type (i.e., T2 is a class type), where T1 is not
3439 // reference-related to T2, and can be implicitly converted to an
3440 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3441 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003442 // applicable conversion functions (13.3.1.6) and choosing the best
3443 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003444 // If we have an rvalue ref to function type here, the rhs must be
3445 // an rvalue.
3446 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3447 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003449 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003450 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003451 Sequence);
3452 if (ConvOvlResult == OR_Success)
3453 return;
John McCall0d1da222010-01-12 00:44:57 +00003454 if (ConvOvlResult != OR_No_Viable_Function) {
3455 Sequence.SetOverloadFailure(
3456 InitializationSequence::FK_ReferenceInitOverloadFailed,
3457 ConvOvlResult);
3458 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003459 }
3460 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003461
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003462 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003463 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003464 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003465 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003466 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3467 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3468 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003469 Sequence.SetOverloadFailure(
3470 InitializationSequence::FK_ReferenceInitOverloadFailed,
3471 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003472 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003473 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003474 ? (RefRelationship == Sema::Ref_Related
3475 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3476 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3477 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003478
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003479 return;
3480 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003481
Douglas Gregor92e460e2011-01-20 16:44:54 +00003482 // - If the initializer expression
3483 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3484 // "cv1 T1" is reference-compatible with "cv2 T2"
3485 // Note: functions are handled below.
3486 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003487 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003489 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003490 (InitCategory.isXValue() ||
3491 (InitCategory.isPRValue() && T2->isRecordType()) ||
3492 (InitCategory.isPRValue() && T2->isArrayType()))) {
3493 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3494 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003495 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3496 // compiler the freedom to perform a copy here or bind to the
3497 // object, while C++0x requires that we bind directly to the
3498 // object. Hence, we always bind to the object without making an
3499 // extra copy. However, in C++03 requires that we check for the
3500 // presence of a suitable copy constructor:
3501 //
3502 // The constructor that would be used to make the copy shall
3503 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003504 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003505 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003506 else if (S.getLangOptions().CPlusPlus0x)
3507 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509
Douglas Gregor92e460e2011-01-20 16:44:54 +00003510 if (DerivedToBase)
3511 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3512 ValueKind);
3513 else if (ObjCConversion)
3514 Sequence.AddObjCObjectConversionStep(
3515 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516
Douglas Gregor92e460e2011-01-20 16:44:54 +00003517 if (T1Quals != T2Quals)
3518 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003520 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523
3524 // - has a class type (i.e., T2 is a class type), where T1 is not
3525 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003526 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3527 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003528 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003529 if (RefRelationship == Sema::Ref_Incompatible) {
3530 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3531 Kind, Initializer,
3532 /*AllowRValues=*/true,
3533 Sequence);
3534 if (ConvOvlResult)
3535 Sequence.SetOverloadFailure(
3536 InitializationSequence::FK_ReferenceInitOverloadFailed,
3537 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003539 return;
3540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003542 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3543 return;
3544 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003545
3546 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003547 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003549 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003550
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003551 // Determine whether we are allowed to call explicit constructors or
3552 // explicit conversion operators.
3553 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003554
3555 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3556
John McCall31168b02011-06-15 23:02:42 +00003557 ImplicitConversionSequence ICS
3558 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003559 /*SuppressUserConversions*/ false,
3560 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003561 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003562 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3563 /*AllowObjCWritebackConversion=*/false);
3564
3565 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003566 // FIXME: Use the conversion function set stored in ICS to turn
3567 // this into an overloading ambiguity diagnostic. However, we need
3568 // to keep that set as an OverloadCandidateSet rather than as some
3569 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003570 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3571 Sequence.SetOverloadFailure(
3572 InitializationSequence::FK_ReferenceInitOverloadFailed,
3573 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003574 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3575 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003576 else
3577 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003578 return;
John McCall31168b02011-06-15 23:02:42 +00003579 } else {
3580 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003581 }
3582
3583 // [...] If T1 is reference-related to T2, cv1 must be the
3584 // same cv-qualification as, or greater cv-qualification
3585 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003586 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3587 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003588 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003589 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003590 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3591 return;
3592 }
3593
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003595 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003597 InitCategory.isLValue()) {
3598 Sequence.SetFailed(
3599 InitializationSequence::FK_RValueReferenceBindingToLValue);
3600 return;
3601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003603 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3604 return;
3605}
3606
3607/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608/// (C++ [dcl.init.string], C99 6.7.8).
3609static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003610 const InitializedEntity &Entity,
3611 const InitializationKind &Kind,
3612 Expr *Initializer,
3613 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003614 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003615}
3616
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003617/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003619 const InitializedEntity &Entity,
3620 const InitializationKind &Kind,
3621 InitializationSequence &Sequence) {
3622 // C++ [dcl.init]p5:
3623 //
3624 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003625 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003627 // -- if T is an array type, then each element is value-initialized;
3628 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3629 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003631 if (const RecordType *RT = T->getAs<RecordType>()) {
3632 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3633 // -- if T is a class type (clause 9) with a user-declared
3634 // constructor (12.1), then the default constructor for T is
3635 // called (and the initialization is ill-formed if T has no
3636 // accessible default constructor);
3637 //
3638 // FIXME: we really want to refer to a single subobject of the array,
3639 // but Entity doesn't have a way to capture that (yet).
3640 if (ClassDecl->hasUserDeclaredConstructor())
3641 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003642
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003643 // -- if T is a (possibly cv-qualified) non-union class type
3644 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003645 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003646 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003647 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003648 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003649 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003650 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003651 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003652 }
3653 }
3654
Douglas Gregor1b303932009-12-22 15:35:07 +00003655 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003656}
3657
Douglas Gregor85dabae2009-12-16 01:38:02 +00003658/// \brief Attempt default initialization (C++ [dcl.init]p6).
3659static void TryDefaultInitialization(Sema &S,
3660 const InitializedEntity &Entity,
3661 const InitializationKind &Kind,
3662 InitializationSequence &Sequence) {
3663 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Douglas Gregor85dabae2009-12-16 01:38:02 +00003665 // C++ [dcl.init]p6:
3666 // To default-initialize an object of type T means:
3667 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003668 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3669
Douglas Gregor85dabae2009-12-16 01:38:02 +00003670 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3671 // constructor for T is called (and the initialization is ill-formed if
3672 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003673 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003674 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3675 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003676 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677
Douglas Gregor85dabae2009-12-16 01:38:02 +00003678 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679
Douglas Gregor85dabae2009-12-16 01:38:02 +00003680 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003682 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003683 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003684 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003685 return;
3686 }
3687
3688 // If the destination type has a lifetime property, zero-initialize it.
3689 if (DestType.getQualifiers().hasObjCLifetime()) {
3690 Sequence.AddZeroInitializationStep(Entity.getType());
3691 return;
3692 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003693}
3694
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003695/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3696/// which enumerates all conversion functions and performs overload resolution
3697/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003699 const InitializedEntity &Entity,
3700 const InitializationKind &Kind,
3701 Expr *Initializer,
3702 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003703 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003704 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3705 QualType SourceType = Initializer->getType();
3706 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3707 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708
Douglas Gregor540c3b02009-12-14 17:27:33 +00003709 // Build the candidate set directly in the initialization sequence
3710 // structure, so that it will persist if we fail.
3711 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3712 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713
Douglas Gregor540c3b02009-12-14 17:27:33 +00003714 // Determine whether we are allowed to call explicit constructors or
3715 // explicit conversion operators.
3716 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717
Douglas Gregor540c3b02009-12-14 17:27:33 +00003718 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3719 // The type we're converting to is a class type. Enumerate its constructors
3720 // to see if there is a suitable conversion.
3721 CXXRecordDecl *DestRecordDecl
3722 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723
Douglas Gregord9848152010-04-26 14:36:57 +00003724 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003726 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003727 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003728 Con != ConEnd; ++Con) {
3729 NamedDecl *D = *Con;
3730 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003731
Douglas Gregord9848152010-04-26 14:36:57 +00003732 // Find the constructor (which may be a template).
3733 CXXConstructorDecl *Constructor = 0;
3734 FunctionTemplateDecl *ConstructorTmpl
3735 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003736 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003737 Constructor = cast<CXXConstructorDecl>(
3738 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003739 else
Douglas Gregord9848152010-04-26 14:36:57 +00003740 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741
Douglas Gregord9848152010-04-26 14:36:57 +00003742 if (!Constructor->isInvalidDecl() &&
3743 Constructor->isConvertingConstructor(AllowExplicit)) {
3744 if (ConstructorTmpl)
3745 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3746 /*ExplicitArgs*/ 0,
3747 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003748 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003749 else
3750 S.AddOverloadCandidate(Constructor, FoundDecl,
3751 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003752 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754 }
Douglas Gregord9848152010-04-26 14:36:57 +00003755 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003756 }
Eli Friedman78275202009-12-19 08:11:05 +00003757
3758 SourceLocation DeclLoc = Initializer->getLocStart();
3759
Douglas Gregor540c3b02009-12-14 17:27:33 +00003760 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3761 // The type we're converting from is a class type, enumerate its conversion
3762 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003763
Eli Friedman4afe9a32009-12-20 22:12:03 +00003764 // We can only enumerate the conversion functions for a complete type; if
3765 // the type isn't complete, simply skip this step.
3766 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3767 CXXRecordDecl *SourceRecordDecl
3768 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769
John McCallad371252010-01-20 00:46:10 +00003770 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003771 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003772 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003774 I != E; ++I) {
3775 NamedDecl *D = *I;
3776 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3777 if (isa<UsingShadowDecl>(D))
3778 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779
Eli Friedman4afe9a32009-12-20 22:12:03 +00003780 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3781 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003782 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003783 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003784 else
John McCallda4458e2010-03-31 01:36:47 +00003785 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786
Eli Friedman4afe9a32009-12-20 22:12:03 +00003787 if (AllowExplicit || !Conv->isExplicit()) {
3788 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003789 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003790 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003791 CandidateSet);
3792 else
John McCalla0296f72010-03-19 07:35:19 +00003793 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003794 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003795 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003796 }
3797 }
3798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003799
3800 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003801 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003802 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003803 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003804 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003806 Result);
3807 return;
3808 }
John McCall0d1da222010-01-12 00:44:57 +00003809
Douglas Gregor540c3b02009-12-14 17:27:33 +00003810 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003811 S.MarkDeclarationReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003812 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813
Douglas Gregor540c3b02009-12-14 17:27:33 +00003814 if (isa<CXXConstructorDecl>(Function)) {
3815 // Add the user-defined conversion step. Any cv-qualification conversion is
3816 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003817 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3818 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003819 return;
3820 }
3821
3822 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003823 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003824 if (ConvType->getAs<RecordType>()) {
3825 // If we're converting to a class type, there may be an copy if
3826 // the resulting temporary object (possible to create an object of
3827 // a base class type). That copy is not a separate conversion, so
3828 // we just make a note of the actual destination type (possibly a
3829 // base class of the type returned by the conversion function) and
3830 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003831 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3832 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003833 return;
3834 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003835
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003836 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3837 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003838
Douglas Gregor5ab11652010-04-17 22:01:05 +00003839 // If the conversion following the call to the conversion function
3840 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003841 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3842 Best->FinalConversion.Third) {
3843 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003844 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003845 ICS.Standard = Best->FinalConversion;
3846 Sequence.AddConversionSequenceStep(ICS, DestType);
3847 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003848}
3849
John McCall31168b02011-06-15 23:02:42 +00003850/// The non-zero enum values here are indexes into diagnostic alternatives.
3851enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3852
3853/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003854static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3855 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003856 // Skip parens.
3857 e = e->IgnoreParens();
3858
3859 // Skip address-of nodes.
3860 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3861 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003862 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003863
3864 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003865 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3866 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003867 case CK_Dependent:
3868 case CK_BitCast:
3869 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003870 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003871 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003872
3873 case CK_ArrayToPointerDecay:
3874 return IIK_nonscalar;
3875
3876 case CK_NullToPointer:
3877 return IIK_okay;
3878
3879 default:
3880 break;
3881 }
3882
3883 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003884 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3885 if (!isAddressOf) return IIK_nonlocal;
3886
3887 VarDecl *var;
3888 if (isa<DeclRefExpr>(e)) {
3889 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3890 if (!var) return IIK_nonlocal;
3891 } else {
3892 var = cast<BlockDeclRefExpr>(e)->getDecl();
3893 }
3894
3895 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003896
3897 // If we have a conditional operator, check both sides.
3898 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003899 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003900 return iik;
3901
John McCall63f84442011-06-27 23:59:58 +00003902 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003903
3904 // These are never scalar.
3905 } else if (isa<ArraySubscriptExpr>(e)) {
3906 return IIK_nonscalar;
3907
3908 // Otherwise, it needs to be a null pointer constant.
3909 } else {
3910 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3911 ? IIK_okay : IIK_nonlocal);
3912 }
3913
3914 return IIK_nonlocal;
3915}
3916
3917/// Check whether the given expression is a valid operand for an
3918/// indirect copy/restore.
3919static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3920 assert(src->isRValue());
3921
John McCall63f84442011-06-27 23:59:58 +00003922 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003923 if (iik == IIK_okay) return;
3924
3925 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3926 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3927 << src->getSourceRange();
3928}
3929
Douglas Gregore2f943b2011-02-22 18:29:51 +00003930/// \brief Determine whether we have compatible array types for the
3931/// purposes of GNU by-copy array initialization.
3932static bool hasCompatibleArrayTypes(ASTContext &Context,
3933 const ArrayType *Dest,
3934 const ArrayType *Source) {
3935 // If the source and destination array types are equivalent, we're
3936 // done.
3937 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3938 return true;
3939
3940 // Make sure that the element types are the same.
3941 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3942 return false;
3943
3944 // The only mismatch we allow is when the destination is an
3945 // incomplete array type and the source is a constant array type.
3946 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3947}
3948
John McCall31168b02011-06-15 23:02:42 +00003949static bool tryObjCWritebackConversion(Sema &S,
3950 InitializationSequence &Sequence,
3951 const InitializedEntity &Entity,
3952 Expr *Initializer) {
3953 bool ArrayDecay = false;
3954 QualType ArgType = Initializer->getType();
3955 QualType ArgPointee;
3956 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3957 ArrayDecay = true;
3958 ArgPointee = ArgArrayType->getElementType();
3959 ArgType = S.Context.getPointerType(ArgPointee);
3960 }
3961
3962 // Handle write-back conversion.
3963 QualType ConvertedArgType;
3964 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3965 ConvertedArgType))
3966 return false;
3967
3968 // We should copy unless we're passing to an argument explicitly
3969 // marked 'out'.
3970 bool ShouldCopy = true;
3971 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3972 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3973
3974 // Do we need an lvalue conversion?
3975 if (ArrayDecay || Initializer->isGLValue()) {
3976 ImplicitConversionSequence ICS;
3977 ICS.setStandard();
3978 ICS.Standard.setAsIdentityConversion();
3979
3980 QualType ResultType;
3981 if (ArrayDecay) {
3982 ICS.Standard.First = ICK_Array_To_Pointer;
3983 ResultType = S.Context.getPointerType(ArgPointee);
3984 } else {
3985 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3986 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3987 }
3988
3989 Sequence.AddConversionSequenceStep(ICS, ResultType);
3990 }
3991
3992 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3993 return true;
3994}
3995
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003996InitializationSequence::InitializationSequence(Sema &S,
3997 const InitializedEntity &Entity,
3998 const InitializationKind &Kind,
3999 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00004000 unsigned NumArgs)
4001 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004002 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004004 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004005 // The semantics of initializers are as follows. The destination type is
4006 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004007 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004009 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004010 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004011
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004012 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004013 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
4014 SequenceKind = DependentSequence;
4015 return;
4016 }
4017
Sebastian Redld201edf2011-06-05 13:59:11 +00004018 // Almost everything is a normal sequence.
4019 setSequenceKind(NormalSequence);
4020
John McCalled75c092010-12-07 22:54:16 +00004021 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00004022 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00004023 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00004024 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4025 if (result.isInvalid()) {
4026 SetFailed(FK_PlaceholderType);
4027 return;
John McCall4124c492011-10-17 18:40:02 +00004028 }
John McCalld5c98ae2011-11-15 01:35:18 +00004029 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00004030 }
John McCalled75c092010-12-07 22:54:16 +00004031
John McCall4124c492011-10-17 18:40:02 +00004032
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004033 QualType SourceType;
4034 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004035 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004036 Initializer = Args[0];
4037 if (!isa<InitListExpr>(Initializer))
4038 SourceType = Initializer->getType();
4039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040
4041 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004042 // list-initialized (8.5.4).
4043 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004044 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004045 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004048 // - If the destination type is a reference type, see 8.5.3.
4049 if (DestType->isReferenceType()) {
4050 // C++0x [dcl.init.ref]p1:
4051 // A variable declared to be a T& or T&&, that is, "reference to type T"
4052 // (8.3.2), shall be initialized by an object, or function, of type T or
4053 // by an object that can be converted into a T.
4054 // (Therefore, multiple arguments are not permitted.)
4055 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004056 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004057 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004058 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004059 return;
4060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004061
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004062 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004063 if (Kind.getKind() == InitializationKind::IK_Value ||
4064 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004065 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004066 return;
4067 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004068
Douglas Gregor85dabae2009-12-16 01:38:02 +00004069 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004070 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004071 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004072 return;
4073 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004074
John McCall66884dd2011-02-21 07:22:22 +00004075 // - If the destination type is an array of characters, an array of
4076 // char16_t, an array of char32_t, or an array of wchar_t, and the
4077 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004078 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004079 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004080 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004081 if (Initializer && isa<VariableArrayType>(DestAT)) {
4082 SetFailed(FK_VariableLengthArrayHasInitializer);
4083 return;
4084 }
4085
Douglas Gregore2f943b2011-02-22 18:29:51 +00004086 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004087 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00004088 return;
4089 }
4090
Douglas Gregore2f943b2011-02-22 18:29:51 +00004091 // Note: as an GNU C extension, we allow initialization of an
4092 // array from a compound literal that creates an array of the same
4093 // type, so long as the initializer has no side effects.
4094 if (!S.getLangOptions().CPlusPlus && Initializer &&
4095 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4096 Initializer->getType()->isArrayType()) {
4097 const ArrayType *SourceAT
4098 = Context.getAsArrayType(Initializer->getType());
4099 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004100 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004101 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004102 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004103 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004104 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004105 }
4106 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004107 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004108 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004109 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004110
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004111 return;
4112 }
Eli Friedman78275202009-12-19 08:11:05 +00004113
John McCall31168b02011-06-15 23:02:42 +00004114 // Determine whether we should consider writeback conversions for
4115 // Objective-C ARC.
4116 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4117 Entity.getKind() == InitializedEntity::EK_Parameter;
4118
4119 // We're at the end of the line for C: it's either a write-back conversion
4120 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004121 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004122 // If allowed, check whether this is an Objective-C writeback conversion.
4123 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004124 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004125 return;
4126 }
4127
4128 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004129 AddCAssignmentStep(DestType);
4130 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004131 return;
4132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133
John McCall31168b02011-06-15 23:02:42 +00004134 assert(S.getLangOptions().CPlusPlus);
4135
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004136 // - If the destination type is a (possibly cv-qualified) class type:
4137 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138 // - If the initialization is direct-initialization, or if it is
4139 // copy-initialization where the cv-unqualified version of the
4140 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004141 // class of the destination, constructors are considered. [...]
4142 if (Kind.getKind() == InitializationKind::IK_Direct ||
4143 (Kind.getKind() == InitializationKind::IK_Copy &&
4144 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4145 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004147 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004149 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004151 // used) to a derived class thereof are enumerated as described in
4152 // 13.3.1.4, and the best one is chosen through overload resolution
4153 // (13.3).
4154 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004155 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004156 return;
4157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
Douglas Gregor85dabae2009-12-16 01:38:02 +00004159 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004160 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004161 return;
4162 }
4163 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004164
4165 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004166 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004167 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004168 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4169 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004170 return;
4171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004173 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004174 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004175 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004177 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004178
4179 ImplicitConversionSequence ICS
4180 = S.TryImplicitConversion(Initializer, Entity.getType(),
4181 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004182 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004183 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004184 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4185 allowObjCWritebackConversion);
4186
4187 if (ICS.isStandard() &&
4188 ICS.Standard.Second == ICK_Writeback_Conversion) {
4189 // Objective-C ARC writeback conversion.
4190
4191 // We should copy unless we're passing to an argument explicitly
4192 // marked 'out'.
4193 bool ShouldCopy = true;
4194 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4195 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4196
4197 // If there was an lvalue adjustment, add it as a separate conversion.
4198 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4199 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4200 ImplicitConversionSequence LvalueICS;
4201 LvalueICS.setStandard();
4202 LvalueICS.Standard.setAsIdentityConversion();
4203 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4204 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004205 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004206 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004207
4208 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004209 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004210 DeclAccessPair dap;
4211 if (Initializer->getType() == Context.OverloadTy &&
4212 !S.ResolveAddressOfOverloadedFunction(Initializer
4213 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004214 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004215 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004216 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004217 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004218 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004219
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004220 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004221 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004222}
4223
4224InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004225 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004226 StepEnd = Steps.end();
4227 Step != StepEnd; ++Step)
4228 Step->Destroy();
4229}
4230
4231//===----------------------------------------------------------------------===//
4232// Perform initialization
4233//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004235getAssignmentAction(const InitializedEntity &Entity) {
4236 switch(Entity.getKind()) {
4237 case InitializedEntity::EK_Variable:
4238 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004239 case InitializedEntity::EK_Exception:
4240 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004241 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004242 return Sema::AA_Initializing;
4243
4244 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004246 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4247 return Sema::AA_Sending;
4248
Douglas Gregore1314a62009-12-18 05:02:21 +00004249 return Sema::AA_Passing;
4250
4251 case InitializedEntity::EK_Result:
4252 return Sema::AA_Returning;
4253
Douglas Gregore1314a62009-12-18 05:02:21 +00004254 case InitializedEntity::EK_Temporary:
4255 // FIXME: Can we tell apart casting vs. converting?
4256 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
Douglas Gregore1314a62009-12-18 05:02:21 +00004258 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004259 case InitializedEntity::EK_ArrayElement:
4260 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004261 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004262 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004263 return Sema::AA_Initializing;
4264 }
4265
4266 return Sema::AA_Converting;
4267}
4268
Douglas Gregor95562572010-04-24 23:45:46 +00004269/// \brief Whether we should binding a created object as a temporary when
4270/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004271static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004272 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004273 case InitializedEntity::EK_ArrayElement:
4274 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004275 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004276 case InitializedEntity::EK_New:
4277 case InitializedEntity::EK_Variable:
4278 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004279 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004280 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004281 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004282 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004283 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004284 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285
Douglas Gregore1314a62009-12-18 05:02:21 +00004286 case InitializedEntity::EK_Parameter:
4287 case InitializedEntity::EK_Temporary:
4288 return true;
4289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
Douglas Gregore1314a62009-12-18 05:02:21 +00004291 llvm_unreachable("missed an InitializedEntity kind?");
4292}
4293
Douglas Gregor95562572010-04-24 23:45:46 +00004294/// \brief Whether the given entity, when initialized with an object
4295/// created for that initialization, requires destruction.
4296static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4297 switch (Entity.getKind()) {
4298 case InitializedEntity::EK_Member:
4299 case InitializedEntity::EK_Result:
4300 case InitializedEntity::EK_New:
4301 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004302 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004303 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004304 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004305 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004306 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregor95562572010-04-24 23:45:46 +00004308 case InitializedEntity::EK_Variable:
4309 case InitializedEntity::EK_Parameter:
4310 case InitializedEntity::EK_Temporary:
4311 case InitializedEntity::EK_ArrayElement:
4312 case InitializedEntity::EK_Exception:
4313 return true;
4314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315
4316 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004317}
4318
Richard Smithc620f552011-10-19 16:55:56 +00004319/// \brief Look for copy and move constructors and constructor templates, for
4320/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4321static void LookupCopyAndMoveConstructors(Sema &S,
4322 OverloadCandidateSet &CandidateSet,
4323 CXXRecordDecl *Class,
4324 Expr *CurInitExpr) {
4325 DeclContext::lookup_iterator Con, ConEnd;
4326 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4327 Con != ConEnd; ++Con) {
4328 CXXConstructorDecl *Constructor = 0;
4329
4330 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4331 // Handle copy/moveconstructors, only.
4332 if (!Constructor || Constructor->isInvalidDecl() ||
4333 !Constructor->isCopyOrMoveConstructor() ||
4334 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4335 continue;
4336
4337 DeclAccessPair FoundDecl
4338 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4339 S.AddOverloadCandidate(Constructor, FoundDecl,
4340 &CurInitExpr, 1, CandidateSet);
4341 continue;
4342 }
4343
4344 // Handle constructor templates.
4345 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4346 if (ConstructorTmpl->isInvalidDecl())
4347 continue;
4348
4349 Constructor = cast<CXXConstructorDecl>(
4350 ConstructorTmpl->getTemplatedDecl());
4351 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4352 continue;
4353
4354 // FIXME: Do we need to limit this to copy-constructor-like
4355 // candidates?
4356 DeclAccessPair FoundDecl
4357 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4358 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4359 &CurInitExpr, 1, CandidateSet, true);
4360 }
4361}
4362
4363/// \brief Get the location at which initialization diagnostics should appear.
4364static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4365 Expr *Initializer) {
4366 switch (Entity.getKind()) {
4367 case InitializedEntity::EK_Result:
4368 return Entity.getReturnLoc();
4369
4370 case InitializedEntity::EK_Exception:
4371 return Entity.getThrowLoc();
4372
4373 case InitializedEntity::EK_Variable:
4374 return Entity.getDecl()->getLocation();
4375
4376 case InitializedEntity::EK_ArrayElement:
4377 case InitializedEntity::EK_Member:
4378 case InitializedEntity::EK_Parameter:
4379 case InitializedEntity::EK_Temporary:
4380 case InitializedEntity::EK_New:
4381 case InitializedEntity::EK_Base:
4382 case InitializedEntity::EK_Delegating:
4383 case InitializedEntity::EK_VectorElement:
4384 case InitializedEntity::EK_ComplexElement:
4385 case InitializedEntity::EK_BlockElement:
4386 return Initializer->getLocStart();
4387 }
4388 llvm_unreachable("missed an InitializedEntity kind?");
4389}
4390
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004391/// \brief Make a (potentially elidable) temporary copy of the object
4392/// provided by the given initializer by calling the appropriate copy
4393/// constructor.
4394///
4395/// \param S The Sema object used for type-checking.
4396///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004397/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004398/// the type of the initializer expression or a superclass thereof.
4399///
4400/// \param Enter The entity being initialized.
4401///
4402/// \param CurInit The initializer expression.
4403///
4404/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4405/// is permitted in C++03 (but not C++0x) when binding a reference to
4406/// an rvalue.
4407///
4408/// \returns An expression that copies the initializer expression into
4409/// a temporary object, or an error expression if a copy could not be
4410/// created.
John McCalldadc5752010-08-24 06:29:42 +00004411static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004412 QualType T,
4413 const InitializedEntity &Entity,
4414 ExprResult CurInit,
4415 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004416 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004417 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004419 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004420 Class = cast<CXXRecordDecl>(Record->getDecl());
4421 if (!Class)
4422 return move(CurInit);
4423
Douglas Gregor5d369002011-01-21 18:05:27 +00004424 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004425 // When certain criteria are met, an implementation is allowed to
4426 // omit the copy/move construction of a class object, even if the
4427 // copy/move constructor and/or destructor for the object have
4428 // side effects. [...]
4429 // - when a temporary class object that has not been bound to a
4430 // reference (12.2) would be copied/moved to a class object
4431 // with the same cv-unqualified type, the copy/move operation
4432 // can be omitted by constructing the temporary object
4433 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004435 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004436 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004438 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004439 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004440 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004441
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004443 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4444 return move(CurInit);
4445
Douglas Gregorf282a762011-01-21 19:38:21 +00004446 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004447 // Only consider constructors and constructor templates. Per
4448 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4449 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004450 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004451 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004453 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4454
Douglas Gregore1314a62009-12-18 05:02:21 +00004455 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004456 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004457 case OR_Success:
4458 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459
Douglas Gregore1314a62009-12-18 05:02:21 +00004460 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004461 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4462 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4463 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004464 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004465 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004466 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004467 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004468 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004469 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470
Douglas Gregore1314a62009-12-18 05:02:21 +00004471 case OR_Ambiguous:
4472 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004473 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004474 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004475 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004476 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477
Douglas Gregore1314a62009-12-18 05:02:21 +00004478 case OR_Deleted:
4479 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004480 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004481 << CurInitExpr->getSourceRange();
4482 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004483 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004484 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004485 }
4486
Douglas Gregor5ab11652010-04-17 22:01:05 +00004487 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004488 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004489 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004490
Anders Carlssona01874b2010-04-21 18:47:17 +00004491 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004492 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004493
4494 if (IsExtraneousCopy) {
4495 // If this is a totally extraneous copy for C++03 reference
4496 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004497 // expression. We don't generate an (elided) copy operation here
4498 // because doing so would require us to pass down a flag to avoid
4499 // infinite recursion, where each step adds another extraneous,
4500 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004501
Douglas Gregor30b52772010-04-18 07:57:34 +00004502 // Instantiate the default arguments of any extra parameters in
4503 // the selected copy constructor, as if we were going to create a
4504 // proper call to the copy constructor.
4505 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4506 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4507 if (S.RequireCompleteType(Loc, Parm->getType(),
4508 S.PDiag(diag::err_call_incomplete_argument)))
4509 break;
4510
4511 // Build the default argument expression; we don't actually care
4512 // if this succeeds or not, because this routine will complain
4513 // if there was a problem.
4514 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4515 }
4516
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004517 return S.Owned(CurInitExpr);
4518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519
Chandler Carruth30141632011-02-25 19:41:05 +00004520 S.MarkDeclarationReferenced(Loc, Constructor);
4521
Douglas Gregor5ab11652010-04-17 22:01:05 +00004522 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004523 // constructor call (we might have derived-to-base conversions, or
4524 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004525 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004526 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004527 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004528
Douglas Gregord0ace022010-04-25 00:55:24 +00004529 // Actually perform the constructor call.
4530 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004531 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004532 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004533 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004534 CXXConstructExpr::CK_Complete,
4535 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004536
Douglas Gregord0ace022010-04-25 00:55:24 +00004537 // If we're supposed to bind temporaries, do so.
4538 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4539 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4540 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004541}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004542
Richard Smithc620f552011-10-19 16:55:56 +00004543/// \brief Check whether elidable copy construction for binding a reference to
4544/// a temporary would have succeeded if we were building in C++98 mode, for
4545/// -Wc++98-compat.
4546static void CheckCXX98CompatAccessibleCopy(Sema &S,
4547 const InitializedEntity &Entity,
4548 Expr *CurInitExpr) {
4549 assert(S.getLangOptions().CPlusPlus0x);
4550
4551 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4552 if (!Record)
4553 return;
4554
4555 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4556 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4557 == DiagnosticsEngine::Ignored)
4558 return;
4559
4560 // Find constructors which would have been considered.
4561 OverloadCandidateSet CandidateSet(Loc);
4562 LookupCopyAndMoveConstructors(
4563 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4564
4565 // Perform overload resolution.
4566 OverloadCandidateSet::iterator Best;
4567 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4568
4569 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4570 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4571 << CurInitExpr->getSourceRange();
4572
4573 switch (OR) {
4574 case OR_Success:
4575 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4576 Best->FoundDecl.getAccess(), Diag);
4577 // FIXME: Check default arguments as far as that's possible.
4578 break;
4579
4580 case OR_No_Viable_Function:
4581 S.Diag(Loc, Diag);
4582 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4583 break;
4584
4585 case OR_Ambiguous:
4586 S.Diag(Loc, Diag);
4587 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4588 break;
4589
4590 case OR_Deleted:
4591 S.Diag(Loc, Diag);
4592 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4593 << 1 << Best->Function->isDeleted();
4594 break;
4595 }
4596}
4597
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004598void InitializationSequence::PrintInitLocationNote(Sema &S,
4599 const InitializedEntity &Entity) {
4600 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4601 if (Entity.getDecl()->getLocation().isInvalid())
4602 return;
4603
4604 if (Entity.getDecl()->getDeclName())
4605 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4606 << Entity.getDecl()->getDeclName();
4607 else
4608 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4609 }
4610}
4611
Sebastian Redl112aa822011-07-14 19:07:55 +00004612static bool isReferenceBinding(const InitializationSequence::Step &s) {
4613 return s.Kind == InitializationSequence::SK_BindReference ||
4614 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4615}
4616
Sebastian Redled2e5322011-12-22 14:44:04 +00004617static ExprResult
4618PerformConstructorInitialization(Sema &S,
4619 const InitializedEntity &Entity,
4620 const InitializationKind &Kind,
4621 MultiExprArg Args,
4622 const InitializationSequence::Step& Step,
4623 bool &ConstructorInitRequiresZeroInit) {
4624 unsigned NumArgs = Args.size();
4625 CXXConstructorDecl *Constructor
4626 = cast<CXXConstructorDecl>(Step.Function.Function);
4627 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4628
4629 // Build a call to the selected constructor.
4630 ASTOwningVector<Expr*> ConstructorArgs(S);
4631 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4632 ? Kind.getEqualLoc()
4633 : Kind.getLocation();
4634
4635 if (Kind.getKind() == InitializationKind::IK_Default) {
4636 // Force even a trivial, implicit default constructor to be
4637 // semantically checked. We do this explicitly because we don't build
4638 // the definition for completely trivial constructors.
4639 CXXRecordDecl *ClassDecl = Constructor->getParent();
4640 assert(ClassDecl && "No parent class for constructor.");
4641 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4642 ClassDecl->hasTrivialDefaultConstructor() &&
4643 !Constructor->isUsed(false))
4644 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4645 }
4646
4647 ExprResult CurInit = S.Owned((Expr *)0);
4648
4649 // Determine the arguments required to actually perform the constructor
4650 // call.
4651 if (S.CompleteConstructorCall(Constructor, move(Args),
4652 Loc, ConstructorArgs))
4653 return ExprError();
4654
4655
4656 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4657 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4658 (Kind.getKind() == InitializationKind::IK_Direct ||
4659 Kind.getKind() == InitializationKind::IK_Value)) {
4660 // An explicitly-constructed temporary, e.g., X(1, 2).
4661 unsigned NumExprs = ConstructorArgs.size();
4662 Expr **Exprs = (Expr **)ConstructorArgs.take();
4663 S.MarkDeclarationReferenced(Loc, Constructor);
4664 S.DiagnoseUseOfDecl(Constructor, Loc);
4665
4666 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4667 if (!TSInfo)
4668 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4669
4670 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4671 Constructor,
4672 TSInfo,
4673 Exprs,
4674 NumExprs,
4675 Kind.getParenRange(),
4676 HadMultipleCandidates,
4677 ConstructorInitRequiresZeroInit));
4678 } else {
4679 CXXConstructExpr::ConstructionKind ConstructKind =
4680 CXXConstructExpr::CK_Complete;
4681
4682 if (Entity.getKind() == InitializedEntity::EK_Base) {
4683 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4684 CXXConstructExpr::CK_VirtualBase :
4685 CXXConstructExpr::CK_NonVirtualBase;
4686 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4687 ConstructKind = CXXConstructExpr::CK_Delegating;
4688 }
4689
4690 // Only get the parenthesis range if it is a direct construction.
4691 SourceRange parenRange =
4692 Kind.getKind() == InitializationKind::IK_Direct ?
4693 Kind.getParenRange() : SourceRange();
4694
4695 // If the entity allows NRVO, mark the construction as elidable
4696 // unconditionally.
4697 if (Entity.allowsNRVO())
4698 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4699 Constructor, /*Elidable=*/true,
4700 move_arg(ConstructorArgs),
4701 HadMultipleCandidates,
4702 ConstructorInitRequiresZeroInit,
4703 ConstructKind,
4704 parenRange);
4705 else
4706 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4707 Constructor,
4708 move_arg(ConstructorArgs),
4709 HadMultipleCandidates,
4710 ConstructorInitRequiresZeroInit,
4711 ConstructKind,
4712 parenRange);
4713 }
4714 if (CurInit.isInvalid())
4715 return ExprError();
4716
4717 // Only check access if all of that succeeded.
4718 S.CheckConstructorAccess(Loc, Constructor, Entity,
4719 Step.Function.FoundDecl.getAccess());
4720 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4721
4722 if (shouldBindAsTemporary(Entity))
4723 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4724
4725 return move(CurInit);
4726}
4727
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004728ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004729InitializationSequence::Perform(Sema &S,
4730 const InitializedEntity &Entity,
4731 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004732 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004733 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004734 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004735 unsigned NumArgs = Args.size();
4736 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004737 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739
Sebastian Redld201edf2011-06-05 13:59:11 +00004740 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004741 // If the declaration is a non-dependent, incomplete array type
4742 // that has an initializer, then its type will be completed once
4743 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004744 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004745 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004746 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004747 if (const IncompleteArrayType *ArrayT
4748 = S.Context.getAsIncompleteArrayType(DeclType)) {
4749 // FIXME: We don't currently have the ability to accurately
4750 // compute the length of an initializer list without
4751 // performing full type-checking of the initializer list
4752 // (since we have to determine where braces are implicitly
4753 // introduced and such). So, we fall back to making the array
4754 // type a dependently-sized array type with no specified
4755 // bound.
4756 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4757 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004758
Douglas Gregor51e77d52009-12-10 17:56:55 +00004759 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004760 if (DeclaratorDecl *DD = Entity.getDecl()) {
4761 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4762 TypeLoc TL = TInfo->getTypeLoc();
4763 if (IncompleteArrayTypeLoc *ArrayLoc
4764 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4765 Brackets = ArrayLoc->getBracketsRange();
4766 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004767 }
4768
4769 *ResultType
4770 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4771 /*NumElts=*/0,
4772 ArrayT->getSizeModifier(),
4773 ArrayT->getIndexTypeCVRQualifiers(),
4774 Brackets);
4775 }
4776
4777 }
4778 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004779 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4780 Kind.isExplicitCast());
4781 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004782 }
4783
Sebastian Redld201edf2011-06-05 13:59:11 +00004784 // No steps means no initialization.
4785 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004786 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787
Douglas Gregor1b303932009-12-22 15:35:07 +00004788 QualType DestType = Entity.getType().getNonReferenceType();
4789 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004790 // the same as Entity.getDecl()->getType() in cases involving type merging,
4791 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004792 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004793 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004794 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004795
John McCalldadc5752010-08-24 06:29:42 +00004796 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004799 // grab the only argument out the Args and place it into the "current"
4800 // initializer.
4801 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004802 case SK_ResolveAddressOfOverloadedFunction:
4803 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004804 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004805 case SK_CastDerivedToBaseLValue:
4806 case SK_BindReference:
4807 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004808 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004809 case SK_UserConversion:
4810 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004811 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004812 case SK_QualificationConversionRValue:
4813 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004814 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004815 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004816 case SK_UnwrapInitList:
4817 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004818 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004819 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004820 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004821 case SK_ArrayInit:
4822 case SK_PassByIndirectCopyRestore:
4823 case SK_PassByIndirectRestore:
4824 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004825 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004826 CurInit = Args.get()[0];
4827 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004828 break;
John McCall34376a62010-12-04 03:47:34 +00004829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Douglas Gregore1314a62009-12-18 05:02:21 +00004831 case SK_ConstructorInitialization:
4832 case SK_ZeroInitialization:
4833 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835
4836 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004837 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004838 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004839 for (step_iterator Step = step_begin(), StepEnd = step_end();
4840 Step != StepEnd; ++Step) {
4841 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004842 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843
John Wiegley01296292011-04-08 18:41:53 +00004844 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846 switch (Step->Kind) {
4847 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004849 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004850 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004851 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004852 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004853 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004854 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004855 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004857 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004858 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004859 case SK_CastDerivedToBaseLValue: {
4860 // We have a derived-to-base cast that produces either an rvalue or an
4861 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862
John McCallcf142162010-08-07 06:22:56 +00004863 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004864
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004865 // Casts to inaccessible base classes are allowed with C-style casts.
4866 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4867 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004868 CurInit.get()->getLocStart(),
4869 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004870 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004871 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872
Douglas Gregor88d292c2010-05-13 16:44:06 +00004873 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4874 QualType T = SourceType;
4875 if (const PointerType *Pointer = T->getAs<PointerType>())
4876 T = Pointer->getPointeeType();
4877 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004878 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004879 cast<CXXRecordDecl>(RecordTy->getDecl()));
4880 }
4881
John McCall2536c6d2010-08-25 10:28:54 +00004882 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004883 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004884 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004885 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004886 VK_XValue :
4887 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004888 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4889 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004890 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004891 CurInit.get(),
4892 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004893 break;
4894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004896 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004897 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004898 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4899 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004900 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004901 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004902 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004903 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004904 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004905 }
Anders Carlssona91be642010-01-29 02:47:33 +00004906
John Wiegley01296292011-04-08 18:41:53 +00004907 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004908 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004909 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4910 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004911 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004912 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004913 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004914 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004916 // Reference binding does not have any corresponding ASTs.
4917
4918 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004919 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004920 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004922 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004923
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004924 case SK_BindReferenceToTemporary:
4925 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004926 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004927 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004928
Douglas Gregorfe314812011-06-21 17:03:29 +00004929 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004930 CurInit = new (S.Context) MaterializeTemporaryExpr(
4931 Entity.getType().getNonReferenceType(),
4932 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004933 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004934
4935 // If we're binding to an Objective-C object that has lifetime, we
4936 // need cleanups.
4937 if (S.getLangOptions().ObjCAutoRefCount &&
4938 CurInit.get()->getType()->isObjCLifetimeType())
4939 S.ExprNeedsCleanups = true;
4940
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004941 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004942
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004943 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004945 /*IsExtraneousCopy=*/true);
4946 break;
4947
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004948 case SK_UserConversion: {
4949 // We have a user-defined conversion that invokes either a constructor
4950 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004951 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004952 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004953 FunctionDecl *Fn = Step->Function.Function;
4954 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004955 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004956 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004957 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004958 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004959 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004960 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004961 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004962
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004963 // Determine the arguments required to actually perform the constructor
4964 // call.
John Wiegley01296292011-04-08 18:41:53 +00004965 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004966 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004967 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004968 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004969 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004971 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004972 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004973 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004974 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004975 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004976 CXXConstructExpr::CK_Complete,
4977 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004978 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004979 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004980
Anders Carlssona01874b2010-04-21 18:47:17 +00004981 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004982 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004983 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004984
John McCalle3027922010-08-25 11:45:40 +00004985 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004986 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4987 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4988 S.IsDerivedFrom(SourceType, Class))
4989 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004990
Douglas Gregor95562572010-04-24 23:45:46 +00004991 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004992 } else {
4993 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004994 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004995 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004996 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004997 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
4999 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005000 // derived-to-base conversion? I believe the answer is "no", because
5001 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005002 ExprResult CurInitExprRes =
5003 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5004 FoundFn, Conversion);
5005 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005006 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005007 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005009 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005010 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5011 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005012 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005013 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014
John McCalle3027922010-08-25 11:45:40 +00005015 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005016
Douglas Gregor95562572010-04-24 23:45:46 +00005017 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Sebastian Redl112aa822011-07-14 19:07:55 +00005020 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005021 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5022
5023 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005024 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005025 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005027 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005028 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005029 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00005030 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
5031 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00005032 }
5033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005034
John McCallcf142162010-08-07 06:22:56 +00005035 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005036 CurInit.get()->getType(),
5037 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005038 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005039 if (MaybeBindToTemp)
5040 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005041 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005042 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5043 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005044 break;
5045 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005046
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005047 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005048 case SK_QualificationConversionXValue:
5049 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005050 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005051 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005052 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005053 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005054 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005055 VK_XValue :
5056 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005057 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005058 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005059 }
5060
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005061 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00005062 Sema::CheckedConversionKind CCK
5063 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5064 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005065 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005066 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005067 ExprResult CurInitExprRes =
5068 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005069 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005070 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005071 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005072 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005073 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005075
Douglas Gregor51e77d52009-12-10 17:56:55 +00005076 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005077 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00005078 // Hack: We must pass *ResultType if available in order to set the type
5079 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5080 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5081 // temporary, not a reference, so we should pass Ty.
5082 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5083 // Since this step is never used for a reference directly, we explicitly
5084 // unwrap references here and rewrap them afterwards.
5085 // We also need to create a InitializeTemporary entity for this.
5086 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5087 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5088 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5089 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5090 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005091 Kind.getKind() != InitializationKind::IK_Direct ||
5092 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005093 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005094 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005095
Sebastian Redl29526f02011-11-27 16:50:07 +00005096 if (ResultType) {
5097 if ((*ResultType)->isRValueReferenceType())
5098 Ty = S.Context.getRValueReferenceType(Ty);
5099 else if ((*ResultType)->isLValueReferenceType())
5100 Ty = S.Context.getLValueReferenceType(Ty,
5101 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5102 *ResultType = Ty;
5103 }
5104
5105 InitListExpr *StructuredInitList =
5106 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005107 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005108 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005109 break;
5110 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005111
Sebastian Redled2e5322011-12-22 14:44:04 +00005112 case SK_ListConstructorCall: {
5113 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5114 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5115 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5116 move(Arg), *Step,
5117 ConstructorInitRequiresZeroInit);
5118 break;
5119 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005120
Sebastian Redl29526f02011-11-27 16:50:07 +00005121 case SK_UnwrapInitList:
5122 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5123 break;
5124
5125 case SK_RewrapInitList: {
5126 Expr *E = CurInit.take();
5127 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5128 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5129 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5130 ILE->setSyntacticForm(Syntactic);
5131 ILE->setType(E->getType());
5132 ILE->setValueKind(E->getValueKind());
5133 CurInit = S.Owned(ILE);
5134 break;
5135 }
5136
Sebastian Redled2e5322011-12-22 14:44:04 +00005137 case SK_ConstructorInitialization:
5138 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5139 *Step,
5140 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005141 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005142
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005143 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005144 step_iterator NextStep = Step;
5145 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005146 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005147 NextStep->Kind == SK_ConstructorInitialization) {
5148 // The need for zero-initialization is recorded directly into
5149 // the call to the object's constructor within the next step.
5150 ConstructorInitRequiresZeroInit = true;
5151 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5152 S.getLangOptions().CPlusPlus &&
5153 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005154 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5155 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005157 Kind.getRange().getBegin());
5158
5159 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5160 TSInfo->getType().getNonLValueExprType(S.Context),
5161 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005162 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005163 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005164 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005165 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005166 break;
5167 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005168
5169 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005170 QualType SourceType = CurInit.get()->getType();
5171 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005172 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005173 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5174 if (Result.isInvalid())
5175 return ExprError();
5176 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005177
5178 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005179 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005180 if (ConvTy != Sema::Compatible &&
5181 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005182 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005183 == Sema::Compatible)
5184 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005185 if (CurInitExprRes.isInvalid())
5186 return ExprError();
5187 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005188
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005189 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005190 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5191 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005192 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005193 getAssignmentAction(Entity),
5194 &Complained)) {
5195 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005196 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005197 } else if (Complained)
5198 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005199 break;
5200 }
Eli Friedman78275202009-12-19 08:11:05 +00005201
5202 case SK_StringInit: {
5203 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005204 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005205 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005206 break;
5207 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005208
5209 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005210 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005211 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005212 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005213 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005214
5215 case SK_ArrayInit:
5216 // Okay: we checked everything before creating this step. Note that
5217 // this is a GNU extension.
5218 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005219 << Step->Type << CurInit.get()->getType()
5220 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005221
5222 // If the destination type is an incomplete array type, update the
5223 // type accordingly.
5224 if (ResultType) {
5225 if (const IncompleteArrayType *IncompleteDest
5226 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5227 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005228 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005229 *ResultType = S.Context.getConstantArrayType(
5230 IncompleteDest->getElementType(),
5231 ConstantSource->getSize(),
5232 ArrayType::Normal, 0);
5233 }
5234 }
5235 }
John McCall31168b02011-06-15 23:02:42 +00005236 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005237
John McCall31168b02011-06-15 23:02:42 +00005238 case SK_PassByIndirectCopyRestore:
5239 case SK_PassByIndirectRestore:
5240 checkIndirectCopyRestoreSource(S, CurInit.get());
5241 CurInit = S.Owned(new (S.Context)
5242 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5243 Step->Kind == SK_PassByIndirectCopyRestore));
5244 break;
5245
5246 case SK_ProduceObjCObject:
5247 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005248 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005249 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005250 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005251 }
5252 }
John McCall1f425642010-11-11 03:21:53 +00005253
5254 // Diagnose non-fatal problems with the completed initialization.
5255 if (Entity.getKind() == InitializedEntity::EK_Member &&
5256 cast<FieldDecl>(Entity.getDecl())->isBitField())
5257 S.CheckBitFieldInitialization(Kind.getLocation(),
5258 cast<FieldDecl>(Entity.getDecl()),
5259 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005260
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005261 return move(CurInit);
5262}
5263
5264//===----------------------------------------------------------------------===//
5265// Diagnose initialization failures
5266//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005268 const InitializedEntity &Entity,
5269 const InitializationKind &Kind,
5270 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005271 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005272 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005273
Douglas Gregor1b303932009-12-22 15:35:07 +00005274 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005275 switch (Failure) {
5276 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005277 // FIXME: Customize for the initialized entity?
5278 if (NumArgs == 0)
5279 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5280 << DestType.getNonReferenceType();
5281 else // FIXME: diagnostic below could be better!
5282 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5283 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005284 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005285
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005286 case FK_ArrayNeedsInitList:
5287 case FK_ArrayNeedsInitListOrStringLiteral:
5288 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5289 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5290 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005291
Douglas Gregore2f943b2011-02-22 18:29:51 +00005292 case FK_ArrayTypeMismatch:
5293 case FK_NonConstantArrayInit:
5294 S.Diag(Kind.getLocation(),
5295 (Failure == FK_ArrayTypeMismatch
5296 ? diag::err_array_init_different_type
5297 : diag::err_array_init_non_constant_array))
5298 << DestType.getNonReferenceType()
5299 << Args[0]->getType()
5300 << Args[0]->getSourceRange();
5301 break;
5302
John McCalla59dc2f2012-01-05 00:13:19 +00005303 case FK_VariableLengthArrayHasInitializer:
5304 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5305 << Args[0]->getSourceRange();
5306 break;
5307
John McCall16df1e52010-03-30 21:47:33 +00005308 case FK_AddressOfOverloadFailed: {
5309 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005310 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005311 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005312 true,
5313 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005314 break;
John McCall16df1e52010-03-30 21:47:33 +00005315 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005316
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005317 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005318 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005319 switch (FailedOverloadResult) {
5320 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005321 if (Failure == FK_UserConversionOverloadFailed)
5322 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5323 << Args[0]->getType() << DestType
5324 << Args[0]->getSourceRange();
5325 else
5326 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5327 << DestType << Args[0]->getType()
5328 << Args[0]->getSourceRange();
5329
John McCall5c32be02010-08-24 20:38:10 +00005330 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005331 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005333 case OR_No_Viable_Function:
5334 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5335 << Args[0]->getType() << DestType.getNonReferenceType()
5336 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005337 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005338 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005339
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005340 case OR_Deleted: {
5341 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5342 << Args[0]->getType() << DestType.getNonReferenceType()
5343 << Args[0]->getSourceRange();
5344 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005345 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005346 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5347 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005348 if (Ovl == OR_Deleted) {
5349 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005350 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005351 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005352 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005353 }
5354 break;
5355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005356
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005357 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005358 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005359 break;
5360 }
5361 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005362
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005363 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005364 if (isa<InitListExpr>(Args[0])) {
5365 S.Diag(Kind.getLocation(),
5366 diag::err_lvalue_reference_bind_to_initlist)
5367 << DestType.getNonReferenceType().isVolatileQualified()
5368 << DestType.getNonReferenceType()
5369 << Args[0]->getSourceRange();
5370 break;
5371 }
5372 // Intentional fallthrough
5373
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005374 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005375 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005376 Failure == FK_NonConstLValueReferenceBindingToTemporary
5377 ? diag::err_lvalue_reference_bind_to_temporary
5378 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005379 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005380 << DestType.getNonReferenceType()
5381 << Args[0]->getType()
5382 << Args[0]->getSourceRange();
5383 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005384
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005385 case FK_RValueReferenceBindingToLValue:
5386 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005387 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005388 << Args[0]->getSourceRange();
5389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005390
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005391 case FK_ReferenceInitDropsQualifiers:
5392 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5393 << DestType.getNonReferenceType()
5394 << Args[0]->getType()
5395 << Args[0]->getSourceRange();
5396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005397
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005398 case FK_ReferenceInitFailed:
5399 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5400 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005401 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005402 << Args[0]->getType()
5403 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005404 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5405 Args[0]->getType()->isObjCObjectPointerType())
5406 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005407 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005408
Douglas Gregorb491ed32011-02-19 21:32:49 +00005409 case FK_ConversionFailed: {
5410 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005411 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005412 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005413 << DestType
John McCall086a4642010-11-24 05:12:34 +00005414 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005415 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005416 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005417 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5418 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005419 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5420 Args[0]->getType()->isObjCObjectPointerType())
5421 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005422 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005423 }
John Wiegley01296292011-04-08 18:41:53 +00005424
5425 case FK_ConversionFromPropertyFailed:
5426 // No-op. This error has already been reported.
5427 break;
5428
Douglas Gregor51e77d52009-12-10 17:56:55 +00005429 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005430 SourceRange R;
5431
5432 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005433 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005434 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005435 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005436 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005437
Douglas Gregor8ec51732010-09-08 21:40:08 +00005438 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5439 if (Kind.isCStyleOrFunctionalCast())
5440 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5441 << R;
5442 else
5443 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5444 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005445 break;
5446 }
5447
5448 case FK_ReferenceBindingToInitList:
5449 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5450 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5451 break;
5452
5453 case FK_InitListBadDestinationType:
5454 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5455 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5456 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005457
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005458 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005459 case FK_ConstructorOverloadFailed: {
5460 SourceRange ArgsRange;
5461 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005463 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005465 if (Failure == FK_ListConstructorOverloadFailed) {
5466 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5467 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5468 Args = InitList->getInits();
5469 NumArgs = InitList->getNumInits();
5470 }
5471
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005472 // FIXME: Using "DestType" for the entity we're printing is probably
5473 // bad.
5474 switch (FailedOverloadResult) {
5475 case OR_Ambiguous:
5476 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5477 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005478 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5479 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005480 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005482 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005483 if (Kind.getKind() == InitializationKind::IK_Default &&
5484 (Entity.getKind() == InitializedEntity::EK_Base ||
5485 Entity.getKind() == InitializedEntity::EK_Member) &&
5486 isa<CXXConstructorDecl>(S.CurContext)) {
5487 // This is implicit default initialization of a member or
5488 // base within a constructor. If no viable function was
5489 // found, notify the user that she needs to explicitly
5490 // initialize this base/member.
5491 CXXConstructorDecl *Constructor
5492 = cast<CXXConstructorDecl>(S.CurContext);
5493 if (Entity.getKind() == InitializedEntity::EK_Base) {
5494 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5495 << Constructor->isImplicit()
5496 << S.Context.getTypeDeclType(Constructor->getParent())
5497 << /*base=*/0
5498 << Entity.getType();
5499
5500 RecordDecl *BaseDecl
5501 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5502 ->getDecl();
5503 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5504 << S.Context.getTagDeclType(BaseDecl);
5505 } else {
5506 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5507 << Constructor->isImplicit()
5508 << S.Context.getTypeDeclType(Constructor->getParent())
5509 << /*member=*/1
5510 << Entity.getName();
5511 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5512
5513 if (const RecordType *Record
5514 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005515 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005516 diag::note_previous_decl)
5517 << S.Context.getTagDeclType(Record->getDecl());
5518 }
5519 break;
5520 }
5521
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005522 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5523 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005524 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005525 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005527 case OR_Deleted: {
5528 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5529 << true << DestType << ArgsRange;
5530 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005531 OverloadingResult Ovl
5532 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005533 if (Ovl == OR_Deleted) {
5534 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005535 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005536 } else {
5537 llvm_unreachable("Inconsistent overload resolution?");
5538 }
5539 break;
5540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005541
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005542 case OR_Success:
5543 llvm_unreachable("Conversion did not fail!");
5544 break;
5545 }
5546 break;
5547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005548
Douglas Gregor85dabae2009-12-16 01:38:02 +00005549 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005550 if (Entity.getKind() == InitializedEntity::EK_Member &&
5551 isa<CXXConstructorDecl>(S.CurContext)) {
5552 // This is implicit default-initialization of a const member in
5553 // a constructor. Complain that it needs to be explicitly
5554 // initialized.
5555 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5556 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5557 << Constructor->isImplicit()
5558 << S.Context.getTypeDeclType(Constructor->getParent())
5559 << /*const=*/1
5560 << Entity.getName();
5561 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5562 << Entity.getName();
5563 } else {
5564 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5565 << DestType << (bool)DestType->getAs<RecordType>();
5566 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005567 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005568
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005569 case FK_Incomplete:
5570 S.RequireCompleteType(Kind.getLocation(), DestType,
5571 diag::err_init_incomplete_type);
5572 break;
5573
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005574 case FK_ListInitializationFailed: {
5575 // Run the init list checker again to emit diagnostics.
5576 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5577 QualType DestType = Entity.getType();
5578 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005579 DestType, /*VerifyOnly=*/false,
5580 Kind.getKind() != InitializationKind::IK_Direct ||
5581 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005582 assert(DiagnoseInitList.HadError() &&
5583 "Inconsistent init list check result.");
5584 break;
5585 }
John McCall4124c492011-10-17 18:40:02 +00005586
5587 case FK_PlaceholderType: {
5588 // FIXME: Already diagnosed!
5589 break;
5590 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005593 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005594 return true;
5595}
Douglas Gregore1314a62009-12-18 05:02:21 +00005596
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005597void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005598 switch (SequenceKind) {
5599 case FailedSequence: {
5600 OS << "Failed sequence: ";
5601 switch (Failure) {
5602 case FK_TooManyInitsForReference:
5603 OS << "too many initializers for reference";
5604 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005606 case FK_ArrayNeedsInitList:
5607 OS << "array requires initializer list";
5608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005610 case FK_ArrayNeedsInitListOrStringLiteral:
5611 OS << "array requires initializer list or string literal";
5612 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005613
Douglas Gregore2f943b2011-02-22 18:29:51 +00005614 case FK_ArrayTypeMismatch:
5615 OS << "array type mismatch";
5616 break;
5617
5618 case FK_NonConstantArrayInit:
5619 OS << "non-constant array initializer";
5620 break;
5621
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005622 case FK_AddressOfOverloadFailed:
5623 OS << "address of overloaded function failed";
5624 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005626 case FK_ReferenceInitOverloadFailed:
5627 OS << "overload resolution for reference initialization failed";
5628 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005630 case FK_NonConstLValueReferenceBindingToTemporary:
5631 OS << "non-const lvalue reference bound to temporary";
5632 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005633
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005634 case FK_NonConstLValueReferenceBindingToUnrelated:
5635 OS << "non-const lvalue reference bound to unrelated type";
5636 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005638 case FK_RValueReferenceBindingToLValue:
5639 OS << "rvalue reference bound to an lvalue";
5640 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005641
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005642 case FK_ReferenceInitDropsQualifiers:
5643 OS << "reference initialization drops qualifiers";
5644 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005645
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005646 case FK_ReferenceInitFailed:
5647 OS << "reference initialization failed";
5648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005650 case FK_ConversionFailed:
5651 OS << "conversion failed";
5652 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005653
John Wiegley01296292011-04-08 18:41:53 +00005654 case FK_ConversionFromPropertyFailed:
5655 OS << "conversion from property failed";
5656 break;
5657
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005658 case FK_TooManyInitsForScalar:
5659 OS << "too many initializers for scalar";
5660 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005661
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005662 case FK_ReferenceBindingToInitList:
5663 OS << "referencing binding to initializer list";
5664 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005665
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005666 case FK_InitListBadDestinationType:
5667 OS << "initializer list for non-aggregate, non-scalar type";
5668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005670 case FK_UserConversionOverloadFailed:
5671 OS << "overloading failed for user-defined conversion";
5672 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005674 case FK_ConstructorOverloadFailed:
5675 OS << "constructor overloading failed";
5676 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005677
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005678 case FK_DefaultInitOfConst:
5679 OS << "default initialization of a const variable";
5680 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005681
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005682 case FK_Incomplete:
5683 OS << "initialization of incomplete type";
5684 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005685
5686 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005687 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005688 break;
5689
John McCalla59dc2f2012-01-05 00:13:19 +00005690 case FK_VariableLengthArrayHasInitializer:
5691 OS << "variable length array has an initializer";
5692 break;
5693
John McCall4124c492011-10-17 18:40:02 +00005694 case FK_PlaceholderType:
5695 OS << "initializer expression isn't contextually valid";
5696 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005697
5698 case FK_ListConstructorOverloadFailed:
5699 OS << "list constructor overloading failed";
5700 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005701 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005702 OS << '\n';
5703 return;
5704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005705
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005706 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005707 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005708 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709
Sebastian Redld201edf2011-06-05 13:59:11 +00005710 case NormalSequence:
5711 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005712 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005714
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005715 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5716 if (S != step_begin()) {
5717 OS << " -> ";
5718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005720 switch (S->Kind) {
5721 case SK_ResolveAddressOfOverloadedFunction:
5722 OS << "resolve address of overloaded function";
5723 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005725 case SK_CastDerivedToBaseRValue:
5726 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5727 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005728
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005729 case SK_CastDerivedToBaseXValue:
5730 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5731 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005732
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005733 case SK_CastDerivedToBaseLValue:
5734 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5735 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005737 case SK_BindReference:
5738 OS << "bind reference to lvalue";
5739 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005740
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005741 case SK_BindReferenceToTemporary:
5742 OS << "bind reference to a temporary";
5743 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005744
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005745 case SK_ExtraneousCopyToTemporary:
5746 OS << "extraneous C++03 copy to temporary";
5747 break;
5748
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005749 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005750 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005751 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005752
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005753 case SK_QualificationConversionRValue:
5754 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005755 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005756
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005757 case SK_QualificationConversionXValue:
5758 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005759 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005760
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005761 case SK_QualificationConversionLValue:
5762 OS << "qualification conversion (lvalue)";
5763 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005765 case SK_ConversionSequence:
5766 OS << "implicit conversion sequence (";
5767 S->ICS->DebugPrint(); // FIXME: use OS
5768 OS << ")";
5769 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005771 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005772 OS << "list aggregate initialization";
5773 break;
5774
5775 case SK_ListConstructorCall:
5776 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005777 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005778
Sebastian Redl29526f02011-11-27 16:50:07 +00005779 case SK_UnwrapInitList:
5780 OS << "unwrap reference initializer list";
5781 break;
5782
5783 case SK_RewrapInitList:
5784 OS << "rewrap reference initializer list";
5785 break;
5786
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005787 case SK_ConstructorInitialization:
5788 OS << "constructor initialization";
5789 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005790
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005791 case SK_ZeroInitialization:
5792 OS << "zero initialization";
5793 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005794
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005795 case SK_CAssignment:
5796 OS << "C assignment";
5797 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005798
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005799 case SK_StringInit:
5800 OS << "string initialization";
5801 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005802
5803 case SK_ObjCObjectConversion:
5804 OS << "Objective-C object conversion";
5805 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005806
5807 case SK_ArrayInit:
5808 OS << "array initialization";
5809 break;
John McCall31168b02011-06-15 23:02:42 +00005810
5811 case SK_PassByIndirectCopyRestore:
5812 OS << "pass by indirect copy and restore";
5813 break;
5814
5815 case SK_PassByIndirectRestore:
5816 OS << "pass by indirect restore";
5817 break;
5818
5819 case SK_ProduceObjCObject:
5820 OS << "Objective-C object retension";
5821 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005822 }
5823 }
5824}
5825
5826void InitializationSequence::dump() const {
5827 dump(llvm::errs());
5828}
5829
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005830static void DiagnoseNarrowingInInitList(
5831 Sema& S, QualType EntityType, const Expr *InitE,
5832 bool Constant, const APValue &ConstantValue) {
5833 if (Constant) {
5834 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005835 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005836 ? diag::err_init_list_constant_narrowing
5837 : diag::warn_init_list_constant_narrowing)
5838 << InitE->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005839 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005840 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005841 } else
5842 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005843 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005844 ? diag::err_init_list_variable_narrowing
5845 : diag::warn_init_list_variable_narrowing)
5846 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005847 << InitE->getType().getLocalUnqualifiedType()
5848 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005849
5850 llvm::SmallString<128> StaticCast;
5851 llvm::raw_svector_ostream OS(StaticCast);
5852 OS << "static_cast<";
5853 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5854 // It's important to use the typedef's name if there is one so that the
5855 // fixit doesn't break code using types like int64_t.
5856 //
5857 // FIXME: This will break if the typedef requires qualification. But
5858 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005859 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005860 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5861 OS << BT->getName(S.getLangOptions());
5862 else {
5863 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5864 // with a broken cast.
5865 return;
5866 }
5867 OS << ">(";
5868 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5869 << InitE->getSourceRange()
5870 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5871 << FixItHint::CreateInsertion(
5872 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5873}
5874
Douglas Gregore1314a62009-12-18 05:02:21 +00005875//===----------------------------------------------------------------------===//
5876// Initialization helper functions
5877//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005878bool
5879Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5880 ExprResult Init) {
5881 if (Init.isInvalid())
5882 return false;
5883
5884 Expr *InitE = Init.get();
5885 assert(InitE && "No initialization expression");
5886
5887 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5888 SourceLocation());
5889 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005890 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005891}
5892
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005894Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5895 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005896 ExprResult Init,
5897 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005898 if (Init.isInvalid())
5899 return ExprError();
5900
John McCall1f425642010-11-11 03:21:53 +00005901 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005902 assert(InitE && "No initialization expression?");
5903
5904 if (EqualLoc.isInvalid())
5905 EqualLoc = InitE->getLocStart();
5906
5907 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5908 EqualLoc);
5909 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5910 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005911
5912 bool Constant = false;
5913 APValue Result;
5914 if (TopLevelOfInitList &&
5915 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5916 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5917 Constant, Result);
5918 }
John McCallfaf5fb42010-08-26 23:41:50 +00005919 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005920}