blob: bcb624be899ce74a2e35a792d8c381887ec1b4f9 [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
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001532/// @brief Check the well-formedness of a C99 designated initializer.
1533///
1534/// Determines whether the designated initializer @p DIE, which
1535/// resides at the given @p Index within the initializer list @p
1536/// IList, is well-formed for a current object of type @p DeclType
1537/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001538/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001539/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001540///
1541/// @param IList The initializer list in which this designated
1542/// initializer occurs.
1543///
Douglas Gregora5324162009-04-15 04:56:10 +00001544/// @param DIE The designated initializer expression.
1545///
1546/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001547///
1548/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1549/// into which the designation in @p DIE should refer.
1550///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001551/// @param NextField If non-NULL and the first designator in @p DIE is
1552/// a field, this will be set to the field declaration corresponding
1553/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001554///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001555/// @param NextElementIndex If non-NULL and the first designator in @p
1556/// DIE is an array designator or GNU array-range designator, this
1557/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001558///
1559/// @param Index Index into @p IList where the designated initializer
1560/// @p DIE occurs.
1561///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001562/// @param StructuredList The initializer list expression that
1563/// describes all of the subobject initializers in the order they'll
1564/// actually be initialized.
1565///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001566/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001567bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001568InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001569 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001570 DesignatedInitExpr *DIE,
1571 unsigned DesigIdx,
1572 QualType &CurrentObjectType,
1573 RecordDecl::field_iterator *NextField,
1574 llvm::APSInt *NextElementIndex,
1575 unsigned &Index,
1576 InitListExpr *StructuredList,
1577 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001578 bool FinishSubobjectInit,
1579 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001580 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001581 // Check the actual initialization for the designated object type.
1582 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001583
1584 // Temporarily remove the designator expression from the
1585 // initializer list that the child calls see, so that we don't try
1586 // to re-process the designator.
1587 unsigned OldIndex = Index;
1588 IList->setInit(OldIndex, DIE->getInit());
1589
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001590 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001591 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001592
1593 // Restore the designated initializer expression in the syntactic
1594 // form of the initializer list.
1595 if (IList->getInit(OldIndex) != DIE->getInit())
1596 DIE->setInit(IList->getInit(OldIndex));
1597 IList->setInit(OldIndex, DIE);
1598
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001599 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001600 }
1601
Douglas Gregora5324162009-04-15 04:56:10 +00001602 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001603 bool IsFirstDesignator = (DesigIdx == 0);
1604 if (!VerifyOnly) {
1605 assert((IsFirstDesignator || StructuredList) &&
1606 "Need a non-designated initializer list to start from");
1607
1608 // Determine the structural initializer list that corresponds to the
1609 // current subobject.
1610 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1611 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1612 StructuredList, StructuredIndex,
1613 SourceRange(D->getStartLocation(),
1614 DIE->getSourceRange().getEnd()));
1615 assert(StructuredList && "Expected a structured initializer list");
1616 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001617
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001618 if (D->isFieldDesignator()) {
1619 // C99 6.7.8p7:
1620 //
1621 // If a designator has the form
1622 //
1623 // . identifier
1624 //
1625 // then the current object (defined below) shall have
1626 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001627 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001628 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001629 if (!RT) {
1630 SourceLocation Loc = D->getDotLoc();
1631 if (Loc.isInvalid())
1632 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001633 if (!VerifyOnly)
1634 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1635 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001636 ++Index;
1637 return true;
1638 }
1639
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001640 // Note: we perform a linear search of the fields here, despite
1641 // the fact that we have a faster lookup method, because we always
1642 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001643 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001644 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001645 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001646 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001647 Field = RT->getDecl()->field_begin(),
1648 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001649 for (; Field != FieldEnd; ++Field) {
1650 if (Field->isUnnamedBitfield())
1651 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001652
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001653 // If we find a field representing an anonymous field, look in the
1654 // IndirectFieldDecl that follow for the designated initializer.
1655 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1656 if (IndirectFieldDecl *IF =
1657 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001658 // In verify mode, don't modify the original.
1659 if (VerifyOnly)
1660 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001661 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1662 D = DIE->getDesignator(DesigIdx);
1663 break;
1664 }
1665 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001666 if (KnownField && KnownField == *Field)
1667 break;
1668 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001669 break;
1670
1671 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001672 }
1673
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001674 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001675 if (VerifyOnly) {
1676 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001677 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001678 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001679
Douglas Gregord5846a12009-04-15 06:41:24 +00001680 // There was no normal field in the struct with the designated
1681 // name. Perform another lookup for this name, which may find
1682 // something that we can't designate (e.g., a member function),
1683 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001684 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001685 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001686 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001687 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001688 // Name lookup didn't find anything. Determine whether this
1689 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001690 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001691 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001692 TypoCorrection Corrected = SemaRef.CorrectTypo(
1693 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1694 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1695 RT->getDecl(), false, Sema::CTC_NoKeywords);
1696 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001697 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001698 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001699 std::string CorrectedStr(
1700 Corrected.getAsString(SemaRef.getLangOptions()));
1701 std::string CorrectedQuotedStr(
1702 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001704 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001705 << FieldName << CurrentObjectType << CorrectedQuotedStr
1706 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001707 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001708 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001709 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001710 } else {
1711 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1712 << FieldName << CurrentObjectType;
1713 ++Index;
1714 return true;
1715 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001718 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001719 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001720 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001721 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001722 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001723 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001724 ++Index;
1725 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001726 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001727
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001728 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001729 // The replacement field comes from typo correction; find it
1730 // in the list of fields.
1731 FieldIndex = 0;
1732 Field = RT->getDecl()->field_begin();
1733 for (; Field != FieldEnd; ++Field) {
1734 if (Field->isUnnamedBitfield())
1735 continue;
1736
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001738 Field->getIdentifier() == ReplacementField->getIdentifier())
1739 break;
1740
1741 ++FieldIndex;
1742 }
1743 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001744 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001745
1746 // All of the fields of a union are located at the same place in
1747 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001748 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001749 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001750 if (!VerifyOnly)
1751 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001752 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001753
Douglas Gregora82064c2011-06-29 21:51:31 +00001754 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001755 bool InvalidUse;
1756 if (VerifyOnly)
1757 InvalidUse = !SemaRef.CanUseDecl(*Field);
1758 else
1759 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1760 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001761 ++Index;
1762 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001763 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001764
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001765 if (!VerifyOnly) {
1766 // Update the designator with the field declaration.
1767 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001768
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001769 // Make sure that our non-designated initializer list has space
1770 // for a subobject corresponding to this field.
1771 if (FieldIndex >= StructuredList->getNumInits())
1772 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1773 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001774
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001775 // This designator names a flexible array member.
1776 if (Field->getType()->isIncompleteArrayType()) {
1777 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001778 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001779 // We can't designate an object within the flexible array
1780 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001781 if (!VerifyOnly) {
1782 DesignatedInitExpr::Designator *NextD
1783 = DIE->getDesignator(DesigIdx + 1);
1784 SemaRef.Diag(NextD->getStartLocation(),
1785 diag::err_designator_into_flexible_array_member)
1786 << SourceRange(NextD->getStartLocation(),
1787 DIE->getSourceRange().getEnd());
1788 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1789 << *Field;
1790 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001791 Invalid = true;
1792 }
1793
Chris Lattner001b29c2010-10-10 17:49:49 +00001794 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1795 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001796 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001797 if (!VerifyOnly) {
1798 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1799 diag::err_flexible_array_init_needs_braces)
1800 << DIE->getInit()->getSourceRange();
1801 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1802 << *Field;
1803 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001804 Invalid = true;
1805 }
1806
Eli Friedman3fa64df2011-08-23 22:24:57 +00001807 // Check GNU flexible array initializer.
1808 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1809 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001810 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001811
1812 if (Invalid) {
1813 ++Index;
1814 return true;
1815 }
1816
1817 // Initialize the array.
1818 bool prevHadError = hadError;
1819 unsigned newStructuredIndex = FieldIndex;
1820 unsigned OldIndex = Index;
1821 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001822
1823 InitializedEntity MemberEntity =
1824 InitializedEntity::InitializeMember(*Field, &Entity);
1825 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001826 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001827
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001828 IList->setInit(OldIndex, DIE);
1829 if (hadError && !prevHadError) {
1830 ++Field;
1831 ++FieldIndex;
1832 if (NextField)
1833 *NextField = Field;
1834 StructuredIndex = FieldIndex;
1835 return true;
1836 }
1837 } else {
1838 // Recurse to check later designated subobjects.
1839 QualType FieldType = (*Field)->getType();
1840 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001842 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001843 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1845 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001846 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001847 true, false))
1848 return true;
1849 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001850
1851 // Find the position of the next field to be initialized in this
1852 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001853 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001854 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001855
1856 // If this the first designator, our caller will continue checking
1857 // the rest of this struct/class/union subobject.
1858 if (IsFirstDesignator) {
1859 if (NextField)
1860 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001861 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001862 return false;
1863 }
1864
Douglas Gregor17bd0942009-01-28 23:36:17 +00001865 if (!FinishSubobjectInit)
1866 return false;
1867
Douglas Gregord5846a12009-04-15 06:41:24 +00001868 // We've already initialized something in the union; we're done.
1869 if (RT->getDecl()->isUnion())
1870 return hadError;
1871
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001872 // Check the remaining fields within this class/struct/union subobject.
1873 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874
Anders Carlsson6cabf312010-01-23 23:23:01 +00001875 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001876 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001877 return hadError && !prevHadError;
1878 }
1879
1880 // C99 6.7.8p6:
1881 //
1882 // If a designator has the form
1883 //
1884 // [ constant-expression ]
1885 //
1886 // then the current object (defined below) shall have array
1887 // type and the expression shall be an integer constant
1888 // expression. If the array is of unknown size, any
1889 // nonnegative value is valid.
1890 //
1891 // Additionally, cope with the GNU extension that permits
1892 // designators of the form
1893 //
1894 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001895 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001896 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001897 if (!VerifyOnly)
1898 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1899 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001900 ++Index;
1901 return true;
1902 }
1903
1904 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001905 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1906 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001907 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001908 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001909 DesignatedEndIndex = DesignatedStartIndex;
1910 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001911 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001912
Mike Stump11289f42009-09-09 15:08:12 +00001913 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001914 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001915 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001916 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001917 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001918
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001919 // Codegen can't handle evaluating array range designators that have side
1920 // effects, because we replicate the AST value for each initialized element.
1921 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1922 // elements with something that has a side effect, so codegen can emit an
1923 // "error unsupported" error instead of miscompiling the app.
1924 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001925 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001926 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001927 }
1928
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001929 if (isa<ConstantArrayType>(AT)) {
1930 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001931 DesignatedStartIndex
1932 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001933 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001934 DesignatedEndIndex
1935 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001936 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1937 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001938 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001939 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1940 diag::err_array_designator_too_large)
1941 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1942 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001943 ++Index;
1944 return true;
1945 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001946 } else {
1947 // Make sure the bit-widths and signedness match.
1948 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001949 DesignatedEndIndex
1950 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001951 else if (DesignatedStartIndex.getBitWidth() <
1952 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001953 DesignatedStartIndex
1954 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001955 DesignatedStartIndex.setIsUnsigned(true);
1956 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001957 }
Mike Stump11289f42009-09-09 15:08:12 +00001958
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001959 // Make sure that our non-designated initializer list has space
1960 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001961 if (!VerifyOnly &&
1962 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001963 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001964 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001965
Douglas Gregor17bd0942009-01-28 23:36:17 +00001966 // Repeatedly perform subobject initializations in the range
1967 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001968
Douglas Gregor17bd0942009-01-28 23:36:17 +00001969 // Move to the next designator
1970 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1971 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001973 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001974 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001975
Douglas Gregor17bd0942009-01-28 23:36:17 +00001976 while (DesignatedStartIndex <= DesignatedEndIndex) {
1977 // Recurse to check later designated subobjects.
1978 QualType ElementType = AT->getElementType();
1979 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001981 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1983 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001984 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001985 (DesignatedStartIndex == DesignatedEndIndex),
1986 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001987 return true;
1988
1989 // Move to the next index in the array that we'll be initializing.
1990 ++DesignatedStartIndex;
1991 ElementIndex = DesignatedStartIndex.getZExtValue();
1992 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001993
1994 // If this the first designator, our caller will continue checking
1995 // the rest of this array subobject.
1996 if (IsFirstDesignator) {
1997 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001998 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001999 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002000 return false;
2001 }
Mike Stump11289f42009-09-09 15:08:12 +00002002
Douglas Gregor17bd0942009-01-28 23:36:17 +00002003 if (!FinishSubobjectInit)
2004 return false;
2005
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002006 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002007 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002009 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002010 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002011 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002012}
2013
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002014// Get the structured initializer list for a subobject of type
2015// @p CurrentObjectType.
2016InitListExpr *
2017InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2018 QualType CurrentObjectType,
2019 InitListExpr *StructuredList,
2020 unsigned StructuredIndex,
2021 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002022 if (VerifyOnly)
2023 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002024 Expr *ExistingInit = 0;
2025 if (!StructuredList)
2026 ExistingInit = SyntacticToSemantic[IList];
2027 else if (StructuredIndex < StructuredList->getNumInits())
2028 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002030 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2031 return Result;
2032
2033 if (ExistingInit) {
2034 // We are creating an initializer list that initializes the
2035 // subobjects of the current object, but there was already an
2036 // initialization that completely initialized the current
2037 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002038 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002039 // struct X { int a, b; };
2040 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002041 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002042 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2043 // designated initializer re-initializes the whole
2044 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002045 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002046 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002047 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002048 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002049 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002050 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002051 << ExistingInit->getSourceRange();
2052 }
2053
Mike Stump11289f42009-09-09 15:08:12 +00002054 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002055 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2056 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002057 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002058
Douglas Gregora8a089b2010-07-13 18:40:04 +00002059 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002060
Douglas Gregor6d00c992009-03-20 23:58:33 +00002061 // Pre-allocate storage for the structured initializer list.
2062 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002063 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002064 bool GotNumInits = false;
2065 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002066 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002067 GotNumInits = true;
2068 } else if (Index < IList->getNumInits()) {
2069 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002070 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002071 GotNumInits = true;
2072 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002073 }
2074
Mike Stump11289f42009-09-09 15:08:12 +00002075 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002076 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2077 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2078 NumElements = CAType->getSize().getZExtValue();
2079 // Simple heuristic so that we don't allocate a very large
2080 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002081 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002082 NumElements = 0;
2083 }
John McCall9dd450b2009-09-21 23:43:11 +00002084 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002085 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002086 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002087 RecordDecl *RDecl = RType->getDecl();
2088 if (RDecl->isUnion())
2089 NumElements = 1;
2090 else
Mike Stump11289f42009-09-09 15:08:12 +00002091 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002092 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002093 }
2094
Ted Kremenekac034612010-04-13 23:39:13 +00002095 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002096
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002097 // Link this new initializer list into the structured initializer
2098 // lists.
2099 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002100 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002101 else {
2102 Result->setSyntacticForm(IList);
2103 SyntacticToSemantic[IList] = Result;
2104 }
2105
2106 return Result;
2107}
2108
2109/// Update the initializer at index @p StructuredIndex within the
2110/// structured initializer list to the value @p expr.
2111void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2112 unsigned &StructuredIndex,
2113 Expr *expr) {
2114 // No structured initializer list to update
2115 if (!StructuredList)
2116 return;
2117
Ted Kremenekac034612010-04-13 23:39:13 +00002118 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2119 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002120 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002121 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002122 diag::warn_initializer_overrides)
2123 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002124 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002125 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002126 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002127 << PrevInit->getSourceRange();
2128 }
Mike Stump11289f42009-09-09 15:08:12 +00002129
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002130 ++StructuredIndex;
2131}
2132
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002133/// Check that the given Index expression is a valid array designator
2134/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002135/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002136/// and produces a reasonable diagnostic if there is a
2137/// failure. Returns true if there was an error, false otherwise. If
2138/// everything went okay, Value will receive the value of the constant
2139/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00002140static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002141CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002142 SourceLocation Loc = Index->getSourceRange().getBegin();
2143
2144 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002145 if (S.VerifyIntegerConstantExpression(Index, &Value))
2146 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002147
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002148 if (Value.isSigned() && Value.isNegative())
2149 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002150 << Value.toString(10) << Index->getSourceRange();
2151
Douglas Gregor51650d32009-01-23 21:04:18 +00002152 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002153 return false;
2154}
2155
John McCalldadc5752010-08-24 06:29:42 +00002156ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002157 SourceLocation Loc,
2158 bool GNUSyntax,
2159 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002160 typedef DesignatedInitExpr::Designator ASTDesignator;
2161
2162 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002163 SmallVector<ASTDesignator, 32> Designators;
2164 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002165
2166 // Build designators and check array designator expressions.
2167 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2168 const Designator &D = Desig.getDesignator(Idx);
2169 switch (D.getKind()) {
2170 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002171 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002172 D.getFieldLoc()));
2173 break;
2174
2175 case Designator::ArrayDesignator: {
2176 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2177 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002178 if (!Index->isTypeDependent() &&
2179 !Index->isValueDependent() &&
2180 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002181 Invalid = true;
2182 else {
2183 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002184 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002185 D.getRBracketLoc()));
2186 InitExpressions.push_back(Index);
2187 }
2188 break;
2189 }
2190
2191 case Designator::ArrayRangeDesignator: {
2192 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2193 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2194 llvm::APSInt StartValue;
2195 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002196 bool StartDependent = StartIndex->isTypeDependent() ||
2197 StartIndex->isValueDependent();
2198 bool EndDependent = EndIndex->isTypeDependent() ||
2199 EndIndex->isValueDependent();
2200 if ((!StartDependent &&
2201 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2202 (!EndDependent &&
2203 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002204 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002205 else {
2206 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002207 if (StartDependent || EndDependent) {
2208 // Nothing to compute.
2209 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002210 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002211 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002212 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002213
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002214 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002215 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002216 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002217 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2218 Invalid = true;
2219 } else {
2220 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002221 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002222 D.getEllipsisLoc(),
2223 D.getRBracketLoc()));
2224 InitExpressions.push_back(StartIndex);
2225 InitExpressions.push_back(EndIndex);
2226 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002227 }
2228 break;
2229 }
2230 }
2231 }
2232
2233 if (Invalid || Init.isInvalid())
2234 return ExprError();
2235
2236 // Clear out the expressions within the designation.
2237 Desig.ClearExprs(*this);
2238
2239 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002240 = DesignatedInitExpr::Create(Context,
2241 Designators.data(), Designators.size(),
2242 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002243 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244
Richard Smithe4345902011-12-29 21:57:33 +00002245 if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002246 Diag(DIE->getLocStart(), diag::ext_designated_init)
2247 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002248
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002249 return Owned(DIE);
2250}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002251
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002252//===----------------------------------------------------------------------===//
2253// Initialization entity
2254//===----------------------------------------------------------------------===//
2255
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002256InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002257 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002258 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002259{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002260 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2261 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002262 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002263 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002264 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002265 Type = VT->getElementType();
2266 } else {
2267 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2268 assert(CT && "Unexpected type");
2269 Kind = EK_ComplexElement;
2270 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002271 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002272}
2273
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002275 CXXBaseSpecifier *Base,
2276 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002277{
2278 InitializedEntity Result;
2279 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002280 Result.Base = reinterpret_cast<uintptr_t>(Base);
2281 if (IsInheritedVirtualBase)
2282 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002283
Douglas Gregor1b303932009-12-22 15:35:07 +00002284 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002285 return Result;
2286}
2287
Douglas Gregor85dabae2009-12-16 01:38:02 +00002288DeclarationName InitializedEntity::getName() const {
2289 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002290 case EK_Parameter: {
2291 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2292 return (D ? D->getDeclName() : DeclarationName());
2293 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002294
2295 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002296 case EK_Member:
2297 return VariableOrMember->getDeclName();
2298
2299 case EK_Result:
2300 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002301 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002302 case EK_Temporary:
2303 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002304 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002305 case EK_ArrayElement:
2306 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002307 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002308 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002309 return DeclarationName();
2310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311
Douglas Gregor85dabae2009-12-16 01:38:02 +00002312 // Silence GCC warning
2313 return DeclarationName();
2314}
2315
Douglas Gregora4b592a2009-12-19 03:01:41 +00002316DeclaratorDecl *InitializedEntity::getDecl() const {
2317 switch (getKind()) {
2318 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002319 case EK_Member:
2320 return VariableOrMember;
2321
John McCall31168b02011-06-15 23:02:42 +00002322 case EK_Parameter:
2323 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2324
Douglas Gregora4b592a2009-12-19 03:01:41 +00002325 case EK_Result:
2326 case EK_Exception:
2327 case EK_New:
2328 case EK_Temporary:
2329 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002330 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002331 case EK_ArrayElement:
2332 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002333 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002334 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002335 return 0;
2336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002337
Douglas Gregora4b592a2009-12-19 03:01:41 +00002338 // Silence GCC warning
2339 return 0;
2340}
2341
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002342bool InitializedEntity::allowsNRVO() const {
2343 switch (getKind()) {
2344 case EK_Result:
2345 case EK_Exception:
2346 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002348 case EK_Variable:
2349 case EK_Parameter:
2350 case EK_Member:
2351 case EK_New:
2352 case EK_Temporary:
2353 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002354 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002355 case EK_ArrayElement:
2356 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002357 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002358 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002359 break;
2360 }
2361
2362 return false;
2363}
2364
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002365//===----------------------------------------------------------------------===//
2366// Initialization sequence
2367//===----------------------------------------------------------------------===//
2368
2369void InitializationSequence::Step::Destroy() {
2370 switch (Kind) {
2371 case SK_ResolveAddressOfOverloadedFunction:
2372 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002373 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002374 case SK_CastDerivedToBaseLValue:
2375 case SK_BindReference:
2376 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002377 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002378 case SK_UserConversion:
2379 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002380 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002381 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002382 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002383 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002384 case SK_UnwrapInitList:
2385 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002386 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002387 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002388 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002389 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002390 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002391 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002392 case SK_PassByIndirectCopyRestore:
2393 case SK_PassByIndirectRestore:
2394 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002395 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002396
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002397 case SK_ConversionSequence:
2398 delete ICS;
2399 }
2400}
2401
Douglas Gregor838fcc32010-03-26 20:14:36 +00002402bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002403 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002404}
2405
2406bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002407 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002408 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002409
Douglas Gregor838fcc32010-03-26 20:14:36 +00002410 switch (getFailureKind()) {
2411 case FK_TooManyInitsForReference:
2412 case FK_ArrayNeedsInitList:
2413 case FK_ArrayNeedsInitListOrStringLiteral:
2414 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2415 case FK_NonConstLValueReferenceBindingToTemporary:
2416 case FK_NonConstLValueReferenceBindingToUnrelated:
2417 case FK_RValueReferenceBindingToLValue:
2418 case FK_ReferenceInitDropsQualifiers:
2419 case FK_ReferenceInitFailed:
2420 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002421 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002422 case FK_TooManyInitsForScalar:
2423 case FK_ReferenceBindingToInitList:
2424 case FK_InitListBadDestinationType:
2425 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002426 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002427 case FK_ArrayTypeMismatch:
2428 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002429 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002430 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002431 case FK_PlaceholderType:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002432 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002433
Douglas Gregor838fcc32010-03-26 20:14:36 +00002434 case FK_ReferenceInitOverloadFailed:
2435 case FK_UserConversionOverloadFailed:
2436 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002437 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002438 return FailedOverloadResult == OR_Ambiguous;
2439 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002440
Douglas Gregor838fcc32010-03-26 20:14:36 +00002441 return false;
2442}
2443
Douglas Gregorb33eed02010-04-16 22:09:46 +00002444bool InitializationSequence::isConstructorInitialization() const {
2445 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2446}
2447
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002448bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2449 const Expr *Initializer,
2450 bool *isInitializerConstant,
2451 APValue *ConstantValue) const {
2452 if (Steps.empty() || Initializer->isValueDependent())
2453 return false;
2454
2455 const Step &LastStep = Steps.back();
2456 if (LastStep.Kind != SK_ConversionSequence)
2457 return false;
2458
2459 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2460 const StandardConversionSequence *SCS = NULL;
2461 switch (ICS.getKind()) {
2462 case ImplicitConversionSequence::StandardConversion:
2463 SCS = &ICS.Standard;
2464 break;
2465 case ImplicitConversionSequence::UserDefinedConversion:
2466 SCS = &ICS.UserDefined.After;
2467 break;
2468 case ImplicitConversionSequence::AmbiguousConversion:
2469 case ImplicitConversionSequence::EllipsisConversion:
2470 case ImplicitConversionSequence::BadConversion:
2471 return false;
2472 }
2473
2474 // Check if SCS represents a narrowing conversion, according to C++0x
2475 // [dcl.init.list]p7:
2476 //
2477 // A narrowing conversion is an implicit conversion ...
2478 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2479 QualType FromType = SCS->getToType(0);
2480 QualType ToType = SCS->getToType(1);
2481 switch (PossibleNarrowing) {
2482 // * from a floating-point type to an integer type, or
2483 //
2484 // * from an integer type or unscoped enumeration type to a floating-point
2485 // type, except where the source is a constant expression and the actual
2486 // value after conversion will fit into the target type and will produce
2487 // the original value when converted back to the original type, or
2488 case ICK_Floating_Integral:
2489 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2490 *isInitializerConstant = false;
2491 return true;
2492 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2493 llvm::APSInt IntConstantValue;
2494 if (Initializer &&
2495 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2496 // Convert the integer to the floating type.
2497 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2498 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2499 llvm::APFloat::rmNearestTiesToEven);
2500 // And back.
2501 llvm::APSInt ConvertedValue = IntConstantValue;
2502 bool ignored;
2503 Result.convertToInteger(ConvertedValue,
2504 llvm::APFloat::rmTowardZero, &ignored);
2505 // If the resulting value is different, this was a narrowing conversion.
2506 if (IntConstantValue != ConvertedValue) {
2507 *isInitializerConstant = true;
2508 *ConstantValue = APValue(IntConstantValue);
2509 return true;
2510 }
2511 } else {
2512 // Variables are always narrowings.
2513 *isInitializerConstant = false;
2514 return true;
2515 }
2516 }
2517 return false;
2518
2519 // * from long double to double or float, or from double to float, except
2520 // where the source is a constant expression and the actual value after
2521 // conversion is within the range of values that can be represented (even
2522 // if it cannot be represented exactly), or
2523 case ICK_Floating_Conversion:
2524 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2525 // FromType is larger than ToType.
2526 Expr::EvalResult InitializerValue;
2527 // FIXME: Check whether Initializer is a constant expression according
2528 // to C++0x [expr.const], rather than just whether it can be folded.
Richard Smith7b553f12011-10-29 00:50:52 +00002529 if (Initializer->EvaluateAsRValue(InitializerValue, Ctx) &&
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002530 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2531 // Constant! (Except for FIXME above.)
2532 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2533 // Convert the source value into the target type.
2534 bool ignored;
2535 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2536 Ctx.getFloatTypeSemantics(ToType),
2537 llvm::APFloat::rmNearestTiesToEven, &ignored);
2538 // If there was no overflow, the source value is within the range of
2539 // values that can be represented.
2540 if (ConvertStatus & llvm::APFloat::opOverflow) {
2541 *isInitializerConstant = true;
2542 *ConstantValue = InitializerValue.Val;
2543 return true;
2544 }
2545 } else {
2546 *isInitializerConstant = false;
2547 return true;
2548 }
2549 }
2550 return false;
2551
2552 // * from an integer type or unscoped enumeration type to an integer type
2553 // that cannot represent all the values of the original type, except where
2554 // the source is a constant expression and the actual value after
2555 // conversion will fit into the target type and will produce the original
2556 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002557 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002558 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2559 // Boolean conversions can be from pointers and pointers to members
2560 // [conv.bool], and those aren't considered narrowing conversions.
2561 return false;
2562 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002563 case ICK_Integral_Conversion: {
2564 assert(FromType->isIntegralOrUnscopedEnumerationType());
2565 assert(ToType->isIntegralOrUnscopedEnumerationType());
2566 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2567 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2568 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2569 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2570
2571 if (FromWidth > ToWidth ||
2572 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2573 // Not all values of FromType can be represented in ToType.
2574 llvm::APSInt InitializerValue;
2575 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2576 *isInitializerConstant = true;
2577 *ConstantValue = APValue(InitializerValue);
2578
2579 // Add a bit to the InitializerValue so we don't have to worry about
2580 // signed vs. unsigned comparisons.
2581 InitializerValue = InitializerValue.extend(
2582 InitializerValue.getBitWidth() + 1);
2583 // Convert the initializer to and from the target width and signed-ness.
2584 llvm::APSInt ConvertedValue = InitializerValue;
2585 ConvertedValue = ConvertedValue.trunc(ToWidth);
2586 ConvertedValue.setIsSigned(ToSigned);
2587 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2588 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2589 // If the result is different, this was a narrowing conversion.
2590 return ConvertedValue != InitializerValue;
2591 } else {
2592 // Variables are always narrowings.
2593 *isInitializerConstant = false;
2594 return true;
2595 }
2596 }
2597 return false;
2598 }
2599
2600 default:
2601 // Other kinds of conversions are not narrowings.
2602 return false;
2603 }
2604}
2605
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002606void
2607InitializationSequence
2608::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2609 DeclAccessPair Found,
2610 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002611 Step S;
2612 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2613 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002614 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002615 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002616 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002617 Steps.push_back(S);
2618}
2619
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002620void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002621 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002622 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002623 switch (VK) {
2624 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2625 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2626 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002627 default: llvm_unreachable("No such category");
2628 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002629 S.Type = BaseType;
2630 Steps.push_back(S);
2631}
2632
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002633void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002634 bool BindingTemporary) {
2635 Step S;
2636 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2637 S.Type = T;
2638 Steps.push_back(S);
2639}
2640
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002641void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2642 Step S;
2643 S.Kind = SK_ExtraneousCopyToTemporary;
2644 S.Type = T;
2645 Steps.push_back(S);
2646}
2647
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002648void
2649InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2650 DeclAccessPair FoundDecl,
2651 QualType T,
2652 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653 Step S;
2654 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002655 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002656 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002657 S.Function.Function = Function;
2658 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002659 Steps.push_back(S);
2660}
2661
2662void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002663 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002664 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002665 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002666 switch (VK) {
2667 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002668 S.Kind = SK_QualificationConversionRValue;
2669 break;
John McCall2536c6d2010-08-25 10:28:54 +00002670 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002671 S.Kind = SK_QualificationConversionXValue;
2672 break;
John McCall2536c6d2010-08-25 10:28:54 +00002673 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002674 S.Kind = SK_QualificationConversionLValue;
2675 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002676 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002677 S.Type = Ty;
2678 Steps.push_back(S);
2679}
2680
2681void InitializationSequence::AddConversionSequenceStep(
2682 const ImplicitConversionSequence &ICS,
2683 QualType T) {
2684 Step S;
2685 S.Kind = SK_ConversionSequence;
2686 S.Type = T;
2687 S.ICS = new ImplicitConversionSequence(ICS);
2688 Steps.push_back(S);
2689}
2690
Douglas Gregor51e77d52009-12-10 17:56:55 +00002691void InitializationSequence::AddListInitializationStep(QualType T) {
2692 Step S;
2693 S.Kind = SK_ListInitialization;
2694 S.Type = T;
2695 Steps.push_back(S);
2696}
2697
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002698void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002699InitializationSequence
2700::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2701 AccessSpecifier Access,
2702 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002703 bool HadMultipleCandidates,
2704 bool FromInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002705 Step S;
Sebastian Redled2e5322011-12-22 14:44:04 +00002706 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002707 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002708 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002709 S.Function.Function = Constructor;
2710 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002711 Steps.push_back(S);
2712}
2713
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002714void InitializationSequence::AddZeroInitializationStep(QualType T) {
2715 Step S;
2716 S.Kind = SK_ZeroInitialization;
2717 S.Type = T;
2718 Steps.push_back(S);
2719}
2720
Douglas Gregore1314a62009-12-18 05:02:21 +00002721void InitializationSequence::AddCAssignmentStep(QualType T) {
2722 Step S;
2723 S.Kind = SK_CAssignment;
2724 S.Type = T;
2725 Steps.push_back(S);
2726}
2727
Eli Friedman78275202009-12-19 08:11:05 +00002728void InitializationSequence::AddStringInitStep(QualType T) {
2729 Step S;
2730 S.Kind = SK_StringInit;
2731 S.Type = T;
2732 Steps.push_back(S);
2733}
2734
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002735void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2736 Step S;
2737 S.Kind = SK_ObjCObjectConversion;
2738 S.Type = T;
2739 Steps.push_back(S);
2740}
2741
Douglas Gregore2f943b2011-02-22 18:29:51 +00002742void InitializationSequence::AddArrayInitStep(QualType T) {
2743 Step S;
2744 S.Kind = SK_ArrayInit;
2745 S.Type = T;
2746 Steps.push_back(S);
2747}
2748
John McCall31168b02011-06-15 23:02:42 +00002749void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2750 bool shouldCopy) {
2751 Step s;
2752 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2753 : SK_PassByIndirectRestore);
2754 s.Type = type;
2755 Steps.push_back(s);
2756}
2757
2758void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2759 Step S;
2760 S.Kind = SK_ProduceObjCObject;
2761 S.Type = T;
2762 Steps.push_back(S);
2763}
2764
Sebastian Redl29526f02011-11-27 16:50:07 +00002765void InitializationSequence::RewrapReferenceInitList(QualType T,
2766 InitListExpr *Syntactic) {
2767 assert(Syntactic->getNumInits() == 1 &&
2768 "Can only rewrap trivial init lists.");
2769 Step S;
2770 S.Kind = SK_UnwrapInitList;
2771 S.Type = Syntactic->getInit(0)->getType();
2772 Steps.insert(Steps.begin(), S);
2773
2774 S.Kind = SK_RewrapInitList;
2775 S.Type = T;
2776 S.WrappingSyntacticList = Syntactic;
2777 Steps.push_back(S);
2778}
2779
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002781 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002782 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002783 this->Failure = Failure;
2784 this->FailedOverloadResult = Result;
2785}
2786
2787//===----------------------------------------------------------------------===//
2788// Attempt initialization
2789//===----------------------------------------------------------------------===//
2790
John McCall31168b02011-06-15 23:02:42 +00002791static void MaybeProduceObjCObject(Sema &S,
2792 InitializationSequence &Sequence,
2793 const InitializedEntity &Entity) {
2794 if (!S.getLangOptions().ObjCAutoRefCount) return;
2795
2796 /// When initializing a parameter, produce the value if it's marked
2797 /// __attribute__((ns_consumed)).
2798 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2799 if (!Entity.isParameterConsumed())
2800 return;
2801
2802 assert(Entity.getType()->isObjCRetainableType() &&
2803 "consuming an object of unretainable type?");
2804 Sequence.AddProduceObjCObjectStep(Entity.getType());
2805
2806 /// When initializing a return value, if the return type is a
2807 /// retainable type, then returns need to immediately retain the
2808 /// object. If an autorelease is required, it will be done at the
2809 /// last instant.
2810 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2811 if (!Entity.getType()->isObjCRetainableType())
2812 return;
2813
2814 Sequence.AddProduceObjCObjectStep(Entity.getType());
2815 }
2816}
2817
Sebastian Redled2e5322011-12-22 14:44:04 +00002818/// \brief When initializing from init list via constructor, deal with the
2819/// empty init list and std::initializer_list special cases.
2820///
2821/// \return True if this was a special case, false otherwise.
2822static bool TryListConstructionSpecialCases(Sema &S,
2823 Expr **Args, unsigned NumArgs,
2824 CXXRecordDecl *DestRecordDecl,
2825 QualType DestType,
2826 InitializationSequence &Sequence) {
2827 // C++0x [dcl.init.list]p3:
2828 // List-initialization of an object of type T is defined as follows:
2829 // - If the initializer list has no elements and T is a class type with
2830 // a default constructor, the object is value-initialized.
2831 if (NumArgs == 0) {
2832 if (CXXConstructorDecl *DefaultConstructor =
2833 S.LookupDefaultConstructor(DestRecordDecl)) {
2834 if (DefaultConstructor->isDeleted() ||
2835 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2836 // Fake an overload resolution failure.
2837 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2838 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2839 DefaultConstructor->getAccess());
2840 if (FunctionTemplateDecl *ConstructorTmpl =
2841 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2842 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2843 /*ExplicitArgs*/ 0,
2844 Args, NumArgs, CandidateSet,
2845 /*SuppressUserConversions*/ false);
2846 else
2847 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2848 Args, NumArgs, CandidateSet,
2849 /*SuppressUserConversions*/ false);
2850 Sequence.SetOverloadFailure(
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002851 InitializationSequence::FK_ListConstructorOverloadFailed,
2852 OR_Deleted);
Sebastian Redled2e5322011-12-22 14:44:04 +00002853 } else
2854 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2855 DefaultConstructor->getAccess(),
2856 DestType,
2857 /*MultipleCandidates=*/false,
2858 /*FromInitList=*/true);
2859 return true;
2860 }
2861 }
2862
2863 // - Otherwise, if T is a specialization of std::initializer_list, [...]
2864 // FIXME: Implement.
2865
2866 // Not a special case.
2867 return false;
2868}
2869
2870/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2871/// enumerates the constructors of the initialized entity and performs overload
2872/// resolution to select the best.
2873/// If FromInitList is true, this is list-initialization of a non-aggregate
2874/// class type.
2875static void TryConstructorInitialization(Sema &S,
2876 const InitializedEntity &Entity,
2877 const InitializationKind &Kind,
2878 Expr **Args, unsigned NumArgs,
2879 QualType DestType,
2880 InitializationSequence &Sequence,
2881 bool FromInitList = false) {
2882 // Check constructor arguments for self reference.
2883 if (DeclaratorDecl *DD = Entity.getDecl())
2884 // Parameters arguments are occassionially constructed with itself,
2885 // for instance, in recursive functions. Skip them.
2886 if (!isa<ParmVarDecl>(DD))
2887 for (unsigned i = 0; i < NumArgs; ++i)
2888 S.CheckSelfReference(DD, Args[i]);
2889
2890 // Build the candidate set directly in the initialization sequence
2891 // structure, so that it will persist if we fail.
2892 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2893 CandidateSet.clear();
2894
2895 // Determine whether we are allowed to call explicit constructors or
2896 // explicit conversion operators.
2897 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2898 Kind.getKind() == InitializationKind::IK_Value ||
2899 Kind.getKind() == InitializationKind::IK_Default);
2900
2901 // The type we're constructing needs to be complete.
2902 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2903 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2904 }
2905
2906 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2907 assert(DestRecordType && "Constructor initialization requires record type");
2908 CXXRecordDecl *DestRecordDecl
2909 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2910
2911 if (FromInitList &&
2912 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2913 DestType, Sequence))
2914 return;
2915
2916 // - Otherwise, if T is a class type, constructors are considered. The
2917 // applicable constructors are enumerated, and the best one is chosen
2918 // through overload resolution.
2919 DeclContext::lookup_iterator Con, ConEnd;
2920 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2921 Con != ConEnd; ++Con) {
2922 NamedDecl *D = *Con;
2923 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2924 bool SuppressUserConversions = false;
2925
2926 // Find the constructor (which may be a template).
2927 CXXConstructorDecl *Constructor = 0;
2928 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2929 if (ConstructorTmpl)
2930 Constructor = cast<CXXConstructorDecl>(
2931 ConstructorTmpl->getTemplatedDecl());
2932 else {
2933 Constructor = cast<CXXConstructorDecl>(D);
2934
2935 // If we're performing copy initialization using a copy constructor, we
2936 // suppress user-defined conversions on the arguments.
2937 // FIXME: Move constructors?
2938 if (Kind.getKind() == InitializationKind::IK_Copy &&
2939 Constructor->isCopyConstructor())
2940 SuppressUserConversions = true;
2941 }
2942
2943 if (!Constructor->isInvalidDecl() &&
2944 (AllowExplicit || !Constructor->isExplicit())) {
2945 if (ConstructorTmpl)
2946 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2947 /*ExplicitArgs*/ 0,
2948 Args, NumArgs, CandidateSet,
2949 SuppressUserConversions);
2950 else
2951 S.AddOverloadCandidate(Constructor, FoundDecl,
2952 Args, NumArgs, CandidateSet,
2953 SuppressUserConversions);
2954 }
2955 }
2956
2957 SourceLocation DeclLoc = Kind.getLocation();
2958
2959 // Perform overload resolution. If it fails, return the failed result.
2960 OverloadCandidateSet::iterator Best;
2961 if (OverloadingResult Result
2962 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002963 Sequence.SetOverloadFailure(FromInitList ?
2964 InitializationSequence::FK_ListConstructorOverloadFailed :
2965 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00002966 Result);
2967 return;
2968 }
2969
2970 // C++0x [dcl.init]p6:
2971 // If a program calls for the default initialization of an object
2972 // of a const-qualified type T, T shall be a class type with a
2973 // user-provided default constructor.
2974 if (Kind.getKind() == InitializationKind::IK_Default &&
2975 Entity.getType().isConstQualified() &&
2976 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2977 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2978 return;
2979 }
2980
2981 // Add the constructor initialization step. Any cv-qualification conversion is
2982 // subsumed by the initialization.
2983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2984 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2985 Sequence.AddConstructorInitializationStep(CtorDecl,
2986 Best->FoundDecl.getAccess(),
2987 DestType, HadMultipleCandidates,
2988 FromInitList);
2989}
2990
Sebastian Redl29526f02011-11-27 16:50:07 +00002991static bool
2992ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2993 Expr *Initializer,
2994 QualType &SourceType,
2995 QualType &UnqualifiedSourceType,
2996 QualType UnqualifiedTargetType,
2997 InitializationSequence &Sequence) {
2998 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2999 S.Context.OverloadTy) {
3000 DeclAccessPair Found;
3001 bool HadMultipleCandidates = false;
3002 if (FunctionDecl *Fn
3003 = S.ResolveAddressOfOverloadedFunction(Initializer,
3004 UnqualifiedTargetType,
3005 false, Found,
3006 &HadMultipleCandidates)) {
3007 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3008 HadMultipleCandidates);
3009 SourceType = Fn->getType();
3010 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3011 } else if (!UnqualifiedTargetType->isRecordType()) {
3012 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3013 return true;
3014 }
3015 }
3016 return false;
3017}
3018
3019static void TryReferenceInitializationCore(Sema &S,
3020 const InitializedEntity &Entity,
3021 const InitializationKind &Kind,
3022 Expr *Initializer,
3023 QualType cv1T1, QualType T1,
3024 Qualifiers T1Quals,
3025 QualType cv2T2, QualType T2,
3026 Qualifiers T2Quals,
3027 InitializationSequence &Sequence);
3028
3029static void TryListInitialization(Sema &S,
3030 const InitializedEntity &Entity,
3031 const InitializationKind &Kind,
3032 InitListExpr *InitList,
3033 InitializationSequence &Sequence);
3034
3035/// \brief Attempt list initialization of a reference.
3036static void TryReferenceListInitialization(Sema &S,
3037 const InitializedEntity &Entity,
3038 const InitializationKind &Kind,
3039 InitListExpr *InitList,
3040 InitializationSequence &Sequence)
3041{
3042 // First, catch C++03 where this isn't possible.
3043 if (!S.getLangOptions().CPlusPlus0x) {
3044 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3045 return;
3046 }
3047
3048 QualType DestType = Entity.getType();
3049 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3050 Qualifiers T1Quals;
3051 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3052
3053 // Reference initialization via an initializer list works thus:
3054 // If the initializer list consists of a single element that is
3055 // reference-related to the referenced type, bind directly to that element
3056 // (possibly creating temporaries).
3057 // Otherwise, initialize a temporary with the initializer list and
3058 // bind to that.
3059 if (InitList->getNumInits() == 1) {
3060 Expr *Initializer = InitList->getInit(0);
3061 QualType cv2T2 = Initializer->getType();
3062 Qualifiers T2Quals;
3063 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3064
3065 // If this fails, creating a temporary wouldn't work either.
3066 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3067 T1, Sequence))
3068 return;
3069
3070 SourceLocation DeclLoc = Initializer->getLocStart();
3071 bool dummy1, dummy2, dummy3;
3072 Sema::ReferenceCompareResult RefRelationship
3073 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3074 dummy2, dummy3);
3075 if (RefRelationship >= Sema::Ref_Related) {
3076 // Try to bind the reference here.
3077 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3078 T1Quals, cv2T2, T2, T2Quals, Sequence);
3079 if (Sequence)
3080 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3081 return;
3082 }
3083 }
3084
3085 // Not reference-related. Create a temporary and bind to that.
3086 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3087
3088 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3089 if (Sequence) {
3090 if (DestType->isRValueReferenceType() ||
3091 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3092 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3093 else
3094 Sequence.SetFailed(
3095 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3096 }
3097}
3098
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003099/// \brief Attempt list initialization (C++0x [dcl.init.list])
3100static void TryListInitialization(Sema &S,
3101 const InitializedEntity &Entity,
3102 const InitializationKind &Kind,
3103 InitListExpr *InitList,
3104 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003105 QualType DestType = Entity.getType();
3106
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003107 // C++ doesn't allow scalar initialization with more than one argument.
3108 // But C99 complex numbers are scalars and it makes sense there.
3109 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3110 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3111 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3112 return;
3113 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003114 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003115 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003116 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003117 }
3118 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003119 if (S.getLangOptions().CPlusPlus0x)
3120 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3121 InitList->getNumInits(), DestType, Sequence,
3122 /*FromInitList=*/true);
3123 else
3124 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003125 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003126 }
3127
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003128 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00003129 DestType, /*VerifyOnly=*/true,
3130 Kind.getKind() != InitializationKind::IK_Direct ||
3131 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003132 if (CheckInitList.HadError()) {
3133 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3134 return;
3135 }
3136
3137 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003138 Sequence.AddListInitializationStep(DestType);
3139}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003140
3141/// \brief Try a reference initialization that involves calling a conversion
3142/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003143static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3144 const InitializedEntity &Entity,
3145 const InitializationKind &Kind,
3146 Expr *Initializer,
3147 bool AllowRValues,
3148 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003149 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003150 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3151 QualType T1 = cv1T1.getUnqualifiedType();
3152 QualType cv2T2 = Initializer->getType();
3153 QualType T2 = cv2T2.getUnqualifiedType();
3154
3155 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003156 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003157 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003159 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003160 ObjCConversion,
3161 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003162 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003163 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003164 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003165 (void)ObjCLifetimeConversion;
3166
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003167 // Build the candidate set directly in the initialization sequence
3168 // structure, so that it will persist if we fail.
3169 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3170 CandidateSet.clear();
3171
3172 // Determine whether we are allowed to call explicit constructors or
3173 // explicit conversion operators.
3174 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003176 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003177 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3178 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003179 // The type we're converting to is a class type. Enumerate its constructors
3180 // to see if there is a suitable conversion.
3181 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003182
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003183 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003184 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003185 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003186 NamedDecl *D = *Con;
3187 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3188
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003189 // Find the constructor (which may be a template).
3190 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003191 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003192 if (ConstructorTmpl)
3193 Constructor = cast<CXXConstructorDecl>(
3194 ConstructorTmpl->getTemplatedDecl());
3195 else
John McCalla0296f72010-03-19 07:35:19 +00003196 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003197
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003198 if (!Constructor->isInvalidDecl() &&
3199 Constructor->isConvertingConstructor(AllowExplicit)) {
3200 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003201 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003202 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003203 &Initializer, 1, CandidateSet,
3204 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003205 else
John McCalla0296f72010-03-19 07:35:19 +00003206 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003207 &Initializer, 1, CandidateSet,
3208 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003211 }
John McCall3696dcb2010-08-17 07:23:57 +00003212 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3213 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003214
Douglas Gregor496e8b342010-05-07 19:42:26 +00003215 const RecordType *T2RecordType = 0;
3216 if ((T2RecordType = T2->getAs<RecordType>()) &&
3217 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003218 // The type we're converting from is a class type, enumerate its conversion
3219 // functions.
3220 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3221
John McCallad371252010-01-20 00:46:10 +00003222 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003223 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003224 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3225 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226 NamedDecl *D = *I;
3227 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3228 if (isa<UsingShadowDecl>(D))
3229 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003230
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003231 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3232 CXXConversionDecl *Conv;
3233 if (ConvTemplate)
3234 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3235 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003236 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238 // If the conversion function doesn't return a reference type,
3239 // it can't be considered for this conversion unless we're allowed to
3240 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241 // FIXME: Do we need to make sure that we only consider conversion
3242 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243 // break recursion.
3244 if ((AllowExplicit || !Conv->isExplicit()) &&
3245 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3246 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003247 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003248 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003249 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003250 else
John McCalla0296f72010-03-19 07:35:19 +00003251 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003252 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003253 }
3254 }
3255 }
John McCall3696dcb2010-08-17 07:23:57 +00003256 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3257 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003259 SourceLocation DeclLoc = Initializer->getLocStart();
3260
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003261 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003262 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003263 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003264 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003265 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003267 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003268
Chandler Carruth30141632011-02-25 19:41:05 +00003269 // This is the overload that will actually be used for the initialization, so
3270 // mark it as used.
3271 S.MarkDeclarationReferenced(DeclLoc, Function);
3272
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003273 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003274 if (isa<CXXConversionDecl>(Function))
3275 T2 = Function->getResultType();
3276 else
3277 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003278
3279 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003280 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003281 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003282 T2.getNonLValueExprType(S.Context),
3283 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003284
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003285 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003286 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003287 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003288 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003289 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003290 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003291 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003292
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003293 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003294 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003295 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003296 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003298 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003299 NewDerivedToBase, NewObjCConversion,
3300 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003301 if (NewRefRelationship == Sema::Ref_Incompatible) {
3302 // If the type we've converted to is not reference-related to the
3303 // type we're looking for, then there is another conversion step
3304 // we need to perform to produce a temporary of the right type
3305 // that we'll be binding to.
3306 ImplicitConversionSequence ICS;
3307 ICS.setStandard();
3308 ICS.Standard = Best->FinalConversion;
3309 T2 = ICS.Standard.getToType(2);
3310 Sequence.AddConversionSequenceStep(ICS, T2);
3311 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003312 Sequence.AddDerivedToBaseCastStep(
3313 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003315 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003316 else if (NewObjCConversion)
3317 Sequence.AddObjCObjectConversionStep(
3318 S.Context.getQualifiedType(T1,
3319 T2.getNonReferenceType().getQualifiers()));
3320
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003321 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003322 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003324 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3325 return OR_Success;
3326}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327
Richard Smithc620f552011-10-19 16:55:56 +00003328static void CheckCXX98CompatAccessibleCopy(Sema &S,
3329 const InitializedEntity &Entity,
3330 Expr *CurInitExpr);
3331
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3333static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003334 const InitializedEntity &Entity,
3335 const InitializationKind &Kind,
3336 Expr *Initializer,
3337 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003338 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003339 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003340 Qualifiers T1Quals;
3341 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003342 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003343 Qualifiers T2Quals;
3344 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003345
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003346 // If the initializer is the address of an overloaded function, try
3347 // to resolve the overloaded function. If all goes well, T2 is the
3348 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003349 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3350 T1, Sequence))
3351 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003352
Sebastian Redl29526f02011-11-27 16:50:07 +00003353 // Delegate everything else to a subfunction.
3354 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3355 T1Quals, cv2T2, T2, T2Quals, Sequence);
3356}
3357
3358/// \brief Reference initialization without resolving overloaded functions.
3359static void TryReferenceInitializationCore(Sema &S,
3360 const InitializedEntity &Entity,
3361 const InitializationKind &Kind,
3362 Expr *Initializer,
3363 QualType cv1T1, QualType T1,
3364 Qualifiers T1Quals,
3365 QualType cv2T2, QualType T2,
3366 Qualifiers T2Quals,
3367 InitializationSequence &Sequence) {
3368 QualType DestType = Entity.getType();
3369 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003370 // Compute some basic properties of the types and the initializer.
3371 bool isLValueRef = DestType->isLValueReferenceType();
3372 bool isRValueRef = !isLValueRef;
3373 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003374 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003375 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003376 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003377 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003378 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003379 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003380
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003381 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003383 // "cv2 T2" as follows:
3384 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003386 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003387 // Note the analogous bullet points for rvlaue refs to functions. Because
3388 // there are no function rvalues in C++, rvalue refs to functions are treated
3389 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003390 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003391 bool T1Function = T1->isFunctionType();
3392 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003394 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003396 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003397 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003398 // reference-compatible with "cv2 T2," or
3399 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003401 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003402 // can occur. However, we do pay attention to whether it is a bit-field
3403 // to decide whether we're actually binding to a temporary created from
3404 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003405 if (DerivedToBase)
3406 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003408 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003409 else if (ObjCConversion)
3410 Sequence.AddObjCObjectConversionStep(
3411 S.Context.getQualifiedType(T1, T2Quals));
3412
Chandler Carruth04bdce62010-01-12 20:32:25 +00003413 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003414 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003415 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003416 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003417 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003418 return;
3419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
3421 // - has a class type (i.e., T2 is a class type), where T1 is not
3422 // reference-related to T2, and can be implicitly converted to an
3423 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3424 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003425 // applicable conversion functions (13.3.1.6) and choosing the best
3426 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003427 // If we have an rvalue ref to function type here, the rhs must be
3428 // an rvalue.
3429 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3430 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003432 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003433 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003434 Sequence);
3435 if (ConvOvlResult == OR_Success)
3436 return;
John McCall0d1da222010-01-12 00:44:57 +00003437 if (ConvOvlResult != OR_No_Viable_Function) {
3438 Sequence.SetOverloadFailure(
3439 InitializationSequence::FK_ReferenceInitOverloadFailed,
3440 ConvOvlResult);
3441 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003442 }
3443 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003444
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003446 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003447 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003448 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003449 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3450 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3451 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003452 Sequence.SetOverloadFailure(
3453 InitializationSequence::FK_ReferenceInitOverloadFailed,
3454 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003455 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003456 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003457 ? (RefRelationship == Sema::Ref_Related
3458 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3459 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3460 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003461
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003462 return;
3463 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003464
Douglas Gregor92e460e2011-01-20 16:44:54 +00003465 // - If the initializer expression
3466 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3467 // "cv1 T1" is reference-compatible with "cv2 T2"
3468 // Note: functions are handled below.
3469 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003470 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003472 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003473 (InitCategory.isXValue() ||
3474 (InitCategory.isPRValue() && T2->isRecordType()) ||
3475 (InitCategory.isPRValue() && T2->isArrayType()))) {
3476 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3477 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003478 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3479 // compiler the freedom to perform a copy here or bind to the
3480 // object, while C++0x requires that we bind directly to the
3481 // object. Hence, we always bind to the object without making an
3482 // extra copy. However, in C++03 requires that we check for the
3483 // presence of a suitable copy constructor:
3484 //
3485 // The constructor that would be used to make the copy shall
3486 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003487 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003488 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smithc620f552011-10-19 16:55:56 +00003489 else if (S.getLangOptions().CPlusPlus0x)
3490 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003492
Douglas Gregor92e460e2011-01-20 16:44:54 +00003493 if (DerivedToBase)
3494 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3495 ValueKind);
3496 else if (ObjCConversion)
3497 Sequence.AddObjCObjectConversionStep(
3498 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499
Douglas Gregor92e460e2011-01-20 16:44:54 +00003500 if (T1Quals != T2Quals)
3501 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbournefcc764d2011-11-13 00:51:30 +00003503 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
3507 // - has a class type (i.e., T2 is a class type), where T1 is not
3508 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003509 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3510 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003511 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003512 if (RefRelationship == Sema::Ref_Incompatible) {
3513 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3514 Kind, Initializer,
3515 /*AllowRValues=*/true,
3516 Sequence);
3517 if (ConvOvlResult)
3518 Sequence.SetOverloadFailure(
3519 InitializationSequence::FK_ReferenceInitOverloadFailed,
3520 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003522 return;
3523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003525 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3526 return;
3527 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003528
3529 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003530 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003533
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003534 // Determine whether we are allowed to call explicit constructors or
3535 // explicit conversion operators.
3536 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003537
3538 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3539
John McCall31168b02011-06-15 23:02:42 +00003540 ImplicitConversionSequence ICS
3541 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003542 /*SuppressUserConversions*/ false,
3543 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003544 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003545 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3546 /*AllowObjCWritebackConversion=*/false);
3547
3548 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003549 // FIXME: Use the conversion function set stored in ICS to turn
3550 // this into an overloading ambiguity diagnostic. However, we need
3551 // to keep that set as an OverloadCandidateSet rather than as some
3552 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003553 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3554 Sequence.SetOverloadFailure(
3555 InitializationSequence::FK_ReferenceInitOverloadFailed,
3556 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003557 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3558 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003559 else
3560 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003561 return;
John McCall31168b02011-06-15 23:02:42 +00003562 } else {
3563 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003564 }
3565
3566 // [...] If T1 is reference-related to T2, cv1 must be the
3567 // same cv-qualification as, or greater cv-qualification
3568 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003569 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3570 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003572 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003573 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3574 return;
3575 }
3576
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003578 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003580 InitCategory.isLValue()) {
3581 Sequence.SetFailed(
3582 InitializationSequence::FK_RValueReferenceBindingToLValue);
3583 return;
3584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003586 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3587 return;
3588}
3589
3590/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591/// (C++ [dcl.init.string], C99 6.7.8).
3592static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003593 const InitializedEntity &Entity,
3594 const InitializationKind &Kind,
3595 Expr *Initializer,
3596 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003597 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003598}
3599
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003600/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003601static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003602 const InitializedEntity &Entity,
3603 const InitializationKind &Kind,
3604 InitializationSequence &Sequence) {
3605 // C++ [dcl.init]p5:
3606 //
3607 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003608 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003610 // -- if T is an array type, then each element is value-initialized;
3611 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3612 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003614 if (const RecordType *RT = T->getAs<RecordType>()) {
3615 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3616 // -- if T is a class type (clause 9) with a user-declared
3617 // constructor (12.1), then the default constructor for T is
3618 // called (and the initialization is ill-formed if T has no
3619 // accessible default constructor);
3620 //
3621 // FIXME: we really want to refer to a single subobject of the array,
3622 // but Entity doesn't have a way to capture that (yet).
3623 if (ClassDecl->hasUserDeclaredConstructor())
3624 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003625
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003626 // -- if T is a (possibly cv-qualified) non-union class type
3627 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003628 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003629 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003630 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003631 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003632 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003633 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003634 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003635 }
3636 }
3637
Douglas Gregor1b303932009-12-22 15:35:07 +00003638 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003639}
3640
Douglas Gregor85dabae2009-12-16 01:38:02 +00003641/// \brief Attempt default initialization (C++ [dcl.init]p6).
3642static void TryDefaultInitialization(Sema &S,
3643 const InitializedEntity &Entity,
3644 const InitializationKind &Kind,
3645 InitializationSequence &Sequence) {
3646 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647
Douglas Gregor85dabae2009-12-16 01:38:02 +00003648 // C++ [dcl.init]p6:
3649 // To default-initialize an object of type T means:
3650 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003651 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3652
Douglas Gregor85dabae2009-12-16 01:38:02 +00003653 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3654 // constructor for T is called (and the initialization is ill-formed if
3655 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003656 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003657 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3658 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660
Douglas Gregor85dabae2009-12-16 01:38:02 +00003661 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
Douglas Gregor85dabae2009-12-16 01:38:02 +00003663 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003665 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003666 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003667 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003668 return;
3669 }
3670
3671 // If the destination type has a lifetime property, zero-initialize it.
3672 if (DestType.getQualifiers().hasObjCLifetime()) {
3673 Sequence.AddZeroInitializationStep(Entity.getType());
3674 return;
3675 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003676}
3677
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003678/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3679/// which enumerates all conversion functions and performs overload resolution
3680/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003681static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003682 const InitializedEntity &Entity,
3683 const InitializationKind &Kind,
3684 Expr *Initializer,
3685 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003686 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003687 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3688 QualType SourceType = Initializer->getType();
3689 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3690 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691
Douglas Gregor540c3b02009-12-14 17:27:33 +00003692 // Build the candidate set directly in the initialization sequence
3693 // structure, so that it will persist if we fail.
3694 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3695 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696
Douglas Gregor540c3b02009-12-14 17:27:33 +00003697 // Determine whether we are allowed to call explicit constructors or
3698 // explicit conversion operators.
3699 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
Douglas Gregor540c3b02009-12-14 17:27:33 +00003701 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3702 // The type we're converting to is a class type. Enumerate its constructors
3703 // to see if there is a suitable conversion.
3704 CXXRecordDecl *DestRecordDecl
3705 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706
Douglas Gregord9848152010-04-26 14:36:57 +00003707 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003709 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003710 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003711 Con != ConEnd; ++Con) {
3712 NamedDecl *D = *Con;
3713 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714
Douglas Gregord9848152010-04-26 14:36:57 +00003715 // Find the constructor (which may be a template).
3716 CXXConstructorDecl *Constructor = 0;
3717 FunctionTemplateDecl *ConstructorTmpl
3718 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003719 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003720 Constructor = cast<CXXConstructorDecl>(
3721 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003722 else
Douglas Gregord9848152010-04-26 14:36:57 +00003723 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724
Douglas Gregord9848152010-04-26 14:36:57 +00003725 if (!Constructor->isInvalidDecl() &&
3726 Constructor->isConvertingConstructor(AllowExplicit)) {
3727 if (ConstructorTmpl)
3728 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3729 /*ExplicitArgs*/ 0,
3730 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003731 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003732 else
3733 S.AddOverloadCandidate(Constructor, FoundDecl,
3734 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003735 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737 }
Douglas Gregord9848152010-04-26 14:36:57 +00003738 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003739 }
Eli Friedman78275202009-12-19 08:11:05 +00003740
3741 SourceLocation DeclLoc = Initializer->getLocStart();
3742
Douglas Gregor540c3b02009-12-14 17:27:33 +00003743 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3744 // The type we're converting from is a class type, enumerate its conversion
3745 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003746
Eli Friedman4afe9a32009-12-20 22:12:03 +00003747 // We can only enumerate the conversion functions for a complete type; if
3748 // the type isn't complete, simply skip this step.
3749 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3750 CXXRecordDecl *SourceRecordDecl
3751 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
John McCallad371252010-01-20 00:46:10 +00003753 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003754 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003755 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003757 I != E; ++I) {
3758 NamedDecl *D = *I;
3759 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3760 if (isa<UsingShadowDecl>(D))
3761 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762
Eli Friedman4afe9a32009-12-20 22:12:03 +00003763 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3764 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003765 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003766 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003767 else
John McCallda4458e2010-03-31 01:36:47 +00003768 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769
Eli Friedman4afe9a32009-12-20 22:12:03 +00003770 if (AllowExplicit || !Conv->isExplicit()) {
3771 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003772 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003773 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003774 CandidateSet);
3775 else
John McCalla0296f72010-03-19 07:35:19 +00003776 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003777 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003778 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003779 }
3780 }
3781 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003782
3783 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003784 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003785 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003786 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003787 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003789 Result);
3790 return;
3791 }
John McCall0d1da222010-01-12 00:44:57 +00003792
Douglas Gregor540c3b02009-12-14 17:27:33 +00003793 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003794 S.MarkDeclarationReferenced(DeclLoc, Function);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003795 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003796
Douglas Gregor540c3b02009-12-14 17:27:33 +00003797 if (isa<CXXConstructorDecl>(Function)) {
3798 // Add the user-defined conversion step. Any cv-qualification conversion is
3799 // subsumed by the initialization.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003800 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3801 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003802 return;
3803 }
3804
3805 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003806 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003807 if (ConvType->getAs<RecordType>()) {
3808 // If we're converting to a class type, there may be an copy if
3809 // the resulting temporary object (possible to create an object of
3810 // a base class type). That copy is not a separate conversion, so
3811 // we just make a note of the actual destination type (possibly a
3812 // base class of the type returned by the conversion function) and
3813 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003814 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3815 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003816 return;
3817 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003818
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003819 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3820 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821
Douglas Gregor5ab11652010-04-17 22:01:05 +00003822 // If the conversion following the call to the conversion function
3823 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003824 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3825 Best->FinalConversion.Third) {
3826 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003827 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003828 ICS.Standard = Best->FinalConversion;
3829 Sequence.AddConversionSequenceStep(ICS, DestType);
3830 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003831}
3832
John McCall31168b02011-06-15 23:02:42 +00003833/// The non-zero enum values here are indexes into diagnostic alternatives.
3834enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3835
3836/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003837static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3838 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003839 // Skip parens.
3840 e = e->IgnoreParens();
3841
3842 // Skip address-of nodes.
3843 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3844 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003845 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003846
3847 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003848 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3849 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003850 case CK_Dependent:
3851 case CK_BitCast:
3852 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003853 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003854 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003855
3856 case CK_ArrayToPointerDecay:
3857 return IIK_nonscalar;
3858
3859 case CK_NullToPointer:
3860 return IIK_okay;
3861
3862 default:
3863 break;
3864 }
3865
3866 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003867 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3868 if (!isAddressOf) return IIK_nonlocal;
3869
3870 VarDecl *var;
3871 if (isa<DeclRefExpr>(e)) {
3872 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3873 if (!var) return IIK_nonlocal;
3874 } else {
3875 var = cast<BlockDeclRefExpr>(e)->getDecl();
3876 }
3877
3878 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003879
3880 // If we have a conditional operator, check both sides.
3881 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003882 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003883 return iik;
3884
John McCall63f84442011-06-27 23:59:58 +00003885 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003886
3887 // These are never scalar.
3888 } else if (isa<ArraySubscriptExpr>(e)) {
3889 return IIK_nonscalar;
3890
3891 // Otherwise, it needs to be a null pointer constant.
3892 } else {
3893 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3894 ? IIK_okay : IIK_nonlocal);
3895 }
3896
3897 return IIK_nonlocal;
3898}
3899
3900/// Check whether the given expression is a valid operand for an
3901/// indirect copy/restore.
3902static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3903 assert(src->isRValue());
3904
John McCall63f84442011-06-27 23:59:58 +00003905 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003906 if (iik == IIK_okay) return;
3907
3908 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3909 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3910 << src->getSourceRange();
3911}
3912
Douglas Gregore2f943b2011-02-22 18:29:51 +00003913/// \brief Determine whether we have compatible array types for the
3914/// purposes of GNU by-copy array initialization.
3915static bool hasCompatibleArrayTypes(ASTContext &Context,
3916 const ArrayType *Dest,
3917 const ArrayType *Source) {
3918 // If the source and destination array types are equivalent, we're
3919 // done.
3920 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3921 return true;
3922
3923 // Make sure that the element types are the same.
3924 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3925 return false;
3926
3927 // The only mismatch we allow is when the destination is an
3928 // incomplete array type and the source is a constant array type.
3929 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3930}
3931
John McCall31168b02011-06-15 23:02:42 +00003932static bool tryObjCWritebackConversion(Sema &S,
3933 InitializationSequence &Sequence,
3934 const InitializedEntity &Entity,
3935 Expr *Initializer) {
3936 bool ArrayDecay = false;
3937 QualType ArgType = Initializer->getType();
3938 QualType ArgPointee;
3939 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3940 ArrayDecay = true;
3941 ArgPointee = ArgArrayType->getElementType();
3942 ArgType = S.Context.getPointerType(ArgPointee);
3943 }
3944
3945 // Handle write-back conversion.
3946 QualType ConvertedArgType;
3947 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3948 ConvertedArgType))
3949 return false;
3950
3951 // We should copy unless we're passing to an argument explicitly
3952 // marked 'out'.
3953 bool ShouldCopy = true;
3954 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3955 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3956
3957 // Do we need an lvalue conversion?
3958 if (ArrayDecay || Initializer->isGLValue()) {
3959 ImplicitConversionSequence ICS;
3960 ICS.setStandard();
3961 ICS.Standard.setAsIdentityConversion();
3962
3963 QualType ResultType;
3964 if (ArrayDecay) {
3965 ICS.Standard.First = ICK_Array_To_Pointer;
3966 ResultType = S.Context.getPointerType(ArgPointee);
3967 } else {
3968 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3969 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3970 }
3971
3972 Sequence.AddConversionSequenceStep(ICS, ResultType);
3973 }
3974
3975 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3976 return true;
3977}
3978
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003979InitializationSequence::InitializationSequence(Sema &S,
3980 const InitializedEntity &Entity,
3981 const InitializationKind &Kind,
3982 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003983 unsigned NumArgs)
3984 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003985 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003987 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988 // The semantics of initializers are as follows. The destination type is
3989 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003990 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003992 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003993 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003994
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003995 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003996 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3997 SequenceKind = DependentSequence;
3998 return;
3999 }
4000
Sebastian Redld201edf2011-06-05 13:59:11 +00004001 // Almost everything is a normal sequence.
4002 setSequenceKind(NormalSequence);
4003
John McCalled75c092010-12-07 22:54:16 +00004004 for (unsigned I = 0; I != NumArgs; ++I)
John McCalld5c98ae2011-11-15 01:35:18 +00004005 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +00004006 // FIXME: should we be doing this here?
John McCalld5c98ae2011-11-15 01:35:18 +00004007 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4008 if (result.isInvalid()) {
4009 SetFailed(FK_PlaceholderType);
4010 return;
John McCall4124c492011-10-17 18:40:02 +00004011 }
John McCalld5c98ae2011-11-15 01:35:18 +00004012 Args[I] = result.take();
John Wiegley01296292011-04-08 18:41:53 +00004013 }
John McCalled75c092010-12-07 22:54:16 +00004014
John McCall4124c492011-10-17 18:40:02 +00004015
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004016 QualType SourceType;
4017 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004018 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004019 Initializer = Args[0];
4020 if (!isa<InitListExpr>(Initializer))
4021 SourceType = Initializer->getType();
4022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023
4024 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004025 // list-initialized (8.5.4).
4026 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004027 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004028 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004031 // - If the destination type is a reference type, see 8.5.3.
4032 if (DestType->isReferenceType()) {
4033 // C++0x [dcl.init.ref]p1:
4034 // A variable declared to be a T& or T&&, that is, "reference to type T"
4035 // (8.3.2), shall be initialized by an object, or function, of type T or
4036 // by an object that can be converted into a T.
4037 // (Therefore, multiple arguments are not permitted.)
4038 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004039 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004040 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004041 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004042 return;
4043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004045 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004046 if (Kind.getKind() == InitializationKind::IK_Value ||
4047 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004048 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004049 return;
4050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051
Douglas Gregor85dabae2009-12-16 01:38:02 +00004052 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004053 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004054 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004055 return;
4056 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004057
John McCall66884dd2011-02-21 07:22:22 +00004058 // - If the destination type is an array of characters, an array of
4059 // char16_t, an array of char32_t, or an array of wchar_t, and the
4060 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004061 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004062 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004063 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004064 if (Initializer && isa<VariableArrayType>(DestAT)) {
4065 SetFailed(FK_VariableLengthArrayHasInitializer);
4066 return;
4067 }
4068
Douglas Gregore2f943b2011-02-22 18:29:51 +00004069 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004070 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00004071 return;
4072 }
4073
Douglas Gregore2f943b2011-02-22 18:29:51 +00004074 // Note: as an GNU C extension, we allow initialization of an
4075 // array from a compound literal that creates an array of the same
4076 // type, so long as the initializer has no side effects.
4077 if (!S.getLangOptions().CPlusPlus && Initializer &&
4078 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4079 Initializer->getType()->isArrayType()) {
4080 const ArrayType *SourceAT
4081 = Context.getAsArrayType(Initializer->getType());
4082 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004083 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004084 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004085 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004086 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004087 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004088 }
4089 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004090 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004091 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004092 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004093
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004094 return;
4095 }
Eli Friedman78275202009-12-19 08:11:05 +00004096
John McCall31168b02011-06-15 23:02:42 +00004097 // Determine whether we should consider writeback conversions for
4098 // Objective-C ARC.
4099 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4100 Entity.getKind() == InitializedEntity::EK_Parameter;
4101
4102 // We're at the end of the line for C: it's either a write-back conversion
4103 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00004104 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004105 // If allowed, check whether this is an Objective-C writeback conversion.
4106 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004107 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004108 return;
4109 }
4110
4111 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004112 AddCAssignmentStep(DestType);
4113 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004114 return;
4115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116
John McCall31168b02011-06-15 23:02:42 +00004117 assert(S.getLangOptions().CPlusPlus);
4118
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004119 // - If the destination type is a (possibly cv-qualified) class type:
4120 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121 // - If the initialization is direct-initialization, or if it is
4122 // copy-initialization where the cv-unqualified version of the
4123 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004124 // class of the destination, constructors are considered. [...]
4125 if (Kind.getKind() == InitializationKind::IK_Direct ||
4126 (Kind.getKind() == InitializationKind::IK_Copy &&
4127 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4128 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004129 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004130 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004132 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004134 // used) to a derived class thereof are enumerated as described in
4135 // 13.3.1.4, and the best one is chosen through overload resolution
4136 // (13.3).
4137 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004138 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004139 return;
4140 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141
Douglas Gregor85dabae2009-12-16 01:38:02 +00004142 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004143 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004144 return;
4145 }
4146 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147
4148 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004149 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004150 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004151 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4152 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004153 return;
4154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004156 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004157 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004158 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004160 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004161
4162 ImplicitConversionSequence ICS
4163 = S.TryImplicitConversion(Initializer, Entity.getType(),
4164 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004165 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004166 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004167 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4168 allowObjCWritebackConversion);
4169
4170 if (ICS.isStandard() &&
4171 ICS.Standard.Second == ICK_Writeback_Conversion) {
4172 // Objective-C ARC writeback conversion.
4173
4174 // We should copy unless we're passing to an argument explicitly
4175 // marked 'out'.
4176 bool ShouldCopy = true;
4177 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4178 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4179
4180 // If there was an lvalue adjustment, add it as a separate conversion.
4181 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4182 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4183 ImplicitConversionSequence LvalueICS;
4184 LvalueICS.setStandard();
4185 LvalueICS.Standard.setAsIdentityConversion();
4186 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4187 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004188 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004189 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004190
4191 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004192 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004193 DeclAccessPair dap;
4194 if (Initializer->getType() == Context.OverloadTy &&
4195 !S.ResolveAddressOfOverloadedFunction(Initializer
4196 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004197 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004198 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004199 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004200 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004201 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00004202
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004203 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004204 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004205}
4206
4207InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004208 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004209 StepEnd = Steps.end();
4210 Step != StepEnd; ++Step)
4211 Step->Destroy();
4212}
4213
4214//===----------------------------------------------------------------------===//
4215// Perform initialization
4216//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004218getAssignmentAction(const InitializedEntity &Entity) {
4219 switch(Entity.getKind()) {
4220 case InitializedEntity::EK_Variable:
4221 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004222 case InitializedEntity::EK_Exception:
4223 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004224 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004225 return Sema::AA_Initializing;
4226
4227 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004228 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004229 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4230 return Sema::AA_Sending;
4231
Douglas Gregore1314a62009-12-18 05:02:21 +00004232 return Sema::AA_Passing;
4233
4234 case InitializedEntity::EK_Result:
4235 return Sema::AA_Returning;
4236
Douglas Gregore1314a62009-12-18 05:02:21 +00004237 case InitializedEntity::EK_Temporary:
4238 // FIXME: Can we tell apart casting vs. converting?
4239 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240
Douglas Gregore1314a62009-12-18 05:02:21 +00004241 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004242 case InitializedEntity::EK_ArrayElement:
4243 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004244 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004245 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004246 return Sema::AA_Initializing;
4247 }
4248
4249 return Sema::AA_Converting;
4250}
4251
Douglas Gregor95562572010-04-24 23:45:46 +00004252/// \brief Whether we should binding a created object as a temporary when
4253/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004254static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004255 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004256 case InitializedEntity::EK_ArrayElement:
4257 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004258 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004259 case InitializedEntity::EK_New:
4260 case InitializedEntity::EK_Variable:
4261 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004262 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004263 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004264 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004265 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004266 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004267 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregore1314a62009-12-18 05:02:21 +00004269 case InitializedEntity::EK_Parameter:
4270 case InitializedEntity::EK_Temporary:
4271 return true;
4272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273
Douglas Gregore1314a62009-12-18 05:02:21 +00004274 llvm_unreachable("missed an InitializedEntity kind?");
4275}
4276
Douglas Gregor95562572010-04-24 23:45:46 +00004277/// \brief Whether the given entity, when initialized with an object
4278/// created for that initialization, requires destruction.
4279static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4280 switch (Entity.getKind()) {
4281 case InitializedEntity::EK_Member:
4282 case InitializedEntity::EK_Result:
4283 case InitializedEntity::EK_New:
4284 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004285 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004286 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004287 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004288 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004289 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
Douglas Gregor95562572010-04-24 23:45:46 +00004291 case InitializedEntity::EK_Variable:
4292 case InitializedEntity::EK_Parameter:
4293 case InitializedEntity::EK_Temporary:
4294 case InitializedEntity::EK_ArrayElement:
4295 case InitializedEntity::EK_Exception:
4296 return true;
4297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298
4299 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004300}
4301
Richard Smithc620f552011-10-19 16:55:56 +00004302/// \brief Look for copy and move constructors and constructor templates, for
4303/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4304static void LookupCopyAndMoveConstructors(Sema &S,
4305 OverloadCandidateSet &CandidateSet,
4306 CXXRecordDecl *Class,
4307 Expr *CurInitExpr) {
4308 DeclContext::lookup_iterator Con, ConEnd;
4309 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4310 Con != ConEnd; ++Con) {
4311 CXXConstructorDecl *Constructor = 0;
4312
4313 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4314 // Handle copy/moveconstructors, only.
4315 if (!Constructor || Constructor->isInvalidDecl() ||
4316 !Constructor->isCopyOrMoveConstructor() ||
4317 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4318 continue;
4319
4320 DeclAccessPair FoundDecl
4321 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4322 S.AddOverloadCandidate(Constructor, FoundDecl,
4323 &CurInitExpr, 1, CandidateSet);
4324 continue;
4325 }
4326
4327 // Handle constructor templates.
4328 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4329 if (ConstructorTmpl->isInvalidDecl())
4330 continue;
4331
4332 Constructor = cast<CXXConstructorDecl>(
4333 ConstructorTmpl->getTemplatedDecl());
4334 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4335 continue;
4336
4337 // FIXME: Do we need to limit this to copy-constructor-like
4338 // candidates?
4339 DeclAccessPair FoundDecl
4340 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4341 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4342 &CurInitExpr, 1, CandidateSet, true);
4343 }
4344}
4345
4346/// \brief Get the location at which initialization diagnostics should appear.
4347static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4348 Expr *Initializer) {
4349 switch (Entity.getKind()) {
4350 case InitializedEntity::EK_Result:
4351 return Entity.getReturnLoc();
4352
4353 case InitializedEntity::EK_Exception:
4354 return Entity.getThrowLoc();
4355
4356 case InitializedEntity::EK_Variable:
4357 return Entity.getDecl()->getLocation();
4358
4359 case InitializedEntity::EK_ArrayElement:
4360 case InitializedEntity::EK_Member:
4361 case InitializedEntity::EK_Parameter:
4362 case InitializedEntity::EK_Temporary:
4363 case InitializedEntity::EK_New:
4364 case InitializedEntity::EK_Base:
4365 case InitializedEntity::EK_Delegating:
4366 case InitializedEntity::EK_VectorElement:
4367 case InitializedEntity::EK_ComplexElement:
4368 case InitializedEntity::EK_BlockElement:
4369 return Initializer->getLocStart();
4370 }
4371 llvm_unreachable("missed an InitializedEntity kind?");
4372}
4373
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004374/// \brief Make a (potentially elidable) temporary copy of the object
4375/// provided by the given initializer by calling the appropriate copy
4376/// constructor.
4377///
4378/// \param S The Sema object used for type-checking.
4379///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004380/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004381/// the type of the initializer expression or a superclass thereof.
4382///
4383/// \param Enter The entity being initialized.
4384///
4385/// \param CurInit The initializer expression.
4386///
4387/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4388/// is permitted in C++03 (but not C++0x) when binding a reference to
4389/// an rvalue.
4390///
4391/// \returns An expression that copies the initializer expression into
4392/// a temporary object, or an error expression if a copy could not be
4393/// created.
John McCalldadc5752010-08-24 06:29:42 +00004394static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004395 QualType T,
4396 const InitializedEntity &Entity,
4397 ExprResult CurInit,
4398 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004399 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004400 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004402 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004403 Class = cast<CXXRecordDecl>(Record->getDecl());
4404 if (!Class)
4405 return move(CurInit);
4406
Douglas Gregor5d369002011-01-21 18:05:27 +00004407 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004408 // When certain criteria are met, an implementation is allowed to
4409 // omit the copy/move construction of a class object, even if the
4410 // copy/move constructor and/or destructor for the object have
4411 // side effects. [...]
4412 // - when a temporary class object that has not been bound to a
4413 // reference (12.2) would be copied/moved to a class object
4414 // with the same cv-unqualified type, the copy/move operation
4415 // can be omitted by constructing the temporary object
4416 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004418 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004419 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004421 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004422 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004423 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004424
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004426 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4427 return move(CurInit);
4428
Douglas Gregorf282a762011-01-21 19:38:21 +00004429 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004430 // Only consider constructors and constructor templates. Per
4431 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4432 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004433 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004434 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004436 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4437
Douglas Gregore1314a62009-12-18 05:02:21 +00004438 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004439 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004440 case OR_Success:
4441 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442
Douglas Gregore1314a62009-12-18 05:02:21 +00004443 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004444 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4445 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4446 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004447 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004448 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004449 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004450 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004451 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004452 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453
Douglas Gregore1314a62009-12-18 05:02:21 +00004454 case OR_Ambiguous:
4455 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004456 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004457 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004458 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004459 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460
Douglas Gregore1314a62009-12-18 05:02:21 +00004461 case OR_Deleted:
4462 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004463 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004464 << CurInitExpr->getSourceRange();
4465 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004466 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004467 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004468 }
4469
Douglas Gregor5ab11652010-04-17 22:01:05 +00004470 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004471 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004472 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004473
Anders Carlssona01874b2010-04-21 18:47:17 +00004474 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004475 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004476
4477 if (IsExtraneousCopy) {
4478 // If this is a totally extraneous copy for C++03 reference
4479 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004480 // expression. We don't generate an (elided) copy operation here
4481 // because doing so would require us to pass down a flag to avoid
4482 // infinite recursion, where each step adds another extraneous,
4483 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004484
Douglas Gregor30b52772010-04-18 07:57:34 +00004485 // Instantiate the default arguments of any extra parameters in
4486 // the selected copy constructor, as if we were going to create a
4487 // proper call to the copy constructor.
4488 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4489 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4490 if (S.RequireCompleteType(Loc, Parm->getType(),
4491 S.PDiag(diag::err_call_incomplete_argument)))
4492 break;
4493
4494 // Build the default argument expression; we don't actually care
4495 // if this succeeds or not, because this routine will complain
4496 // if there was a problem.
4497 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4498 }
4499
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004500 return S.Owned(CurInitExpr);
4501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004502
Chandler Carruth30141632011-02-25 19:41:05 +00004503 S.MarkDeclarationReferenced(Loc, Constructor);
4504
Douglas Gregor5ab11652010-04-17 22:01:05 +00004505 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004506 // constructor call (we might have derived-to-base conversions, or
4507 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004508 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004509 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004510 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004511
Douglas Gregord0ace022010-04-25 00:55:24 +00004512 // Actually perform the constructor call.
4513 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004514 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004515 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004516 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004517 CXXConstructExpr::CK_Complete,
4518 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519
Douglas Gregord0ace022010-04-25 00:55:24 +00004520 // If we're supposed to bind temporaries, do so.
4521 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4522 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4523 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004524}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004525
Richard Smithc620f552011-10-19 16:55:56 +00004526/// \brief Check whether elidable copy construction for binding a reference to
4527/// a temporary would have succeeded if we were building in C++98 mode, for
4528/// -Wc++98-compat.
4529static void CheckCXX98CompatAccessibleCopy(Sema &S,
4530 const InitializedEntity &Entity,
4531 Expr *CurInitExpr) {
4532 assert(S.getLangOptions().CPlusPlus0x);
4533
4534 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4535 if (!Record)
4536 return;
4537
4538 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4539 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4540 == DiagnosticsEngine::Ignored)
4541 return;
4542
4543 // Find constructors which would have been considered.
4544 OverloadCandidateSet CandidateSet(Loc);
4545 LookupCopyAndMoveConstructors(
4546 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4547
4548 // Perform overload resolution.
4549 OverloadCandidateSet::iterator Best;
4550 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4551
4552 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4553 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4554 << CurInitExpr->getSourceRange();
4555
4556 switch (OR) {
4557 case OR_Success:
4558 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4559 Best->FoundDecl.getAccess(), Diag);
4560 // FIXME: Check default arguments as far as that's possible.
4561 break;
4562
4563 case OR_No_Viable_Function:
4564 S.Diag(Loc, Diag);
4565 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4566 break;
4567
4568 case OR_Ambiguous:
4569 S.Diag(Loc, Diag);
4570 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4571 break;
4572
4573 case OR_Deleted:
4574 S.Diag(Loc, Diag);
4575 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4576 << 1 << Best->Function->isDeleted();
4577 break;
4578 }
4579}
4580
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004581void InitializationSequence::PrintInitLocationNote(Sema &S,
4582 const InitializedEntity &Entity) {
4583 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4584 if (Entity.getDecl()->getLocation().isInvalid())
4585 return;
4586
4587 if (Entity.getDecl()->getDeclName())
4588 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4589 << Entity.getDecl()->getDeclName();
4590 else
4591 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4592 }
4593}
4594
Sebastian Redl112aa822011-07-14 19:07:55 +00004595static bool isReferenceBinding(const InitializationSequence::Step &s) {
4596 return s.Kind == InitializationSequence::SK_BindReference ||
4597 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4598}
4599
Sebastian Redled2e5322011-12-22 14:44:04 +00004600static ExprResult
4601PerformConstructorInitialization(Sema &S,
4602 const InitializedEntity &Entity,
4603 const InitializationKind &Kind,
4604 MultiExprArg Args,
4605 const InitializationSequence::Step& Step,
4606 bool &ConstructorInitRequiresZeroInit) {
4607 unsigned NumArgs = Args.size();
4608 CXXConstructorDecl *Constructor
4609 = cast<CXXConstructorDecl>(Step.Function.Function);
4610 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4611
4612 // Build a call to the selected constructor.
4613 ASTOwningVector<Expr*> ConstructorArgs(S);
4614 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4615 ? Kind.getEqualLoc()
4616 : Kind.getLocation();
4617
4618 if (Kind.getKind() == InitializationKind::IK_Default) {
4619 // Force even a trivial, implicit default constructor to be
4620 // semantically checked. We do this explicitly because we don't build
4621 // the definition for completely trivial constructors.
4622 CXXRecordDecl *ClassDecl = Constructor->getParent();
4623 assert(ClassDecl && "No parent class for constructor.");
4624 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4625 ClassDecl->hasTrivialDefaultConstructor() &&
4626 !Constructor->isUsed(false))
4627 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4628 }
4629
4630 ExprResult CurInit = S.Owned((Expr *)0);
4631
4632 // Determine the arguments required to actually perform the constructor
4633 // call.
4634 if (S.CompleteConstructorCall(Constructor, move(Args),
4635 Loc, ConstructorArgs))
4636 return ExprError();
4637
4638
4639 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4640 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4641 (Kind.getKind() == InitializationKind::IK_Direct ||
4642 Kind.getKind() == InitializationKind::IK_Value)) {
4643 // An explicitly-constructed temporary, e.g., X(1, 2).
4644 unsigned NumExprs = ConstructorArgs.size();
4645 Expr **Exprs = (Expr **)ConstructorArgs.take();
4646 S.MarkDeclarationReferenced(Loc, Constructor);
4647 S.DiagnoseUseOfDecl(Constructor, Loc);
4648
4649 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4650 if (!TSInfo)
4651 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4652
4653 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4654 Constructor,
4655 TSInfo,
4656 Exprs,
4657 NumExprs,
4658 Kind.getParenRange(),
4659 HadMultipleCandidates,
4660 ConstructorInitRequiresZeroInit));
4661 } else {
4662 CXXConstructExpr::ConstructionKind ConstructKind =
4663 CXXConstructExpr::CK_Complete;
4664
4665 if (Entity.getKind() == InitializedEntity::EK_Base) {
4666 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4667 CXXConstructExpr::CK_VirtualBase :
4668 CXXConstructExpr::CK_NonVirtualBase;
4669 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4670 ConstructKind = CXXConstructExpr::CK_Delegating;
4671 }
4672
4673 // Only get the parenthesis range if it is a direct construction.
4674 SourceRange parenRange =
4675 Kind.getKind() == InitializationKind::IK_Direct ?
4676 Kind.getParenRange() : SourceRange();
4677
4678 // If the entity allows NRVO, mark the construction as elidable
4679 // unconditionally.
4680 if (Entity.allowsNRVO())
4681 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4682 Constructor, /*Elidable=*/true,
4683 move_arg(ConstructorArgs),
4684 HadMultipleCandidates,
4685 ConstructorInitRequiresZeroInit,
4686 ConstructKind,
4687 parenRange);
4688 else
4689 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4690 Constructor,
4691 move_arg(ConstructorArgs),
4692 HadMultipleCandidates,
4693 ConstructorInitRequiresZeroInit,
4694 ConstructKind,
4695 parenRange);
4696 }
4697 if (CurInit.isInvalid())
4698 return ExprError();
4699
4700 // Only check access if all of that succeeded.
4701 S.CheckConstructorAccess(Loc, Constructor, Entity,
4702 Step.Function.FoundDecl.getAccess());
4703 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4704
4705 if (shouldBindAsTemporary(Entity))
4706 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4707
4708 return move(CurInit);
4709}
4710
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004712InitializationSequence::Perform(Sema &S,
4713 const InitializedEntity &Entity,
4714 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004715 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004716 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004717 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004718 unsigned NumArgs = Args.size();
4719 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004720 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722
Sebastian Redld201edf2011-06-05 13:59:11 +00004723 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004724 // If the declaration is a non-dependent, incomplete array type
4725 // that has an initializer, then its type will be completed once
4726 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004727 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004728 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004729 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004730 if (const IncompleteArrayType *ArrayT
4731 = S.Context.getAsIncompleteArrayType(DeclType)) {
4732 // FIXME: We don't currently have the ability to accurately
4733 // compute the length of an initializer list without
4734 // performing full type-checking of the initializer list
4735 // (since we have to determine where braces are implicitly
4736 // introduced and such). So, we fall back to making the array
4737 // type a dependently-sized array type with no specified
4738 // bound.
4739 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4740 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004741
Douglas Gregor51e77d52009-12-10 17:56:55 +00004742 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004743 if (DeclaratorDecl *DD = Entity.getDecl()) {
4744 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4745 TypeLoc TL = TInfo->getTypeLoc();
4746 if (IncompleteArrayTypeLoc *ArrayLoc
4747 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4748 Brackets = ArrayLoc->getBracketsRange();
4749 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004750 }
4751
4752 *ResultType
4753 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4754 /*NumElts=*/0,
4755 ArrayT->getSizeModifier(),
4756 ArrayT->getIndexTypeCVRQualifiers(),
4757 Brackets);
4758 }
4759
4760 }
4761 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004762 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4763 Kind.isExplicitCast());
4764 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004765 }
4766
Sebastian Redld201edf2011-06-05 13:59:11 +00004767 // No steps means no initialization.
4768 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004769 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770
Douglas Gregor1b303932009-12-22 15:35:07 +00004771 QualType DestType = Entity.getType().getNonReferenceType();
4772 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004773 // the same as Entity.getDecl()->getType() in cases involving type merging,
4774 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004775 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004776 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004777 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004778
John McCalldadc5752010-08-24 06:29:42 +00004779 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004780
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004782 // grab the only argument out the Args and place it into the "current"
4783 // initializer.
4784 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004785 case SK_ResolveAddressOfOverloadedFunction:
4786 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004787 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004788 case SK_CastDerivedToBaseLValue:
4789 case SK_BindReference:
4790 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004791 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004792 case SK_UserConversion:
4793 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004794 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004795 case SK_QualificationConversionRValue:
4796 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004797 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004798 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00004799 case SK_UnwrapInitList:
4800 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00004801 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004802 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004803 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004804 case SK_ArrayInit:
4805 case SK_PassByIndirectCopyRestore:
4806 case SK_PassByIndirectRestore:
4807 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004808 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004809 CurInit = Args.get()[0];
4810 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004811 break;
John McCall34376a62010-12-04 03:47:34 +00004812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813
Douglas Gregore1314a62009-12-18 05:02:21 +00004814 case SK_ConstructorInitialization:
4815 case SK_ZeroInitialization:
4816 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
4819 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004820 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004821 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004822 for (step_iterator Step = step_begin(), StepEnd = step_end();
4823 Step != StepEnd; ++Step) {
4824 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004825 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826
John Wiegley01296292011-04-08 18:41:53 +00004827 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004829 switch (Step->Kind) {
4830 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004832 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004833 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004834 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004835 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004836 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004837 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004838 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004840 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004841 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004842 case SK_CastDerivedToBaseLValue: {
4843 // We have a derived-to-base cast that produces either an rvalue or an
4844 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
John McCallcf142162010-08-07 06:22:56 +00004846 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004847
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004848 // Casts to inaccessible base classes are allowed with C-style casts.
4849 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4850 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004851 CurInit.get()->getLocStart(),
4852 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004853 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004854 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004855
Douglas Gregor88d292c2010-05-13 16:44:06 +00004856 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4857 QualType T = SourceType;
4858 if (const PointerType *Pointer = T->getAs<PointerType>())
4859 T = Pointer->getPointeeType();
4860 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004861 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004862 cast<CXXRecordDecl>(RecordTy->getDecl()));
4863 }
4864
John McCall2536c6d2010-08-25 10:28:54 +00004865 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004866 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004867 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004868 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004869 VK_XValue :
4870 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004871 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4872 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004873 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004874 CurInit.get(),
4875 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004876 break;
4877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004878
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004879 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004880 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004881 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4882 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004883 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004884 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004885 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004886 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004887 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004888 }
Anders Carlssona91be642010-01-29 02:47:33 +00004889
John Wiegley01296292011-04-08 18:41:53 +00004890 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004891 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004892 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4893 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004894 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004895 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004896 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004898
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004899 // Reference binding does not have any corresponding ASTs.
4900
4901 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004902 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004903 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004904
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004905 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004906
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004907 case SK_BindReferenceToTemporary:
4908 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004909 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004910 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004911
Douglas Gregorfe314812011-06-21 17:03:29 +00004912 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004913 CurInit = new (S.Context) MaterializeTemporaryExpr(
4914 Entity.getType().getNonReferenceType(),
4915 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004916 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004917
4918 // If we're binding to an Objective-C object that has lifetime, we
4919 // need cleanups.
4920 if (S.getLangOptions().ObjCAutoRefCount &&
4921 CurInit.get()->getType()->isObjCLifetimeType())
4922 S.ExprNeedsCleanups = true;
4923
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004924 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004926 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004928 /*IsExtraneousCopy=*/true);
4929 break;
4930
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004931 case SK_UserConversion: {
4932 // We have a user-defined conversion that invokes either a constructor
4933 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004934 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004935 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004936 FunctionDecl *Fn = Step->Function.Function;
4937 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004938 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004939 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004940 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004941 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004942 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004943 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004944 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004945
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004946 // Determine the arguments required to actually perform the constructor
4947 // call.
John Wiegley01296292011-04-08 18:41:53 +00004948 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004949 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004950 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004951 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004952 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004954 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004956 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004957 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004958 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004959 CXXConstructExpr::CK_Complete,
4960 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004961 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004962 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004963
Anders Carlssona01874b2010-04-21 18:47:17 +00004964 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004965 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004966 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004967
John McCalle3027922010-08-25 11:45:40 +00004968 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004969 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4970 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4971 S.IsDerivedFrom(SourceType, Class))
4972 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973
Douglas Gregor95562572010-04-24 23:45:46 +00004974 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004975 } else {
4976 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004977 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004978 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004979 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004980 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004981
4982 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004983 // derived-to-base conversion? I believe the answer is "no", because
4984 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004985 ExprResult CurInitExprRes =
4986 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4987 FoundFn, Conversion);
4988 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004989 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004990 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004991
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004992 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004993 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4994 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004995 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004996 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997
John McCalle3027922010-08-25 11:45:40 +00004998 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999
Douglas Gregor95562572010-04-24 23:45:46 +00005000 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005002
Sebastian Redl112aa822011-07-14 19:07:55 +00005003 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005004 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5005
5006 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005007 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005008 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005010 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005011 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005012 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00005013 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
5014 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00005015 }
5016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017
John McCallcf142162010-08-07 06:22:56 +00005018 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005019 CurInit.get()->getType(),
5020 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005021 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005022 if (MaybeBindToTemp)
5023 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005024 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005025 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5026 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005027 break;
5028 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005029
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005030 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005031 case SK_QualificationConversionXValue:
5032 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005033 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005034 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005035 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005036 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005037 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005038 VK_XValue :
5039 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005040 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005041 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005042 }
5043
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005044 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00005045 Sema::CheckedConversionKind CCK
5046 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5047 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005048 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005049 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005050 ExprResult CurInitExprRes =
5051 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005052 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005053 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005054 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005055 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005056 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058
Douglas Gregor51e77d52009-12-10 17:56:55 +00005059 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005060 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl29526f02011-11-27 16:50:07 +00005061 // Hack: We must pass *ResultType if available in order to set the type
5062 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5063 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5064 // temporary, not a reference, so we should pass Ty.
5065 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5066 // Since this step is never used for a reference directly, we explicitly
5067 // unwrap references here and rewrap them afterwards.
5068 // We also need to create a InitializeTemporary entity for this.
5069 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5070 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5071 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5072 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5073 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005074 Kind.getKind() != InitializationKind::IK_Direct ||
5075 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005076 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005077 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005078
Sebastian Redl29526f02011-11-27 16:50:07 +00005079 if (ResultType) {
5080 if ((*ResultType)->isRValueReferenceType())
5081 Ty = S.Context.getRValueReferenceType(Ty);
5082 else if ((*ResultType)->isLValueReferenceType())
5083 Ty = S.Context.getLValueReferenceType(Ty,
5084 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5085 *ResultType = Ty;
5086 }
5087
5088 InitListExpr *StructuredInitList =
5089 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005090 CurInit.release();
Sebastian Redl29526f02011-11-27 16:50:07 +00005091 CurInit = S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005092 break;
5093 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005094
Sebastian Redled2e5322011-12-22 14:44:04 +00005095 case SK_ListConstructorCall: {
5096 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5097 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5098 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5099 move(Arg), *Step,
5100 ConstructorInitRequiresZeroInit);
5101 break;
5102 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005103
Sebastian Redl29526f02011-11-27 16:50:07 +00005104 case SK_UnwrapInitList:
5105 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5106 break;
5107
5108 case SK_RewrapInitList: {
5109 Expr *E = CurInit.take();
5110 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5111 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5112 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5113 ILE->setSyntacticForm(Syntactic);
5114 ILE->setType(E->getType());
5115 ILE->setValueKind(E->getValueKind());
5116 CurInit = S.Owned(ILE);
5117 break;
5118 }
5119
Sebastian Redled2e5322011-12-22 14:44:04 +00005120 case SK_ConstructorInitialization:
5121 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5122 *Step,
5123 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005124 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005126 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005127 step_iterator NextStep = Step;
5128 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005129 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005130 NextStep->Kind == SK_ConstructorInitialization) {
5131 // The need for zero-initialization is recorded directly into
5132 // the call to the object's constructor within the next step.
5133 ConstructorInitRequiresZeroInit = true;
5134 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5135 S.getLangOptions().CPlusPlus &&
5136 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00005137 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5138 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005139 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00005140 Kind.getRange().getBegin());
5141
5142 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5143 TSInfo->getType().getNonLValueExprType(S.Context),
5144 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005145 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005146 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005147 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005148 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00005149 break;
5150 }
Douglas Gregore1314a62009-12-18 05:02:21 +00005151
5152 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00005153 QualType SourceType = CurInit.get()->getType();
5154 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00005155 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00005156 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5157 if (Result.isInvalid())
5158 return ExprError();
5159 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00005160
5161 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005162 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00005163 if (ConvTy != Sema::Compatible &&
5164 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00005165 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00005166 == Sema::Compatible)
5167 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00005168 if (CurInitExprRes.isInvalid())
5169 return ExprError();
5170 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00005171
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005172 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00005173 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5174 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00005175 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005176 getAssignmentAction(Entity),
5177 &Complained)) {
5178 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005179 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005180 } else if (Complained)
5181 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00005182 break;
5183 }
Eli Friedman78275202009-12-19 08:11:05 +00005184
5185 case SK_StringInit: {
5186 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00005187 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00005188 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00005189 break;
5190 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005191
5192 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00005193 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005194 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005195 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005196 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005197
5198 case SK_ArrayInit:
5199 // Okay: we checked everything before creating this step. Note that
5200 // this is a GNU extension.
5201 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00005202 << Step->Type << CurInit.get()->getType()
5203 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00005204
5205 // If the destination type is an incomplete array type, update the
5206 // type accordingly.
5207 if (ResultType) {
5208 if (const IncompleteArrayType *IncompleteDest
5209 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5210 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00005211 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00005212 *ResultType = S.Context.getConstantArrayType(
5213 IncompleteDest->getElementType(),
5214 ConstantSource->getSize(),
5215 ArrayType::Normal, 0);
5216 }
5217 }
5218 }
John McCall31168b02011-06-15 23:02:42 +00005219 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005220
John McCall31168b02011-06-15 23:02:42 +00005221 case SK_PassByIndirectCopyRestore:
5222 case SK_PassByIndirectRestore:
5223 checkIndirectCopyRestoreSource(S, CurInit.get());
5224 CurInit = S.Owned(new (S.Context)
5225 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5226 Step->Kind == SK_PassByIndirectCopyRestore));
5227 break;
5228
5229 case SK_ProduceObjCObject:
5230 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00005231 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00005232 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00005233 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005234 }
5235 }
John McCall1f425642010-11-11 03:21:53 +00005236
5237 // Diagnose non-fatal problems with the completed initialization.
5238 if (Entity.getKind() == InitializedEntity::EK_Member &&
5239 cast<FieldDecl>(Entity.getDecl())->isBitField())
5240 S.CheckBitFieldInitialization(Kind.getLocation(),
5241 cast<FieldDecl>(Entity.getDecl()),
5242 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005243
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005244 return move(CurInit);
5245}
5246
5247//===----------------------------------------------------------------------===//
5248// Diagnose initialization failures
5249//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005250bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005251 const InitializedEntity &Entity,
5252 const InitializationKind &Kind,
5253 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005254 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005255 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005256
Douglas Gregor1b303932009-12-22 15:35:07 +00005257 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005258 switch (Failure) {
5259 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005260 // FIXME: Customize for the initialized entity?
5261 if (NumArgs == 0)
5262 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5263 << DestType.getNonReferenceType();
5264 else // FIXME: diagnostic below could be better!
5265 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5266 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005267 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005268
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005269 case FK_ArrayNeedsInitList:
5270 case FK_ArrayNeedsInitListOrStringLiteral:
5271 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5272 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5273 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005274
Douglas Gregore2f943b2011-02-22 18:29:51 +00005275 case FK_ArrayTypeMismatch:
5276 case FK_NonConstantArrayInit:
5277 S.Diag(Kind.getLocation(),
5278 (Failure == FK_ArrayTypeMismatch
5279 ? diag::err_array_init_different_type
5280 : diag::err_array_init_non_constant_array))
5281 << DestType.getNonReferenceType()
5282 << Args[0]->getType()
5283 << Args[0]->getSourceRange();
5284 break;
5285
John McCalla59dc2f2012-01-05 00:13:19 +00005286 case FK_VariableLengthArrayHasInitializer:
5287 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5288 << Args[0]->getSourceRange();
5289 break;
5290
John McCall16df1e52010-03-30 21:47:33 +00005291 case FK_AddressOfOverloadFailed: {
5292 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005293 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005294 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00005295 true,
5296 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005297 break;
John McCall16df1e52010-03-30 21:47:33 +00005298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005300 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00005301 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005302 switch (FailedOverloadResult) {
5303 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00005304 if (Failure == FK_UserConversionOverloadFailed)
5305 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5306 << Args[0]->getType() << DestType
5307 << Args[0]->getSourceRange();
5308 else
5309 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5310 << DestType << Args[0]->getType()
5311 << Args[0]->getSourceRange();
5312
John McCall5c32be02010-08-24 20:38:10 +00005313 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005314 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005315
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005316 case OR_No_Viable_Function:
5317 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5318 << Args[0]->getType() << DestType.getNonReferenceType()
5319 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00005320 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005321 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005322
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005323 case OR_Deleted: {
5324 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5325 << Args[0]->getType() << DestType.getNonReferenceType()
5326 << Args[0]->getSourceRange();
5327 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005328 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00005329 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5330 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005331 if (Ovl == OR_Deleted) {
5332 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005333 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005334 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005335 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005336 }
5337 break;
5338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005339
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005340 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005341 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005342 break;
5343 }
5344 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005345
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005346 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00005347 if (isa<InitListExpr>(Args[0])) {
5348 S.Diag(Kind.getLocation(),
5349 diag::err_lvalue_reference_bind_to_initlist)
5350 << DestType.getNonReferenceType().isVolatileQualified()
5351 << DestType.getNonReferenceType()
5352 << Args[0]->getSourceRange();
5353 break;
5354 }
5355 // Intentional fallthrough
5356
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005357 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005359 Failure == FK_NonConstLValueReferenceBindingToTemporary
5360 ? diag::err_lvalue_reference_bind_to_temporary
5361 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005362 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005363 << DestType.getNonReferenceType()
5364 << Args[0]->getType()
5365 << Args[0]->getSourceRange();
5366 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005367
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005368 case FK_RValueReferenceBindingToLValue:
5369 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005370 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005371 << Args[0]->getSourceRange();
5372 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005374 case FK_ReferenceInitDropsQualifiers:
5375 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5376 << DestType.getNonReferenceType()
5377 << Args[0]->getType()
5378 << Args[0]->getSourceRange();
5379 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005380
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005381 case FK_ReferenceInitFailed:
5382 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5383 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005384 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005385 << Args[0]->getType()
5386 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005387 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5388 Args[0]->getType()->isObjCObjectPointerType())
5389 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005390 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391
Douglas Gregorb491ed32011-02-19 21:32:49 +00005392 case FK_ConversionFailed: {
5393 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00005394 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00005395 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005396 << DestType
John McCall086a4642010-11-24 05:12:34 +00005397 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005398 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005399 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00005400 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5401 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor33823722011-06-11 01:09:30 +00005402 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5403 Args[0]->getType()->isObjCObjectPointerType())
5404 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005405 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005406 }
John Wiegley01296292011-04-08 18:41:53 +00005407
5408 case FK_ConversionFromPropertyFailed:
5409 // No-op. This error has already been reported.
5410 break;
5411
Douglas Gregor51e77d52009-12-10 17:56:55 +00005412 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005413 SourceRange R;
5414
5415 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005416 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005417 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005418 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005419 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005420
Douglas Gregor8ec51732010-09-08 21:40:08 +00005421 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5422 if (Kind.isCStyleOrFunctionalCast())
5423 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5424 << R;
5425 else
5426 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5427 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005428 break;
5429 }
5430
5431 case FK_ReferenceBindingToInitList:
5432 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5433 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5434 break;
5435
5436 case FK_InitListBadDestinationType:
5437 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5438 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5439 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005440
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005441 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005442 case FK_ConstructorOverloadFailed: {
5443 SourceRange ArgsRange;
5444 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005445 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005446 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005447
Sebastian Redl6901c0d2011-12-22 18:58:38 +00005448 if (Failure == FK_ListConstructorOverloadFailed) {
5449 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5450 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5451 Args = InitList->getInits();
5452 NumArgs = InitList->getNumInits();
5453 }
5454
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005455 // FIXME: Using "DestType" for the entity we're printing is probably
5456 // bad.
5457 switch (FailedOverloadResult) {
5458 case OR_Ambiguous:
5459 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5460 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005461 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5462 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005463 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005465 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005466 if (Kind.getKind() == InitializationKind::IK_Default &&
5467 (Entity.getKind() == InitializedEntity::EK_Base ||
5468 Entity.getKind() == InitializedEntity::EK_Member) &&
5469 isa<CXXConstructorDecl>(S.CurContext)) {
5470 // This is implicit default initialization of a member or
5471 // base within a constructor. If no viable function was
5472 // found, notify the user that she needs to explicitly
5473 // initialize this base/member.
5474 CXXConstructorDecl *Constructor
5475 = cast<CXXConstructorDecl>(S.CurContext);
5476 if (Entity.getKind() == InitializedEntity::EK_Base) {
5477 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5478 << Constructor->isImplicit()
5479 << S.Context.getTypeDeclType(Constructor->getParent())
5480 << /*base=*/0
5481 << Entity.getType();
5482
5483 RecordDecl *BaseDecl
5484 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5485 ->getDecl();
5486 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5487 << S.Context.getTagDeclType(BaseDecl);
5488 } else {
5489 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5490 << Constructor->isImplicit()
5491 << S.Context.getTypeDeclType(Constructor->getParent())
5492 << /*member=*/1
5493 << Entity.getName();
5494 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5495
5496 if (const RecordType *Record
5497 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005498 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005499 diag::note_previous_decl)
5500 << S.Context.getTagDeclType(Record->getDecl());
5501 }
5502 break;
5503 }
5504
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005505 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5506 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005507 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005508 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005509
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005510 case OR_Deleted: {
5511 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5512 << true << DestType << ArgsRange;
5513 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005514 OverloadingResult Ovl
5515 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005516 if (Ovl == OR_Deleted) {
5517 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005518 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005519 } else {
5520 llvm_unreachable("Inconsistent overload resolution?");
5521 }
5522 break;
5523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005525 case OR_Success:
5526 llvm_unreachable("Conversion did not fail!");
5527 break;
5528 }
5529 break;
5530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531
Douglas Gregor85dabae2009-12-16 01:38:02 +00005532 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005533 if (Entity.getKind() == InitializedEntity::EK_Member &&
5534 isa<CXXConstructorDecl>(S.CurContext)) {
5535 // This is implicit default-initialization of a const member in
5536 // a constructor. Complain that it needs to be explicitly
5537 // initialized.
5538 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5539 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5540 << Constructor->isImplicit()
5541 << S.Context.getTypeDeclType(Constructor->getParent())
5542 << /*const=*/1
5543 << Entity.getName();
5544 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5545 << Entity.getName();
5546 } else {
5547 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5548 << DestType << (bool)DestType->getAs<RecordType>();
5549 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005550 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005551
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005552 case FK_Incomplete:
5553 S.RequireCompleteType(Kind.getLocation(), DestType,
5554 diag::err_init_incomplete_type);
5555 break;
5556
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005557 case FK_ListInitializationFailed: {
5558 // Run the init list checker again to emit diagnostics.
5559 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5560 QualType DestType = Entity.getType();
5561 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005562 DestType, /*VerifyOnly=*/false,
5563 Kind.getKind() != InitializationKind::IK_Direct ||
5564 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005565 assert(DiagnoseInitList.HadError() &&
5566 "Inconsistent init list check result.");
5567 break;
5568 }
John McCall4124c492011-10-17 18:40:02 +00005569
5570 case FK_PlaceholderType: {
5571 // FIXME: Already diagnosed!
5572 break;
5573 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005576 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005577 return true;
5578}
Douglas Gregore1314a62009-12-18 05:02:21 +00005579
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005580void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005581 switch (SequenceKind) {
5582 case FailedSequence: {
5583 OS << "Failed sequence: ";
5584 switch (Failure) {
5585 case FK_TooManyInitsForReference:
5586 OS << "too many initializers for reference";
5587 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005588
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005589 case FK_ArrayNeedsInitList:
5590 OS << "array requires initializer list";
5591 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005593 case FK_ArrayNeedsInitListOrStringLiteral:
5594 OS << "array requires initializer list or string literal";
5595 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596
Douglas Gregore2f943b2011-02-22 18:29:51 +00005597 case FK_ArrayTypeMismatch:
5598 OS << "array type mismatch";
5599 break;
5600
5601 case FK_NonConstantArrayInit:
5602 OS << "non-constant array initializer";
5603 break;
5604
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005605 case FK_AddressOfOverloadFailed:
5606 OS << "address of overloaded function failed";
5607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005609 case FK_ReferenceInitOverloadFailed:
5610 OS << "overload resolution for reference initialization failed";
5611 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005613 case FK_NonConstLValueReferenceBindingToTemporary:
5614 OS << "non-const lvalue reference bound to temporary";
5615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005617 case FK_NonConstLValueReferenceBindingToUnrelated:
5618 OS << "non-const lvalue reference bound to unrelated type";
5619 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005621 case FK_RValueReferenceBindingToLValue:
5622 OS << "rvalue reference bound to an lvalue";
5623 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005624
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005625 case FK_ReferenceInitDropsQualifiers:
5626 OS << "reference initialization drops qualifiers";
5627 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005628
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005629 case FK_ReferenceInitFailed:
5630 OS << "reference initialization failed";
5631 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005632
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005633 case FK_ConversionFailed:
5634 OS << "conversion failed";
5635 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005636
John Wiegley01296292011-04-08 18:41:53 +00005637 case FK_ConversionFromPropertyFailed:
5638 OS << "conversion from property failed";
5639 break;
5640
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005641 case FK_TooManyInitsForScalar:
5642 OS << "too many initializers for scalar";
5643 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005644
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005645 case FK_ReferenceBindingToInitList:
5646 OS << "referencing binding to initializer list";
5647 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005649 case FK_InitListBadDestinationType:
5650 OS << "initializer list for non-aggregate, non-scalar type";
5651 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005652
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005653 case FK_UserConversionOverloadFailed:
5654 OS << "overloading failed for user-defined conversion";
5655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005656
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005657 case FK_ConstructorOverloadFailed:
5658 OS << "constructor overloading failed";
5659 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005661 case FK_DefaultInitOfConst:
5662 OS << "default initialization of a const variable";
5663 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005664
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005665 case FK_Incomplete:
5666 OS << "initialization of incomplete type";
5667 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005668
5669 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005670 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005671 break;
5672
John McCalla59dc2f2012-01-05 00:13:19 +00005673 case FK_VariableLengthArrayHasInitializer:
5674 OS << "variable length array has an initializer";
5675 break;
5676
John McCall4124c492011-10-17 18:40:02 +00005677 case FK_PlaceholderType:
5678 OS << "initializer expression isn't contextually valid";
5679 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00005680
5681 case FK_ListConstructorOverloadFailed:
5682 OS << "list constructor overloading failed";
5683 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005684 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005685 OS << '\n';
5686 return;
5687 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005688
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005689 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005690 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005691 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005692
Sebastian Redld201edf2011-06-05 13:59:11 +00005693 case NormalSequence:
5694 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005695 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005697
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005698 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5699 if (S != step_begin()) {
5700 OS << " -> ";
5701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005702
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005703 switch (S->Kind) {
5704 case SK_ResolveAddressOfOverloadedFunction:
5705 OS << "resolve address of overloaded function";
5706 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005707
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005708 case SK_CastDerivedToBaseRValue:
5709 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5710 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005712 case SK_CastDerivedToBaseXValue:
5713 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5714 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005715
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005716 case SK_CastDerivedToBaseLValue:
5717 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5718 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005720 case SK_BindReference:
5721 OS << "bind reference to lvalue";
5722 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005723
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005724 case SK_BindReferenceToTemporary:
5725 OS << "bind reference to a temporary";
5726 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005727
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005728 case SK_ExtraneousCopyToTemporary:
5729 OS << "extraneous C++03 copy to temporary";
5730 break;
5731
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005732 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005733 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005734 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005735
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005736 case SK_QualificationConversionRValue:
5737 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005738 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005739
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005740 case SK_QualificationConversionXValue:
5741 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00005742 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005743
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005744 case SK_QualificationConversionLValue:
5745 OS << "qualification conversion (lvalue)";
5746 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005747
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005748 case SK_ConversionSequence:
5749 OS << "implicit conversion sequence (";
5750 S->ICS->DebugPrint(); // FIXME: use OS
5751 OS << ")";
5752 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005754 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005755 OS << "list aggregate initialization";
5756 break;
5757
5758 case SK_ListConstructorCall:
5759 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761
Sebastian Redl29526f02011-11-27 16:50:07 +00005762 case SK_UnwrapInitList:
5763 OS << "unwrap reference initializer list";
5764 break;
5765
5766 case SK_RewrapInitList:
5767 OS << "rewrap reference initializer list";
5768 break;
5769
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005770 case SK_ConstructorInitialization:
5771 OS << "constructor initialization";
5772 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005773
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005774 case SK_ZeroInitialization:
5775 OS << "zero initialization";
5776 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005777
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005778 case SK_CAssignment:
5779 OS << "C assignment";
5780 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005781
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005782 case SK_StringInit:
5783 OS << "string initialization";
5784 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005785
5786 case SK_ObjCObjectConversion:
5787 OS << "Objective-C object conversion";
5788 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005789
5790 case SK_ArrayInit:
5791 OS << "array initialization";
5792 break;
John McCall31168b02011-06-15 23:02:42 +00005793
5794 case SK_PassByIndirectCopyRestore:
5795 OS << "pass by indirect copy and restore";
5796 break;
5797
5798 case SK_PassByIndirectRestore:
5799 OS << "pass by indirect restore";
5800 break;
5801
5802 case SK_ProduceObjCObject:
5803 OS << "Objective-C object retension";
5804 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005805 }
5806 }
5807}
5808
5809void InitializationSequence::dump() const {
5810 dump(llvm::errs());
5811}
5812
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005813static void DiagnoseNarrowingInInitList(
5814 Sema& S, QualType EntityType, const Expr *InitE,
5815 bool Constant, const APValue &ConstantValue) {
5816 if (Constant) {
5817 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005818 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005819 ? diag::err_init_list_constant_narrowing
5820 : diag::warn_init_list_constant_narrowing)
5821 << InitE->getSourceRange()
Richard Smithf6f003a2011-12-16 19:06:07 +00005822 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005823 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005824 } else
5825 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005826 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005827 ? diag::err_init_list_variable_narrowing
5828 : diag::warn_init_list_variable_narrowing)
5829 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005830 << InitE->getType().getLocalUnqualifiedType()
5831 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005832
5833 llvm::SmallString<128> StaticCast;
5834 llvm::raw_svector_ostream OS(StaticCast);
5835 OS << "static_cast<";
5836 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5837 // It's important to use the typedef's name if there is one so that the
5838 // fixit doesn't break code using types like int64_t.
5839 //
5840 // FIXME: This will break if the typedef requires qualification. But
5841 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005842 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005843 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5844 OS << BT->getName(S.getLangOptions());
5845 else {
5846 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5847 // with a broken cast.
5848 return;
5849 }
5850 OS << ">(";
5851 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5852 << InitE->getSourceRange()
5853 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5854 << FixItHint::CreateInsertion(
5855 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5856}
5857
Douglas Gregore1314a62009-12-18 05:02:21 +00005858//===----------------------------------------------------------------------===//
5859// Initialization helper functions
5860//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005861bool
5862Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5863 ExprResult Init) {
5864 if (Init.isInvalid())
5865 return false;
5866
5867 Expr *InitE = Init.get();
5868 assert(InitE && "No initialization expression");
5869
5870 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5871 SourceLocation());
5872 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005873 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005874}
5875
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005876ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005877Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5878 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005879 ExprResult Init,
5880 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005881 if (Init.isInvalid())
5882 return ExprError();
5883
John McCall1f425642010-11-11 03:21:53 +00005884 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005885 assert(InitE && "No initialization expression?");
5886
5887 if (EqualLoc.isInvalid())
5888 EqualLoc = InitE->getLocStart();
5889
5890 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5891 EqualLoc);
5892 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5893 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005894
5895 bool Constant = false;
5896 APValue Result;
5897 if (TopLevelOfInitList &&
5898 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5899 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5900 Constant, Result);
5901 }
John McCallfaf5fb42010-08-26 23:41:50 +00005902 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005903}