blob: e8fa40f263b92caff02363cd5a1aaae7e52a1336 [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000025#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000026#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000027using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000028
Chris Lattnerdd8e0062009-02-24 22:27:37 +000029//===----------------------------------------------------------------------===//
30// Sema Initialization Checking
31//===----------------------------------------------------------------------===//
32
John McCallce6c9b72011-02-21 07:22:22 +000033static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000035 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
36 return 0;
37
Chris Lattner8879e3b2009-02-26 23:26:43 +000038 // See if this is a string literal or @encode.
39 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000040
Chris Lattner8879e3b2009-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 Lattner220b6362009-02-26 23:42:47 +000047 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000048
49 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-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 Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-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 Lattner8879e3b2009-02-26 23:26:43 +000069
Douglas Gregor5cee1192011-07-27 05:40:30 +000070 return 0;
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor5cee1192011-07-27 05:40:30 +000073 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074}
75
John McCallce6c9b72011-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 McCallfef8b342011-02-21 07:57:55 +000083static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
84 Sema &S) {
Chris Lattner79e079d2009-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 Stump1eb44332009-09-09 15:08:12 +000089
Chris Lattnerdd8e0062009-02-24 22:27:37 +000090 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000091 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 // being initialized to a string literal.
93 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000094 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000095 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000096 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
97 ConstVal,
98 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000099 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000100 }
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Eli Friedman8718a6a2009-05-29 18:22:49 +0000102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000104 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-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 Friedmanbc34b1d2011-04-11 00:23:45 +0000107 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-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 Friedmanbc34b1d2011-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 Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-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 Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregor9e80f722009-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 Bagnara63e7d252011-01-27 19:55:10 +0000155/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-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 Lattner8b419b92009-02-24 22:48:58 +0000168namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000172 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000173 bool AllowBraceElision;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000180 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000181 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000183 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000186 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000188 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000189 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000191 unsigned &StructuredIndex,
192 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000194 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Eli Friedman0c706c22011-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 Carlsson8ff9e862010-01-23 23:23:01 +0000203 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000204 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000205 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
207 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000208 void CheckReferenceType(const InitializedEntity &Entity,
209 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000210 unsigned &Index,
211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000213 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000214 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000215 InitListExpr *StructuredList,
216 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000217 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000218 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000219 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000220 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000221 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000222 unsigned &StructuredIndex,
223 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000224 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000225 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000226 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000227 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000228 InitListExpr *StructuredList,
229 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000230 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000231 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000232 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000233 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000234 RecordDecl::field_iterator *NextField,
235 llvm::APSInt *NextElementIndex,
236 unsigned &Index,
237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000239 bool FinishSubobjectInit,
240 bool TopLevelObject);
Douglas Gregorc34ee5e2009-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 Gregor9e80f722009-01-29 01:05:33 +0000246 void UpdateStructuredListElement(InitListExpr *StructuredList,
247 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000248 Expr *expr);
249 int numArrayElements(QualType DeclType);
250 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000251
Douglas Gregord6d37de2009-12-22 00:05:34 +0000252 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
253 const InitializedEntity &ParentEntity,
254 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000255 void FillInValueInitializations(const InitializedEntity &Entity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000257 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
258 Expr *InitExpr, FieldDecl *Field,
259 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000260 void CheckValueInitializable(const InitializedEntity &Entity);
261
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000262public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000263 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000264 InitListExpr *IL, QualType &T, bool VerifyOnly,
265 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-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 Lattner8b419b92009-02-24 22:48:58 +0000272} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000273
Sebastian Redl3ff5c862011-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 Gregord6d37de2009-12-22 00:05:34 +0000286void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
287 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000288 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000289 bool &RequiresSecondPass) {
290 SourceLocation Loc = ILE->getSourceRange().getBegin();
291 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-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 Takumidfbb02a2011-01-27 07:10:08 +0000311
Douglas Gregord6d37de2009-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 Takumidfbb02a2011-01-27 07:10:08 +0000320
John McCall60d7b3a2010-08-24 06:29:42 +0000321 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000322 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000323 if (MemberInit.isInvalid()) {
324 hadError = true;
325 return;
326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327
Douglas Gregord6d37de2009-12-22 00:05:34 +0000328 if (hadError) {
329 // Do nothing
330 } else if (Init < NumInits) {
331 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000332 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-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 Kremenek709210f2010-04-13 23:39:13 +0000337 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000338 RequiresSecondPass = true;
339 }
340 } else if (InitListExpr *InnerILE
341 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000342 FillInValueInitializations(MemberEntity, InnerILE,
343 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000344}
345
Douglas Gregor4c678342009-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 Takumidfbb02a2011-01-27 07:10:08 +0000349void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000350InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
351 InitListExpr *ILE,
352 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000353 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000354 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000355 SourceLocation Loc = ILE->getSourceRange().getBegin();
356 if (ILE->getSyntacticForm())
357 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Ted Kremenek6217b802009-07-29 21:53:49 +0000359 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-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 Gregor4c678342009-01-28 21:54:33 +0000372
Douglas Gregord6d37de2009-12-22 00:05:34 +0000373 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000374 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000375
376 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
377 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000379
Douglas Gregord6d37de2009-12-22 00:05:34 +0000380 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000381
Douglas Gregord6d37de2009-12-22 00:05:34 +0000382 // Only look at the first initialization of a union.
383 if (RType->getDecl()->isUnion())
384 break;
385 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000386 }
387
388 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000389 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000390
391 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000393 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000394 unsigned NumInits = ILE->getNumInits();
395 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000396 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000397 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000398 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
399 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000400 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000402 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000403 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000404 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000405 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000406 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000407 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000408 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000409
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000410
Douglas Gregor87fd7032009-02-02 17:43:21 +0000411 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000412 if (hadError)
413 return;
414
Anders Carlssond3d824d2010-01-23 04:34:47 +0000415 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
416 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000417 ElementEntity.setElementIndex(Init);
418
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000419 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
420 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-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 Gregor87fd7032009-02-02 17:43:21 +0000426 hadError = true;
427 return;
428 }
429
John McCall60d7b3a2010-08-24 06:29:42 +0000430 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000431 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000432 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000433 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000434 return;
435 }
436
437 if (hadError) {
438 // Do nothing
439 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-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 Kyrtzidis4423ac02011-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 Redl7491c492011-06-05 13:59:11 +0000454 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-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 Gregorcb57fb92009-12-16 06:35:08 +0000462 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000463 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000464 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000465 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000466 }
467}
468
Chris Lattner68355a52009-01-29 05:10:57 +0000469
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000470InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000471 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000472 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000473 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000474 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000475
Eli Friedmanb85f7072008-05-19 19:16:24 +0000476 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000477 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000478 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000479 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000480 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000481 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000482 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000483
Sebastian Redl14b0c192011-09-24 17:48:00 +0000484 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000485 bool RequiresSecondPass = false;
486 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000487 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000488 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000489 RequiresSecondPass);
490 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000491}
492
493int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000494 // FIXME: use a proper constant
495 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000496 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000497 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-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 Kremenek6217b802009-07-29 21:53:49 +0000504 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000505 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000506 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000507 Field = structDecl->field_begin(),
508 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000509 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000510 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000511 ++InitializableMembers;
512 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000513 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000514 return std::min(InitializableMembers, 1);
515 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000516}
517
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000518void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000519 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000520 QualType T, unsigned &Index,
521 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000522 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000523 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Steve Naroff0cca7492008-05-01 22:18:59 +0000525 if (T->isArrayType())
526 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000527 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000528 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000529 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000530 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000531 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000532 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000533
Eli Friedman402256f2008-05-25 13:49:22 +0000534 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000535 if (!VerifyOnly)
536 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
537 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000538 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000539 hadError = true;
540 return;
541 }
542
Douglas Gregor4c678342009-01-28 21:54:33 +0000543 // Build a structured initializer list corresponding to this subobject.
544 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000545 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
546 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000547 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
548 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000549 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000550
Douglas Gregor4c678342009-01-28 21:54:33 +0000551 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000552 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000554 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000555 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000556 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000557
558 if (VerifyOnly) {
559 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
560 hadError = true;
561 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000562 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000563
Sebastian Redlc2235182011-10-16 18:19:28 +0000564 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-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 Takumidfbb02a2011-01-27 07:10:08 +0000572
Sebastian Redlc2235182011-10-16 18:19:28 +0000573 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000574 if (T->isArrayType() || T->isRecordType()) {
575 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000576 AllowBraceElision ? diag::warn_missing_braces :
577 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000578 << StructuredSubobjectInitList->getSourceRange()
579 << FixItHint::CreateInsertion(
580 StructuredSubobjectInitList->getLocStart(), "{")
581 << FixItHint::CreateInsertion(
582 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000584 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000585 if (!AllowBraceElision)
586 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000587 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000588 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000589}
590
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000591void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000592 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000593 unsigned &Index,
594 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000595 unsigned &StructuredIndex,
596 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000597 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000598 if (!VerifyOnly) {
599 SyntacticToSemantic[IList] = StructuredList;
600 StructuredList->setSyntacticForm(IList);
601 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000602 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000603 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-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 Friedman638e1442008-05-25 13:22:35 +0000609 if (hadError)
610 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000611
Eli Friedman638e1442008-05-25 13:22:35 +0000612 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000613 // We have leftover initializers
Sebastian Redl14b0c192011-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 Friedmane5408582009-05-29 20:20:05 +0000623 if (StructuredIndex == 1 &&
624 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000625 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000626 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000627 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000628 hadError = true;
629 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000630 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000631 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000632 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000633 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000634 // Don't complain for incomplete types, since we'll get an error
635 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000636 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000637 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000638 CurrentObjectType->isArrayType()? 0 :
639 CurrentObjectType->isVectorType()? 1 :
640 CurrentObjectType->isScalarType()? 2 :
641 CurrentObjectType->isUnionType()? 3 :
642 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000643
644 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000645 if (SemaRef.getLangOptions().CPlusPlus) {
646 DK = diag::err_excess_initializers;
647 hadError = true;
648 }
Nate Begeman08634522009-07-07 21:53:06 +0000649 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
650 DK = diag::err_excess_initializers;
651 hadError = true;
652 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000653
Chris Lattner08202542009-02-24 22:50:46 +0000654 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000655 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000656 }
657 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000658
Sebastian Redl14b0c192011-09-24 17:48:00 +0000659 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
660 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000661 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000662 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000663 << FixItHint::CreateRemoval(IList->getLocStart())
664 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000665}
666
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000667void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000668 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000669 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000670 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000671 unsigned &Index,
672 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000673 unsigned &StructuredIndex,
674 bool TopLevelObject) {
Eli Friedman0c706c22011-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 Carlsson46f46592010-01-23 19:55:29 +0000681 CheckScalarType(Entity, IList, DeclType, Index,
682 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000683 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000685 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000686 } else if (DeclType->isAggregateType()) {
687 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000688 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000689 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000690 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000691 StructuredList, StructuredIndex,
692 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000693 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000694 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000695 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000696 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000698 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000699 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000700 } else
David Blaikieb219cfc2011-09-23 05:06:16 +0000701 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000702 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
703 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000704 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000705 if (!VerifyOnly)
706 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
707 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000708 hadError = true;
Douglas Gregor930d8b52009-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 Redl14b0c192011-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 Gregor930d8b52009-01-30 22:09:00 +0000721 hadError = true;
722 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000723 CheckReferenceType(Entity, IList, DeclType, Index,
724 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000725 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000726 if (!VerifyOnly)
727 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
728 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000729 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000730 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000731 if (!VerifyOnly)
732 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
733 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000734 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000735 }
736}
737
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000738void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000739 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000740 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000741 unsigned &Index,
742 InitListExpr *StructuredList,
743 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000744 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000745 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
746 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000747 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000748 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000749 = getStructuredSubobjectInit(IList, Index, ElemType,
750 StructuredList, StructuredIndex,
751 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000752 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000753 newStructuredList, newStructuredIndex);
754 ++StructuredIndex;
755 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000756 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000757 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000758 return CheckScalarType(Entity, IList, ElemType, Index,
759 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000760 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000761 return CheckReferenceType(Entity, IList, ElemType, Index,
762 StructuredList, StructuredIndex);
763 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000764
John McCallfef8b342011-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 Takumidfbb02a2011-01-27 07:10:08 +0000769
John McCallfef8b342011-02-21 07:57:55 +0000770 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000771 if (!VerifyOnly) {
772 CheckStringInit(Str, ElemType, arrayType, SemaRef);
773 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
774 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000775 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000776 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000777 }
John McCallfef8b342011-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 Redl5d3d41d2011-09-24 17:47:39 +0000784 // initializing the aggregate member with an initializer from
John McCallfef8b342011-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 Redl14b0c192011-09-24 17:48:00 +0000794 if (!VerifyOnly) {
Richard Smithb6f8d282011-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 McCallfef8b342011-02-21 07:57:55 +0000799
Sebastian Redl14b0c192011-09-24 17:48:00 +0000800 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000801 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000802 }
John McCallfef8b342011-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 Wiegley429bb272011-04-08 18:41:53 +0000817 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000818 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000819 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
820 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000821 == Sema::Compatible) {
John Wiegley429bb272011-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 McCallfef8b342011-02-21 07:57:55 +0000831 ++Index;
832 return;
833 }
John Wiegley429bb272011-04-08 18:41:53 +0000834 ExprRes.release();
John McCallfef8b342011-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 Lattner61b4bc82011-07-15 23:07:01 +0000844 if (!SemaRef.getLangOptions().OpenCL &&
845 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000846 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
847 StructuredIndex);
848 ++StructuredIndex;
849 } else {
Sebastian Redl14b0c192011-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 McCallfef8b342011-02-21 07:57:55 +0000857 hadError = true;
858 ++Index;
859 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000860 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000861}
862
Eli Friedman0c706c22011-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 Redl14b0c192011-09-24 17:48:00 +0000883 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-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 Carlsson8ff9e862010-01-23 23:23:01 +0000900void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000901 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000902 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000903 InitListExpr *StructuredList,
904 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000905 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-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 Gregor4c678342009-01-28 21:54:33 +0000913 ++Index;
914 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000915 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000916 }
John McCallb934c2d2010-11-11 00:46:36 +0000917
918 Expr *expr = IList->getInit(Index);
919 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-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 McCallb934c2d2010-11-11 00:46:36 +0000924
925 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
926 StructuredIndex);
927 return;
928 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-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 McCallb934c2d2010-11-11 00:46:36 +0000933 hadError = true;
934 ++Index;
935 ++StructuredIndex;
936 return;
937 }
938
Sebastian Redl14b0c192011-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 McCallb934c2d2010-11-11 00:46:36 +0000946 ExprResult Result =
947 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000948 SemaRef.Owned(expr),
949 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000957
John McCallb934c2d2010-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 Naroff0cca7492008-05-01 22:18:59 +0000968}
969
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000970void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
971 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000972 unsigned &Index,
973 InitListExpr *StructuredList,
974 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000975 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-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 Redl14b0c192011-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 Gregor930d8b52009-01-30 22:09:00 +0000985 hadError = true;
986 ++Index;
987 ++StructuredIndex;
988 return;
989 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000990
991 Expr *expr = IList->getInit(Index);
Sebastian Redl13dc8f92011-11-27 16:50:07 +0000992 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redl14b0c192011-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 Gregor930d8b52009-01-30 22:09:00 +00001025}
1026
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001027void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001028 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001029 unsigned &Index,
1030 InitListExpr *StructuredList,
1031 unsigned &StructuredIndex) {
John McCall20e047a2010-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 Carlsson46f46592010-01-23 19:55:29 +00001036
Sebastian Redl3ff5c862011-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 McCall20e047a2010-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 Redl14b0c192011-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 McCall20e047a2010-10-30 00:11:39 +00001057 ExprResult Result =
1058 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001059 SemaRef.Owned(Init),
1060 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-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 Takumidfbb02a2011-01-27 07:10:08 +00001067
John McCall20e047a2010-10-30 00:11:39 +00001068 if (ResultExpr != Init) {
1069 // The type was promoted, update initializer list.
1070 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001071 }
1072 }
John McCall20e047a2010-10-30 00:11:39 +00001073 if (hadError)
1074 ++StructuredIndex;
1075 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001076 UpdateStructuredListElement(StructuredList, StructuredIndex,
1077 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001078 ++Index;
1079 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001080 }
Mike Stump1eb44332009-09-09 15:08:12 +00001081
John McCall20e047a2010-10-30 00:11:39 +00001082 InitializedEntity ElementEntity =
1083 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001084
John McCall20e047a2010-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 Redl3ff5c862011-10-16 18:19:20 +00001087 if (Index >= IList->getNumInits()) {
1088 if (VerifyOnly)
1089 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001090 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001091 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001092
John McCall20e047a2010-10-30 00:11:39 +00001093 ElementEntity.setElementIndex(Index);
1094 CheckSubElementType(ElementEntity, IList, elementType, Index,
1095 StructuredList, StructuredIndex);
1096 }
1097 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001098 }
John McCall20e047a2010-10-30 00:11:39 +00001099
1100 InitializedEntity ElementEntity =
1101 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001102
John McCall20e047a2010-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 Takumidfbb02a2011-01-27 07:10:08 +00001108
John McCall20e047a2010-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 Takumidfbb02a2011-01-27 07:10:08 +00001120
John McCall20e047a2010-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 Wilsone86d78c2010-11-10 21:56:12 +00001125 IVT->getVectorKind());
John McCall20e047a2010-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 Redl3ff5c862011-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 Naroff0cca7492008-05-01 22:18:59 +00001140}
1141
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001142void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001143 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001144 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001145 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001146 unsigned &Index,
1147 InitListExpr *StructuredList,
1148 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001149 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1150
Steve Naroff0cca7492008-05-01 22:18:59 +00001151 // Check for the special-case of initializing an array with a string.
1152 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001153 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001154 SemaRef.Context)) {
Douglas Gregor4c678342009-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 Redl14b0c192011-09-24 17:48:00 +00001160 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001161 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001162 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1163 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1164 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001165 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001166 return;
1167 }
1168 }
John McCallce6c9b72011-02-21 07:22:22 +00001169 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-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 Redl14b0c192011-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 Friedman638e1442008-05-25 13:22:35 +00001177 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001178 ++Index;
1179 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001180 return;
1181 }
1182
Douglas Gregor05c13a32009-01-22 00:58:24 +00001183 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001184 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1185 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001186 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001187 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001188 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001189 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001190 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001191 maxElementsKnown = true;
1192 }
1193
John McCallce6c9b72011-02-21 07:22:22 +00001194 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-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 Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +00001203
Douglas Gregor87f55cf2009-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 Carlsson9a8a70e2010-01-23 22:49:02 +00001206 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001207 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001208 StructuredList, StructuredIndex, true,
1209 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001210 hadError = true;
1211 continue;
1212 }
1213
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001214 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001215 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001216 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001217 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001218 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001219
Douglas Gregor87f55cf2009-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 Gregor05c13a32009-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 Naroff0cca7492008-05-01 22:18:59 +00001231 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001232
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001233 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001234 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001235 Entity);
1236 // Check this element.
1237 CheckSubElementType(ElementEntity, IList, elementType, Index,
1238 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-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 Naroff0cca7492008-05-01 22:18:59 +00001245 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001246 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001247 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001248 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001249 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001250 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-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 Lattner08202542009-02-24 22:50:46 +00001253 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001254 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001255 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001256
Mike Stump1eb44332009-09-09 15:08:12 +00001257 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001258 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001259 }
Sebastian Redl3ff5c862011-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 Naroff0cca7492008-05-01 22:18:59 +00001268}
1269
Eli Friedmanf40fd6b2011-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 Redl14b0c192011-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 Friedmanf40fd6b2011-08-23 22:24:57 +00001305
1306 return FlexArrayDiag != diag::ext_flexible_array_init;
1307}
1308
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001309void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001310 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001311 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001312 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001313 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001314 unsigned &Index,
1315 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001316 unsigned &StructuredIndex,
1317 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001318 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Eli Friedmanb85f7072008-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 Stump1eb44332009-09-09 15:08:12 +00001325 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001326
1327 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-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 Redl14b0c192011-09-24 17:48:00 +00001337 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001338 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001339 }
1340 }
1341 return;
1342 }
1343
Douglas Gregor05c13a32009-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 Kremenek6217b802009-07-29 21:53:49 +00001348 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001349 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001350 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001351 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-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 Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +00001361
Douglas Gregor87f55cf2009-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 Carlsson9a8a70e2010-01-23 22:49:02 +00001364 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001365 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001366 StructuredList, StructuredIndex,
1367 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001368 hadError = true;
1369
Douglas Gregordfb5e592009-02-12 19:00:39 +00001370 InitializedSomething = true;
John McCall80639de2010-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 Gregor05c13a32009-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 Gregordfb5e592009-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 Gregor44b43212008-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 Gregor0bb76892009-01-29 16:53:55 +00001391 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001392 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001393 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001394 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001395 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001396
Douglas Gregor54001c12011-06-29 21:51:31 +00001397 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-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 Gregor54001c12011-06-29 21:51:31 +00001405 ++Index;
1406 ++Field;
1407 hadError = true;
1408 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001409 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001410
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001411 InitializedEntity MemberEntity =
1412 InitializedEntity::InitializeMember(*Field, &Entity);
1413 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1414 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001415 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001416
Sebastian Redl14b0c192011-09-24 17:48:00 +00001417 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001418 // Initialize the first field within the union.
1419 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001420 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001421
1422 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001423 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001424
John McCall80639de2010-03-11 19:32:38 +00001425 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001426 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1427 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1428 !DeclType->isUnionType()) {
John McCall80639de2010-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 Redl3ff5c862011-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 Stump1eb44332009-09-09 15:08:12 +00001452 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001453 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001454 return;
1455
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001456 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1457 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001458 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001459 ++Index;
1460 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001461 }
1462
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001463 InitializedEntity MemberEntity =
1464 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001465
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001466 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001467 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001468 StructuredList, StructuredIndex);
1469 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001471 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001472}
Steve Naroff0cca7492008-05-01 22:18:59 +00001473
Douglas Gregorffb4b6e2009-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 Gregorffb4b6e2009-04-15 06:41:24 +00001478static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001479 DesignatedInitExpr *DIE,
1480 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001481 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001482 typedef DesignatedInitExpr::Designator Designator;
1483
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001484 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001485 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-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 Stump1eb44332009-09-09 15:08:12 +00001489 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-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 Picheta0e27f02010-12-22 03:46:10 +00001495 assert(isa<FieldDecl>(*PI));
1496 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-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 Gregor319d57f2010-01-06 23:17:19 +00001502 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001503 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001504}
Mike Stump1eb44332009-09-09 15:08:12 +00001505
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001506/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-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 Gregorffb4b6e2009-04-15 06:41:24 +00001516 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001517 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001518}
1519
Sebastian Redl14b0c192011-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 Gregor05c13a32009-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 Stump1eb44332009-09-09 15:08:12 +00001538/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001539/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001540///
1541/// @param IList The initializer list in which this designated
1542/// initializer occurs.
1543///
Douglas Gregor71199712009-04-15 04:56:10 +00001544/// @param DIE The designated initializer expression.
1545///
1546/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-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 Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +00001554///
Douglas Gregor87f55cf2009-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 Gregor05c13a32009-01-22 00:58:24 +00001558///
1559/// @param Index Index into @p IList where the designated initializer
1560/// @p DIE occurs.
1561///
Douglas Gregor4c678342009-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 Gregor05c13a32009-01-22 00:58:24 +00001566/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001567bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001568InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001569 InitListExpr *IList,
Sebastian Redl14b0c192011-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 Gregoreeb15d42009-02-04 22:46:25 +00001578 bool FinishSubobjectInit,
1579 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001580 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001581 // Check the actual initialization for the designated object type.
1582 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-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 Carlsson9a8a70e2010-01-23 22:49:02 +00001590 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001591 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-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 Gregor87f55cf2009-01-22 23:26:18 +00001599 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001600 }
1601
Douglas Gregor71199712009-04-15 04:56:10 +00001602 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-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 Gregor4c678342009-01-28 21:54:33 +00001617
Douglas Gregor87f55cf2009-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 Stump1eb44332009-09-09 15:08:12 +00001627 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001628 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001629 if (!RT) {
1630 SourceLocation Loc = D->getDotLoc();
1631 if (Loc.isInvalid())
1632 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001633 if (!VerifyOnly)
1634 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1635 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001636 ++Index;
1637 return true;
1638 }
1639
Douglas Gregor4c678342009-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 Gregorffb4b6e2009-04-15 06:41:24 +00001643 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001644 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001645 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001646 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001647 Field = RT->getDecl()->field_begin(),
1648 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001649 for (; Field != FieldEnd; ++Field) {
1650 if (Field->isUnnamedBitfield())
1651 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001652
Francois Picheta0e27f02010-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 Redl14b0c192011-09-24 17:48:00 +00001658 // In verify mode, don't modify the original.
1659 if (VerifyOnly)
1660 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001661 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1662 D = DIE->getDesignator(DesigIdx);
1663 break;
1664 }
1665 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001666 if (KnownField && KnownField == *Field)
1667 break;
1668 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001669 break;
1670
1671 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001672 }
1673
Douglas Gregor4c678342009-01-28 21:54:33 +00001674 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001675 if (VerifyOnly) {
1676 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001677 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001678 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001679
Douglas Gregorffb4b6e2009-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 Stump1eb44332009-09-09 15:08:12 +00001684 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001685 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001686 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001687 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001688 // Name lookup didn't find anything. Determine whether this
1689 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001690 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001691 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-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 Redl7a126a42010-08-31 00:36:30 +00001697 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001698 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001699 std::string CorrectedStr(
1700 Corrected.getAsString(SemaRef.getLangOptions()));
1701 std::string CorrectedQuotedStr(
1702 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001704 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001705 << FieldName << CurrentObjectType << CorrectedQuotedStr
1706 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001707 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001708 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001709 hadError = true;
Douglas Gregorc171e3b2010-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 Gregorc171e3b2010-01-01 00:03:05 +00001716 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001717
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001718 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001719 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001720 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001721 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001722 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001723 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001724 ++Index;
1725 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001726 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001727
Francois Picheta0e27f02010-12-22 03:46:10 +00001728 if (!KnownField) {
Douglas Gregorc171e3b2010-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 Takumidfbb02a2011-01-27 07:10:08 +00001737 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001738 Field->getIdentifier() == ReplacementField->getIdentifier())
1739 break;
1740
1741 ++FieldIndex;
1742 }
1743 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001744 }
Douglas Gregor4c678342009-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 Gregor0bb76892009-01-29 16:53:55 +00001748 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001749 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001750 if (!VerifyOnly)
1751 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001752 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001753
Douglas Gregor54001c12011-06-29 21:51:31 +00001754 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-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 Gregor54001c12011-06-29 21:51:31 +00001761 ++Index;
1762 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001763 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001764
Sebastian Redl14b0c192011-09-24 17:48:00 +00001765 if (!VerifyOnly) {
1766 // Update the designator with the field declaration.
1767 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Sebastian Redl14b0c192011-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 Gregor4c678342009-01-28 21:54:33 +00001774
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001775 // This designator names a flexible array member.
1776 if (Field->getType()->isIncompleteArrayType()) {
1777 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001778 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-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 Redl14b0c192011-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 Gregoreeb15d42009-02-04 22:46:25 +00001791 Invalid = true;
1792 }
1793
Chris Lattner9046c222010-10-10 17:49:49 +00001794 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1795 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001796 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-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 Gregoreeb15d42009-02-04 22:46:25 +00001804 Invalid = true;
1805 }
1806
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001807 // Check GNU flexible array initializer.
1808 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1809 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001810 Invalid = true;
Douglas Gregoreeb15d42009-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 Carlsson8ff9e862010-01-23 23:23:01 +00001822
1823 InitializedEntity MemberEntity =
1824 InitializedEntity::InitializeMember(*Field, &Entity);
1825 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001826 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001827
Douglas Gregoreeb15d42009-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 Takumidfbb02a2011-01-27 07:10:08 +00001841
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001842 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001843 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001844 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1845 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001846 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001847 true, false))
1848 return true;
1849 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001850
1851 // Find the position of the next field to be initialized in this
1852 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001853 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001854 ++FieldIndex;
Douglas Gregor87f55cf2009-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 Gregor4c678342009-01-28 21:54:33 +00001861 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001862 return false;
1863 }
1864
Douglas Gregor34e79462009-01-28 23:36:17 +00001865 if (!FinishSubobjectInit)
1866 return false;
1867
Douglas Gregorffb4b6e2009-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 Gregor87f55cf2009-01-22 23:26:18 +00001872 // Check the remaining fields within this class/struct/union subobject.
1873 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001874
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001875 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001876 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-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 Lattner08202542009-02-24 22:50:46 +00001895 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001896 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001897 if (!VerifyOnly)
1898 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1899 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001900 ++Index;
1901 return true;
1902 }
1903
1904 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001905 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1906 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001907 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001908 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001909 DesignatedEndIndex = DesignatedStartIndex;
1910 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001911 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001912
Mike Stump1eb44332009-09-09 15:08:12 +00001913 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001914 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001915 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001916 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001917 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001918
Chris Lattnere0fd8322011-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 Redl14b0c192011-09-24 17:48:00 +00001925 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001926 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001927 }
1928
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001929 if (isa<ConstantArrayType>(AT)) {
1930 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001931 DesignatedStartIndex
1932 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001933 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001934 DesignatedEndIndex
1935 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001936 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1937 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001938 if (!VerifyOnly)
Sebastian Redl14b0c192011-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 Gregor87f55cf2009-01-22 23:26:18 +00001943 ++Index;
1944 return true;
1945 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001946 } else {
1947 // Make sure the bit-widths and signedness match.
1948 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001949 DesignatedEndIndex
1950 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001951 else if (DesignatedStartIndex.getBitWidth() <
1952 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001953 DesignatedStartIndex
1954 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001955 DesignatedStartIndex.setIsUnsigned(true);
1956 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001957 }
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Douglas Gregor4c678342009-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 Redl14b0c192011-09-24 17:48:00 +00001961 if (!VerifyOnly &&
1962 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001963 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001964 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001965
Douglas Gregor34e79462009-01-28 23:36:17 +00001966 // Repeatedly perform subobject initializations in the range
1967 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001968
Douglas Gregor34e79462009-01-28 23:36:17 +00001969 // Move to the next designator
1970 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1971 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001972
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001973 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001974 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001975
Douglas Gregor34e79462009-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 Takumidfbb02a2011-01-27 07:10:08 +00001980
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001981 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001982 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1983 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001984 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001985 (DesignatedStartIndex == DesignatedEndIndex),
1986 false))
Douglas Gregor34e79462009-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 Gregor87f55cf2009-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 Gregor34e79462009-01-28 23:36:17 +00001998 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001999 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002000 return false;
2001 }
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Douglas Gregor34e79462009-01-28 23:36:17 +00002003 if (!FinishSubobjectInit)
2004 return false;
2005
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002006 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002007 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002008 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002009 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002010 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002011 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002012}
2013
Douglas Gregor4c678342009-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 Redl14b0c192011-09-24 17:48:00 +00002022 if (VerifyOnly)
2023 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-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 Stump1eb44332009-09-09 15:08:12 +00002029
Douglas Gregor4c678342009-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 Stump1eb44332009-09-09 15:08:12 +00002038 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002039 // struct X { int a, b; };
2040 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002041 //
Douglas Gregor4c678342009-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 Stump1eb44332009-09-09 15:08:12 +00002045 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002046 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002047 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00002048 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002049 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002050 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002051 << ExistingInit->getSourceRange();
2052 }
2053
Mike Stump1eb44332009-09-09 15:08:12 +00002054 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002055 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2056 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002057 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002058
Douglas Gregor63982352010-07-13 18:40:04 +00002059 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00002060
Douglas Gregorfa219202009-03-20 23:58:33 +00002061 // Pre-allocate storage for the structured initializer list.
2062 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002063 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002064 bool GotNumInits = false;
2065 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002066 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-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 Gregor08457732009-03-21 18:13:52 +00002070 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002071 GotNumInits = true;
2072 }
Douglas Gregor08457732009-03-21 18:13:52 +00002073 }
2074
Mike Stump1eb44332009-09-09 15:08:12 +00002075 if (const ArrayType *AType
Douglas Gregorfa219202009-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 Kyrtzidisf8b17712011-04-28 18:53:55 +00002081 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002082 NumElements = 0;
2083 }
John McCall183700f2009-09-21 23:43:11 +00002084 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002085 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002086 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002087 RecordDecl *RDecl = RType->getDecl();
2088 if (RDecl->isUnion())
2089 NumElements = 1;
2090 else
Mike Stump1eb44332009-09-09 15:08:12 +00002091 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002092 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002093 }
2094
Ted Kremenek709210f2010-04-13 23:39:13 +00002095 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002096
Douglas Gregor4c678342009-01-28 21:54:33 +00002097 // Link this new initializer list into the structured initializer
2098 // lists.
2099 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002100 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-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 Kremenek709210f2010-04-13 23:39:13 +00002118 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2119 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002120 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00002121 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002122 diag::warn_initializer_overrides)
2123 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002124 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002125 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002126 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002127 << PrevInit->getSourceRange();
2128 }
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Douglas Gregor4c678342009-01-28 21:54:33 +00002130 ++StructuredIndex;
2131}
2132
Douglas Gregor05c13a32009-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 Lattner3bf68932009-04-25 21:59:05 +00002135/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-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 Stump1eb44332009-09-09 15:08:12 +00002140static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00002141CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002142 SourceLocation Loc = Index->getSourceRange().getBegin();
2143
2144 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00002145 if (S.VerifyIntegerConstantExpression(Index, &Value))
2146 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002147
Chris Lattner3bf68932009-04-25 21:59:05 +00002148 if (Value.isSigned() && Value.isNegative())
2149 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002150 << Value.toString(10) << Index->getSourceRange();
2151
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002152 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002153 return false;
2154}
2155
John McCall60d7b3a2010-08-24 06:29:42 +00002156ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002157 SourceLocation Loc,
2158 bool GNUSyntax,
2159 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002160 typedef DesignatedInitExpr::Designator ASTDesignator;
2161
2162 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002163 SmallVector<ASTDesignator, 32> Designators;
2164 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-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 Stump1eb44332009-09-09 15:08:12 +00002171 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-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 Gregor9ea62762009-05-21 23:17:49 +00002178 if (!Index->isTypeDependent() &&
2179 !Index->isValueDependent() &&
2180 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002181 Invalid = true;
2182 else {
2183 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002184 D.getLBracketLoc(),
Douglas Gregor05c13a32009-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 Gregor9ea62762009-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 Gregor05c13a32009-01-22 00:58:24 +00002204 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002205 else {
2206 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002207 if (StartDependent || EndDependent) {
2208 // Nothing to compute.
2209 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002210 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002211 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002212 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002213
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002214 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002215 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002216 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002217 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2218 Invalid = true;
2219 } else {
2220 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002221 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002222 D.getEllipsisLoc(),
2223 D.getRBracketLoc()));
2224 InitExpressions.push_back(StartIndex);
2225 InitExpressions.push_back(EndIndex);
2226 }
Douglas Gregor05c13a32009-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 Foadbeaaccd2009-05-21 09:52:38 +00002240 = DesignatedInitExpr::Create(Context,
2241 Designators.data(), Designators.size(),
2242 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002243 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002245 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002246 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2247 << DIE->getSourceRange();
2248 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002249 Diag(DIE->getLocStart(), diag::ext_designated_init)
2250 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002251
Douglas Gregor05c13a32009-01-22 00:58:24 +00002252 return Owned(DIE);
2253}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002254
Douglas Gregor20093b42009-12-09 23:02:17 +00002255//===----------------------------------------------------------------------===//
2256// Initialization entity
2257//===----------------------------------------------------------------------===//
2258
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002259InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002260 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002261 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002262{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002263 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2264 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002265 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002266 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002267 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002268 Type = VT->getElementType();
2269 } else {
2270 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2271 assert(CT && "Unexpected type");
2272 Kind = EK_ComplexElement;
2273 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002274 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002275}
2276
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002277InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002278 CXXBaseSpecifier *Base,
2279 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002280{
2281 InitializedEntity Result;
2282 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002283 Result.Base = reinterpret_cast<uintptr_t>(Base);
2284 if (IsInheritedVirtualBase)
2285 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002286
Douglas Gregord6542d82009-12-22 15:35:07 +00002287 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002288 return Result;
2289}
2290
Douglas Gregor99a2e602009-12-16 01:38:02 +00002291DeclarationName InitializedEntity::getName() const {
2292 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002293 case EK_Parameter: {
2294 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2295 return (D ? D->getDeclName() : DeclarationName());
2296 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002297
2298 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002299 case EK_Member:
2300 return VariableOrMember->getDeclName();
2301
2302 case EK_Result:
2303 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002304 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002305 case EK_Temporary:
2306 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002307 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002308 case EK_ArrayElement:
2309 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002310 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002311 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002312 return DeclarationName();
2313 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002314
Douglas Gregor99a2e602009-12-16 01:38:02 +00002315 // Silence GCC warning
2316 return DeclarationName();
2317}
2318
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002319DeclaratorDecl *InitializedEntity::getDecl() const {
2320 switch (getKind()) {
2321 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002322 case EK_Member:
2323 return VariableOrMember;
2324
John McCallf85e1932011-06-15 23:02:42 +00002325 case EK_Parameter:
2326 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2327
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002328 case EK_Result:
2329 case EK_Exception:
2330 case EK_New:
2331 case EK_Temporary:
2332 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002333 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002334 case EK_ArrayElement:
2335 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002336 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002337 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002338 return 0;
2339 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002340
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002341 // Silence GCC warning
2342 return 0;
2343}
2344
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002345bool InitializedEntity::allowsNRVO() const {
2346 switch (getKind()) {
2347 case EK_Result:
2348 case EK_Exception:
2349 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002350
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002351 case EK_Variable:
2352 case EK_Parameter:
2353 case EK_Member:
2354 case EK_New:
2355 case EK_Temporary:
2356 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002357 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002358 case EK_ArrayElement:
2359 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002360 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002361 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002362 break;
2363 }
2364
2365 return false;
2366}
2367
Douglas Gregor20093b42009-12-09 23:02:17 +00002368//===----------------------------------------------------------------------===//
2369// Initialization sequence
2370//===----------------------------------------------------------------------===//
2371
2372void InitializationSequence::Step::Destroy() {
2373 switch (Kind) {
2374 case SK_ResolveAddressOfOverloadedFunction:
2375 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002376 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002377 case SK_CastDerivedToBaseLValue:
2378 case SK_BindReference:
2379 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002380 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002381 case SK_UserConversion:
2382 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002383 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002384 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002385 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002386 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002387 case SK_UnwrapInitList:
2388 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002389 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002390 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002391 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002392 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002393 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002394 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002395 case SK_PassByIndirectCopyRestore:
2396 case SK_PassByIndirectRestore:
2397 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002398 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002399
Douglas Gregor20093b42009-12-09 23:02:17 +00002400 case SK_ConversionSequence:
2401 delete ICS;
2402 }
2403}
2404
Douglas Gregorb70cf442010-03-26 20:14:36 +00002405bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002406 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002407}
2408
2409bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002410 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002411 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002412
Douglas Gregorb70cf442010-03-26 20:14:36 +00002413 switch (getFailureKind()) {
2414 case FK_TooManyInitsForReference:
2415 case FK_ArrayNeedsInitList:
2416 case FK_ArrayNeedsInitListOrStringLiteral:
2417 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2418 case FK_NonConstLValueReferenceBindingToTemporary:
2419 case FK_NonConstLValueReferenceBindingToUnrelated:
2420 case FK_RValueReferenceBindingToLValue:
2421 case FK_ReferenceInitDropsQualifiers:
2422 case FK_ReferenceInitFailed:
2423 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002424 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002425 case FK_TooManyInitsForScalar:
2426 case FK_ReferenceBindingToInitList:
2427 case FK_InitListBadDestinationType:
2428 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002429 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002430 case FK_ArrayTypeMismatch:
2431 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002432 case FK_ListInitializationFailed:
John McCall5acb0c92011-10-17 18:40:02 +00002433 case FK_PlaceholderType:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002434 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002435
Douglas Gregorb70cf442010-03-26 20:14:36 +00002436 case FK_ReferenceInitOverloadFailed:
2437 case FK_UserConversionOverloadFailed:
2438 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002439 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002440 return FailedOverloadResult == OR_Ambiguous;
2441 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002442
Douglas Gregorb70cf442010-03-26 20:14:36 +00002443 return false;
2444}
2445
Douglas Gregord6e44a32010-04-16 22:09:46 +00002446bool InitializationSequence::isConstructorInitialization() const {
2447 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2448}
2449
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002450bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2451 const Expr *Initializer,
2452 bool *isInitializerConstant,
2453 APValue *ConstantValue) const {
2454 if (Steps.empty() || Initializer->isValueDependent())
2455 return false;
2456
2457 const Step &LastStep = Steps.back();
2458 if (LastStep.Kind != SK_ConversionSequence)
2459 return false;
2460
2461 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2462 const StandardConversionSequence *SCS = NULL;
2463 switch (ICS.getKind()) {
2464 case ImplicitConversionSequence::StandardConversion:
2465 SCS = &ICS.Standard;
2466 break;
2467 case ImplicitConversionSequence::UserDefinedConversion:
2468 SCS = &ICS.UserDefined.After;
2469 break;
2470 case ImplicitConversionSequence::AmbiguousConversion:
2471 case ImplicitConversionSequence::EllipsisConversion:
2472 case ImplicitConversionSequence::BadConversion:
2473 return false;
2474 }
2475
2476 // Check if SCS represents a narrowing conversion, according to C++0x
2477 // [dcl.init.list]p7:
2478 //
2479 // A narrowing conversion is an implicit conversion ...
2480 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2481 QualType FromType = SCS->getToType(0);
2482 QualType ToType = SCS->getToType(1);
2483 switch (PossibleNarrowing) {
2484 // * from a floating-point type to an integer type, or
2485 //
2486 // * from an integer type or unscoped enumeration type to a floating-point
2487 // type, except where the source is a constant expression and the actual
2488 // value after conversion will fit into the target type and will produce
2489 // the original value when converted back to the original type, or
2490 case ICK_Floating_Integral:
2491 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2492 *isInitializerConstant = false;
2493 return true;
2494 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2495 llvm::APSInt IntConstantValue;
2496 if (Initializer &&
2497 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2498 // Convert the integer to the floating type.
2499 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2500 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2501 llvm::APFloat::rmNearestTiesToEven);
2502 // And back.
2503 llvm::APSInt ConvertedValue = IntConstantValue;
2504 bool ignored;
2505 Result.convertToInteger(ConvertedValue,
2506 llvm::APFloat::rmTowardZero, &ignored);
2507 // If the resulting value is different, this was a narrowing conversion.
2508 if (IntConstantValue != ConvertedValue) {
2509 *isInitializerConstant = true;
2510 *ConstantValue = APValue(IntConstantValue);
2511 return true;
2512 }
2513 } else {
2514 // Variables are always narrowings.
2515 *isInitializerConstant = false;
2516 return true;
2517 }
2518 }
2519 return false;
2520
2521 // * from long double to double or float, or from double to float, except
2522 // where the source is a constant expression and the actual value after
2523 // conversion is within the range of values that can be represented (even
2524 // if it cannot be represented exactly), or
2525 case ICK_Floating_Conversion:
2526 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2527 // FromType is larger than ToType.
2528 Expr::EvalResult InitializerValue;
2529 // FIXME: Check whether Initializer is a constant expression according
2530 // to C++0x [expr.const], rather than just whether it can be folded.
Richard Smith51f47082011-10-29 00:50:52 +00002531 if (Initializer->EvaluateAsRValue(InitializerValue, Ctx) &&
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002532 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2533 // Constant! (Except for FIXME above.)
2534 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2535 // Convert the source value into the target type.
2536 bool ignored;
2537 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2538 Ctx.getFloatTypeSemantics(ToType),
2539 llvm::APFloat::rmNearestTiesToEven, &ignored);
2540 // If there was no overflow, the source value is within the range of
2541 // values that can be represented.
2542 if (ConvertStatus & llvm::APFloat::opOverflow) {
2543 *isInitializerConstant = true;
2544 *ConstantValue = InitializerValue.Val;
2545 return true;
2546 }
2547 } else {
2548 *isInitializerConstant = false;
2549 return true;
2550 }
2551 }
2552 return false;
2553
2554 // * from an integer type or unscoped enumeration type to an integer type
2555 // that cannot represent all the values of the original type, except where
2556 // the source is a constant expression and the actual value after
2557 // conversion will fit into the target type and will produce the original
2558 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002559 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002560 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2561 // Boolean conversions can be from pointers and pointers to members
2562 // [conv.bool], and those aren't considered narrowing conversions.
2563 return false;
2564 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002565 case ICK_Integral_Conversion: {
2566 assert(FromType->isIntegralOrUnscopedEnumerationType());
2567 assert(ToType->isIntegralOrUnscopedEnumerationType());
2568 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2569 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2570 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2571 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2572
2573 if (FromWidth > ToWidth ||
2574 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2575 // Not all values of FromType can be represented in ToType.
2576 llvm::APSInt InitializerValue;
2577 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2578 *isInitializerConstant = true;
2579 *ConstantValue = APValue(InitializerValue);
2580
2581 // Add a bit to the InitializerValue so we don't have to worry about
2582 // signed vs. unsigned comparisons.
2583 InitializerValue = InitializerValue.extend(
2584 InitializerValue.getBitWidth() + 1);
2585 // Convert the initializer to and from the target width and signed-ness.
2586 llvm::APSInt ConvertedValue = InitializerValue;
2587 ConvertedValue = ConvertedValue.trunc(ToWidth);
2588 ConvertedValue.setIsSigned(ToSigned);
2589 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2590 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2591 // If the result is different, this was a narrowing conversion.
2592 return ConvertedValue != InitializerValue;
2593 } else {
2594 // Variables are always narrowings.
2595 *isInitializerConstant = false;
2596 return true;
2597 }
2598 }
2599 return false;
2600 }
2601
2602 default:
2603 // Other kinds of conversions are not narrowings.
2604 return false;
2605 }
2606}
2607
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002608void
2609InitializationSequence
2610::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2611 DeclAccessPair Found,
2612 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002613 Step S;
2614 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2615 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002616 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002617 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002618 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002619 Steps.push_back(S);
2620}
2621
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002622void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002623 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002624 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002625 switch (VK) {
2626 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2627 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2628 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002629 default: llvm_unreachable("No such category");
2630 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002631 S.Type = BaseType;
2632 Steps.push_back(S);
2633}
2634
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002635void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002636 bool BindingTemporary) {
2637 Step S;
2638 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2639 S.Type = T;
2640 Steps.push_back(S);
2641}
2642
Douglas Gregor523d46a2010-04-18 07:40:54 +00002643void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2644 Step S;
2645 S.Kind = SK_ExtraneousCopyToTemporary;
2646 S.Type = T;
2647 Steps.push_back(S);
2648}
2649
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002650void
2651InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2652 DeclAccessPair FoundDecl,
2653 QualType T,
2654 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002655 Step S;
2656 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002657 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002658 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002659 S.Function.Function = Function;
2660 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002661 Steps.push_back(S);
2662}
2663
2664void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002665 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002666 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002667 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002668 switch (VK) {
2669 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002670 S.Kind = SK_QualificationConversionRValue;
2671 break;
John McCall5baba9d2010-08-25 10:28:54 +00002672 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002673 S.Kind = SK_QualificationConversionXValue;
2674 break;
John McCall5baba9d2010-08-25 10:28:54 +00002675 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002676 S.Kind = SK_QualificationConversionLValue;
2677 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002678 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002679 S.Type = Ty;
2680 Steps.push_back(S);
2681}
2682
2683void InitializationSequence::AddConversionSequenceStep(
2684 const ImplicitConversionSequence &ICS,
2685 QualType T) {
2686 Step S;
2687 S.Kind = SK_ConversionSequence;
2688 S.Type = T;
2689 S.ICS = new ImplicitConversionSequence(ICS);
2690 Steps.push_back(S);
2691}
2692
Douglas Gregord87b61f2009-12-10 17:56:55 +00002693void InitializationSequence::AddListInitializationStep(QualType T) {
2694 Step S;
2695 S.Kind = SK_ListInitialization;
2696 S.Type = T;
2697 Steps.push_back(S);
2698}
2699
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002700void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002701InitializationSequence
2702::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2703 AccessSpecifier Access,
2704 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002705 bool HadMultipleCandidates,
2706 bool FromInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002707 Step S;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002708 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002709 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002710 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002711 S.Function.Function = Constructor;
2712 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002713 Steps.push_back(S);
2714}
2715
Douglas Gregor71d17402009-12-15 00:01:57 +00002716void InitializationSequence::AddZeroInitializationStep(QualType T) {
2717 Step S;
2718 S.Kind = SK_ZeroInitialization;
2719 S.Type = T;
2720 Steps.push_back(S);
2721}
2722
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002723void InitializationSequence::AddCAssignmentStep(QualType T) {
2724 Step S;
2725 S.Kind = SK_CAssignment;
2726 S.Type = T;
2727 Steps.push_back(S);
2728}
2729
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002730void InitializationSequence::AddStringInitStep(QualType T) {
2731 Step S;
2732 S.Kind = SK_StringInit;
2733 S.Type = T;
2734 Steps.push_back(S);
2735}
2736
Douglas Gregor569c3162010-08-07 11:51:51 +00002737void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2738 Step S;
2739 S.Kind = SK_ObjCObjectConversion;
2740 S.Type = T;
2741 Steps.push_back(S);
2742}
2743
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002744void InitializationSequence::AddArrayInitStep(QualType T) {
2745 Step S;
2746 S.Kind = SK_ArrayInit;
2747 S.Type = T;
2748 Steps.push_back(S);
2749}
2750
John McCallf85e1932011-06-15 23:02:42 +00002751void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2752 bool shouldCopy) {
2753 Step s;
2754 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2755 : SK_PassByIndirectRestore);
2756 s.Type = type;
2757 Steps.push_back(s);
2758}
2759
2760void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2761 Step S;
2762 S.Kind = SK_ProduceObjCObject;
2763 S.Type = T;
2764 Steps.push_back(S);
2765}
2766
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002767void InitializationSequence::RewrapReferenceInitList(QualType T,
2768 InitListExpr *Syntactic) {
2769 assert(Syntactic->getNumInits() == 1 &&
2770 "Can only rewrap trivial init lists.");
2771 Step S;
2772 S.Kind = SK_UnwrapInitList;
2773 S.Type = Syntactic->getInit(0)->getType();
2774 Steps.insert(Steps.begin(), S);
2775
2776 S.Kind = SK_RewrapInitList;
2777 S.Type = T;
2778 S.WrappingSyntacticList = Syntactic;
2779 Steps.push_back(S);
2780}
2781
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002782void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002783 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002784 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002785 this->Failure = Failure;
2786 this->FailedOverloadResult = Result;
2787}
2788
2789//===----------------------------------------------------------------------===//
2790// Attempt initialization
2791//===----------------------------------------------------------------------===//
2792
John McCallf85e1932011-06-15 23:02:42 +00002793static void MaybeProduceObjCObject(Sema &S,
2794 InitializationSequence &Sequence,
2795 const InitializedEntity &Entity) {
2796 if (!S.getLangOptions().ObjCAutoRefCount) return;
2797
2798 /// When initializing a parameter, produce the value if it's marked
2799 /// __attribute__((ns_consumed)).
2800 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2801 if (!Entity.isParameterConsumed())
2802 return;
2803
2804 assert(Entity.getType()->isObjCRetainableType() &&
2805 "consuming an object of unretainable type?");
2806 Sequence.AddProduceObjCObjectStep(Entity.getType());
2807
2808 /// When initializing a return value, if the return type is a
2809 /// retainable type, then returns need to immediately retain the
2810 /// object. If an autorelease is required, it will be done at the
2811 /// last instant.
2812 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2813 if (!Entity.getType()->isObjCRetainableType())
2814 return;
2815
2816 Sequence.AddProduceObjCObjectStep(Entity.getType());
2817 }
2818}
2819
Sebastian Redl10f04a62011-12-22 14:44:04 +00002820/// \brief When initializing from init list via constructor, deal with the
2821/// empty init list and std::initializer_list special cases.
2822///
2823/// \return True if this was a special case, false otherwise.
2824static bool TryListConstructionSpecialCases(Sema &S,
2825 Expr **Args, unsigned NumArgs,
2826 CXXRecordDecl *DestRecordDecl,
2827 QualType DestType,
2828 InitializationSequence &Sequence) {
2829 // C++0x [dcl.init.list]p3:
2830 // List-initialization of an object of type T is defined as follows:
2831 // - If the initializer list has no elements and T is a class type with
2832 // a default constructor, the object is value-initialized.
2833 if (NumArgs == 0) {
2834 if (CXXConstructorDecl *DefaultConstructor =
2835 S.LookupDefaultConstructor(DestRecordDecl)) {
2836 if (DefaultConstructor->isDeleted() ||
2837 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2838 // Fake an overload resolution failure.
2839 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2840 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2841 DefaultConstructor->getAccess());
2842 if (FunctionTemplateDecl *ConstructorTmpl =
2843 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2844 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2845 /*ExplicitArgs*/ 0,
2846 Args, NumArgs, CandidateSet,
2847 /*SuppressUserConversions*/ false);
2848 else
2849 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2850 Args, NumArgs, CandidateSet,
2851 /*SuppressUserConversions*/ false);
2852 Sequence.SetOverloadFailure(
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002853 InitializationSequence::FK_ListConstructorOverloadFailed,
2854 OR_Deleted);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002855 } else
2856 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2857 DefaultConstructor->getAccess(),
2858 DestType,
2859 /*MultipleCandidates=*/false,
2860 /*FromInitList=*/true);
2861 return true;
2862 }
2863 }
2864
2865 // - Otherwise, if T is a specialization of std::initializer_list, [...]
2866 // FIXME: Implement.
2867
2868 // Not a special case.
2869 return false;
2870}
2871
2872/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2873/// enumerates the constructors of the initialized entity and performs overload
2874/// resolution to select the best.
2875/// If FromInitList is true, this is list-initialization of a non-aggregate
2876/// class type.
2877static void TryConstructorInitialization(Sema &S,
2878 const InitializedEntity &Entity,
2879 const InitializationKind &Kind,
2880 Expr **Args, unsigned NumArgs,
2881 QualType DestType,
2882 InitializationSequence &Sequence,
2883 bool FromInitList = false) {
2884 // Check constructor arguments for self reference.
2885 if (DeclaratorDecl *DD = Entity.getDecl())
2886 // Parameters arguments are occassionially constructed with itself,
2887 // for instance, in recursive functions. Skip them.
2888 if (!isa<ParmVarDecl>(DD))
2889 for (unsigned i = 0; i < NumArgs; ++i)
2890 S.CheckSelfReference(DD, Args[i]);
2891
2892 // Build the candidate set directly in the initialization sequence
2893 // structure, so that it will persist if we fail.
2894 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2895 CandidateSet.clear();
2896
2897 // Determine whether we are allowed to call explicit constructors or
2898 // explicit conversion operators.
2899 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2900 Kind.getKind() == InitializationKind::IK_Value ||
2901 Kind.getKind() == InitializationKind::IK_Default);
2902
2903 // The type we're constructing needs to be complete.
2904 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2905 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2906 }
2907
2908 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2909 assert(DestRecordType && "Constructor initialization requires record type");
2910 CXXRecordDecl *DestRecordDecl
2911 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2912
2913 if (FromInitList &&
2914 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2915 DestType, Sequence))
2916 return;
2917
2918 // - Otherwise, if T is a class type, constructors are considered. The
2919 // applicable constructors are enumerated, and the best one is chosen
2920 // through overload resolution.
2921 DeclContext::lookup_iterator Con, ConEnd;
2922 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2923 Con != ConEnd; ++Con) {
2924 NamedDecl *D = *Con;
2925 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2926 bool SuppressUserConversions = false;
2927
2928 // Find the constructor (which may be a template).
2929 CXXConstructorDecl *Constructor = 0;
2930 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2931 if (ConstructorTmpl)
2932 Constructor = cast<CXXConstructorDecl>(
2933 ConstructorTmpl->getTemplatedDecl());
2934 else {
2935 Constructor = cast<CXXConstructorDecl>(D);
2936
2937 // If we're performing copy initialization using a copy constructor, we
2938 // suppress user-defined conversions on the arguments.
2939 // FIXME: Move constructors?
2940 if (Kind.getKind() == InitializationKind::IK_Copy &&
2941 Constructor->isCopyConstructor())
2942 SuppressUserConversions = true;
2943 }
2944
2945 if (!Constructor->isInvalidDecl() &&
2946 (AllowExplicit || !Constructor->isExplicit())) {
2947 if (ConstructorTmpl)
2948 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2949 /*ExplicitArgs*/ 0,
2950 Args, NumArgs, CandidateSet,
2951 SuppressUserConversions);
2952 else
2953 S.AddOverloadCandidate(Constructor, FoundDecl,
2954 Args, NumArgs, CandidateSet,
2955 SuppressUserConversions);
2956 }
2957 }
2958
2959 SourceLocation DeclLoc = Kind.getLocation();
2960
2961 // Perform overload resolution. If it fails, return the failed result.
2962 OverloadCandidateSet::iterator Best;
2963 if (OverloadingResult Result
2964 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002965 Sequence.SetOverloadFailure(FromInitList ?
2966 InitializationSequence::FK_ListConstructorOverloadFailed :
2967 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002968 Result);
2969 return;
2970 }
2971
2972 // C++0x [dcl.init]p6:
2973 // If a program calls for the default initialization of an object
2974 // of a const-qualified type T, T shall be a class type with a
2975 // user-provided default constructor.
2976 if (Kind.getKind() == InitializationKind::IK_Default &&
2977 Entity.getType().isConstQualified() &&
2978 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2979 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2980 return;
2981 }
2982
2983 // Add the constructor initialization step. Any cv-qualification conversion is
2984 // subsumed by the initialization.
2985 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2986 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2987 Sequence.AddConstructorInitializationStep(CtorDecl,
2988 Best->FoundDecl.getAccess(),
2989 DestType, HadMultipleCandidates,
2990 FromInitList);
2991}
2992
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002993static bool
2994ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2995 Expr *Initializer,
2996 QualType &SourceType,
2997 QualType &UnqualifiedSourceType,
2998 QualType UnqualifiedTargetType,
2999 InitializationSequence &Sequence) {
3000 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3001 S.Context.OverloadTy) {
3002 DeclAccessPair Found;
3003 bool HadMultipleCandidates = false;
3004 if (FunctionDecl *Fn
3005 = S.ResolveAddressOfOverloadedFunction(Initializer,
3006 UnqualifiedTargetType,
3007 false, Found,
3008 &HadMultipleCandidates)) {
3009 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3010 HadMultipleCandidates);
3011 SourceType = Fn->getType();
3012 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3013 } else if (!UnqualifiedTargetType->isRecordType()) {
3014 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3015 return true;
3016 }
3017 }
3018 return false;
3019}
3020
3021static void TryReferenceInitializationCore(Sema &S,
3022 const InitializedEntity &Entity,
3023 const InitializationKind &Kind,
3024 Expr *Initializer,
3025 QualType cv1T1, QualType T1,
3026 Qualifiers T1Quals,
3027 QualType cv2T2, QualType T2,
3028 Qualifiers T2Quals,
3029 InitializationSequence &Sequence);
3030
3031static void TryListInitialization(Sema &S,
3032 const InitializedEntity &Entity,
3033 const InitializationKind &Kind,
3034 InitListExpr *InitList,
3035 InitializationSequence &Sequence);
3036
3037/// \brief Attempt list initialization of a reference.
3038static void TryReferenceListInitialization(Sema &S,
3039 const InitializedEntity &Entity,
3040 const InitializationKind &Kind,
3041 InitListExpr *InitList,
3042 InitializationSequence &Sequence)
3043{
3044 // First, catch C++03 where this isn't possible.
3045 if (!S.getLangOptions().CPlusPlus0x) {
3046 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3047 return;
3048 }
3049
3050 QualType DestType = Entity.getType();
3051 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3052 Qualifiers T1Quals;
3053 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3054
3055 // Reference initialization via an initializer list works thus:
3056 // If the initializer list consists of a single element that is
3057 // reference-related to the referenced type, bind directly to that element
3058 // (possibly creating temporaries).
3059 // Otherwise, initialize a temporary with the initializer list and
3060 // bind to that.
3061 if (InitList->getNumInits() == 1) {
3062 Expr *Initializer = InitList->getInit(0);
3063 QualType cv2T2 = Initializer->getType();
3064 Qualifiers T2Quals;
3065 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3066
3067 // If this fails, creating a temporary wouldn't work either.
3068 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3069 T1, Sequence))
3070 return;
3071
3072 SourceLocation DeclLoc = Initializer->getLocStart();
3073 bool dummy1, dummy2, dummy3;
3074 Sema::ReferenceCompareResult RefRelationship
3075 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3076 dummy2, dummy3);
3077 if (RefRelationship >= Sema::Ref_Related) {
3078 // Try to bind the reference here.
3079 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3080 T1Quals, cv2T2, T2, T2Quals, Sequence);
3081 if (Sequence)
3082 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3083 return;
3084 }
3085 }
3086
3087 // Not reference-related. Create a temporary and bind to that.
3088 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3089
3090 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3091 if (Sequence) {
3092 if (DestType->isRValueReferenceType() ||
3093 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3094 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3095 else
3096 Sequence.SetFailed(
3097 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3098 }
3099}
3100
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003101/// \brief Attempt list initialization (C++0x [dcl.init.list])
3102static void TryListInitialization(Sema &S,
3103 const InitializedEntity &Entity,
3104 const InitializationKind &Kind,
3105 InitListExpr *InitList,
3106 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003107 QualType DestType = Entity.getType();
3108
Sebastian Redl14b0c192011-09-24 17:48:00 +00003109 // C++ doesn't allow scalar initialization with more than one argument.
3110 // But C99 complex numbers are scalars and it makes sense there.
3111 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3112 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3113 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3114 return;
3115 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003116 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003117 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003118 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003119 }
3120 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003121 if (S.getLangOptions().CPlusPlus0x)
3122 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3123 InitList->getNumInits(), DestType, Sequence,
3124 /*FromInitList=*/true);
3125 else
3126 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003127 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003128 }
3129
Sebastian Redl14b0c192011-09-24 17:48:00 +00003130 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003131 DestType, /*VerifyOnly=*/true,
3132 Kind.getKind() != InitializationKind::IK_Direct ||
3133 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003134 if (CheckInitList.HadError()) {
3135 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3136 return;
3137 }
3138
3139 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003140 Sequence.AddListInitializationStep(DestType);
3141}
Douglas Gregor20093b42009-12-09 23:02:17 +00003142
3143/// \brief Try a reference initialization that involves calling a conversion
3144/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003145static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3146 const InitializedEntity &Entity,
3147 const InitializationKind &Kind,
3148 Expr *Initializer,
3149 bool AllowRValues,
3150 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003151 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003152 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3153 QualType T1 = cv1T1.getUnqualifiedType();
3154 QualType cv2T2 = Initializer->getType();
3155 QualType T2 = cv2T2.getUnqualifiedType();
3156
3157 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003158 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003159 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003160 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003161 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003162 ObjCConversion,
3163 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003164 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003165 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003166 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003167 (void)ObjCLifetimeConversion;
3168
Douglas Gregor20093b42009-12-09 23:02:17 +00003169 // Build the candidate set directly in the initialization sequence
3170 // structure, so that it will persist if we fail.
3171 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3172 CandidateSet.clear();
3173
3174 // Determine whether we are allowed to call explicit constructors or
3175 // explicit conversion operators.
3176 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003177
Douglas Gregor20093b42009-12-09 23:02:17 +00003178 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003179 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3180 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003181 // The type we're converting to is a class type. Enumerate its constructors
3182 // to see if there is a suitable conversion.
3183 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003184
Douglas Gregor20093b42009-12-09 23:02:17 +00003185 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003186 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00003187 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003188 NamedDecl *D = *Con;
3189 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3190
Douglas Gregor20093b42009-12-09 23:02:17 +00003191 // Find the constructor (which may be a template).
3192 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003193 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003194 if (ConstructorTmpl)
3195 Constructor = cast<CXXConstructorDecl>(
3196 ConstructorTmpl->getTemplatedDecl());
3197 else
John McCall9aa472c2010-03-19 07:35:19 +00003198 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199
Douglas Gregor20093b42009-12-09 23:02:17 +00003200 if (!Constructor->isInvalidDecl() &&
3201 Constructor->isConvertingConstructor(AllowExplicit)) {
3202 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003203 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003204 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003205 &Initializer, 1, CandidateSet,
3206 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003207 else
John McCall9aa472c2010-03-19 07:35:19 +00003208 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003209 &Initializer, 1, CandidateSet,
3210 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003211 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003212 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003213 }
John McCall572fc622010-08-17 07:23:57 +00003214 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3215 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003216
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003217 const RecordType *T2RecordType = 0;
3218 if ((T2RecordType = T2->getAs<RecordType>()) &&
3219 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003220 // The type we're converting from is a class type, enumerate its conversion
3221 // functions.
3222 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3223
John McCalleec51cf2010-01-20 00:46:10 +00003224 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00003225 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003226 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3227 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003228 NamedDecl *D = *I;
3229 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3230 if (isa<UsingShadowDecl>(D))
3231 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003232
Douglas Gregor20093b42009-12-09 23:02:17 +00003233 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3234 CXXConversionDecl *Conv;
3235 if (ConvTemplate)
3236 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3237 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003238 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003239
Douglas Gregor20093b42009-12-09 23:02:17 +00003240 // If the conversion function doesn't return a reference type,
3241 // it can't be considered for this conversion unless we're allowed to
3242 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003243 // FIXME: Do we need to make sure that we only consider conversion
3244 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003245 // break recursion.
3246 if ((AllowExplicit || !Conv->isExplicit()) &&
3247 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3248 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003249 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003250 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003251 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003252 else
John McCall9aa472c2010-03-19 07:35:19 +00003253 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003254 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003255 }
3256 }
3257 }
John McCall572fc622010-08-17 07:23:57 +00003258 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3259 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260
Douglas Gregor20093b42009-12-09 23:02:17 +00003261 SourceLocation DeclLoc = Initializer->getLocStart();
3262
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003264 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003265 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003266 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003267 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003268
Douglas Gregor20093b42009-12-09 23:02:17 +00003269 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00003270
Chandler Carruth25ca4212011-02-25 19:41:05 +00003271 // This is the overload that will actually be used for the initialization, so
3272 // mark it as used.
3273 S.MarkDeclarationReferenced(DeclLoc, Function);
3274
Eli Friedman03981012009-12-11 02:42:07 +00003275 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003276 if (isa<CXXConversionDecl>(Function))
3277 T2 = Function->getResultType();
3278 else
3279 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003280
3281 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003282 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003283 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003284 T2.getNonLValueExprType(S.Context),
3285 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003286
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003288 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003289 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003290 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003291 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003292 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003293 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003294
Douglas Gregor20093b42009-12-09 23:02:17 +00003295 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003296 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003297 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003298 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003299 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003300 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003301 NewDerivedToBase, NewObjCConversion,
3302 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003303 if (NewRefRelationship == Sema::Ref_Incompatible) {
3304 // If the type we've converted to is not reference-related to the
3305 // type we're looking for, then there is another conversion step
3306 // we need to perform to produce a temporary of the right type
3307 // that we'll be binding to.
3308 ImplicitConversionSequence ICS;
3309 ICS.setStandard();
3310 ICS.Standard = Best->FinalConversion;
3311 T2 = ICS.Standard.getToType(2);
3312 Sequence.AddConversionSequenceStep(ICS, T2);
3313 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003314 Sequence.AddDerivedToBaseCastStep(
3315 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003316 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003317 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003318 else if (NewObjCConversion)
3319 Sequence.AddObjCObjectConversionStep(
3320 S.Context.getQualifiedType(T1,
3321 T2.getNonReferenceType().getQualifiers()));
3322
Douglas Gregor20093b42009-12-09 23:02:17 +00003323 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003324 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003325
Douglas Gregor20093b42009-12-09 23:02:17 +00003326 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3327 return OR_Success;
3328}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003329
Richard Smith83da2e72011-10-19 16:55:56 +00003330static void CheckCXX98CompatAccessibleCopy(Sema &S,
3331 const InitializedEntity &Entity,
3332 Expr *CurInitExpr);
3333
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003334/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3335static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003336 const InitializedEntity &Entity,
3337 const InitializationKind &Kind,
3338 Expr *Initializer,
3339 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003340 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003341 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003342 Qualifiers T1Quals;
3343 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003344 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003345 Qualifiers T2Quals;
3346 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003347
Douglas Gregor20093b42009-12-09 23:02:17 +00003348 // If the initializer is the address of an overloaded function, try
3349 // to resolve the overloaded function. If all goes well, T2 is the
3350 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003351 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3352 T1, Sequence))
3353 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003354
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003355 // Delegate everything else to a subfunction.
3356 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3357 T1Quals, cv2T2, T2, T2Quals, Sequence);
3358}
3359
3360/// \brief Reference initialization without resolving overloaded functions.
3361static void TryReferenceInitializationCore(Sema &S,
3362 const InitializedEntity &Entity,
3363 const InitializationKind &Kind,
3364 Expr *Initializer,
3365 QualType cv1T1, QualType T1,
3366 Qualifiers T1Quals,
3367 QualType cv2T2, QualType T2,
3368 Qualifiers T2Quals,
3369 InitializationSequence &Sequence) {
3370 QualType DestType = Entity.getType();
3371 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003372 // Compute some basic properties of the types and the initializer.
3373 bool isLValueRef = DestType->isLValueReferenceType();
3374 bool isRValueRef = !isLValueRef;
3375 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003376 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003377 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003378 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003379 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003380 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003381 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003382
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003384 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003385 // "cv2 T2" as follows:
3386 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003387 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003388 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003389 // Note the analogous bullet points for rvlaue refs to functions. Because
3390 // there are no function rvalues in C++, rvalue refs to functions are treated
3391 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003392 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003393 bool T1Function = T1->isFunctionType();
3394 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003395 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003396 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003397 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003398 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003400 // reference-compatible with "cv2 T2," or
3401 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003402 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003403 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003404 // can occur. However, we do pay attention to whether it is a bit-field
3405 // to decide whether we're actually binding to a temporary created from
3406 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003407 if (DerivedToBase)
3408 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003409 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003410 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003411 else if (ObjCConversion)
3412 Sequence.AddObjCObjectConversionStep(
3413 S.Context.getQualifiedType(T1, T2Quals));
3414
Chandler Carruth5535c382010-01-12 20:32:25 +00003415 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003416 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003417 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003418 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003419 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003420 return;
3421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003422
3423 // - has a class type (i.e., T2 is a class type), where T1 is not
3424 // reference-related to T2, and can be implicitly converted to an
3425 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3426 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003427 // applicable conversion functions (13.3.1.6) and choosing the best
3428 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003429 // If we have an rvalue ref to function type here, the rhs must be
3430 // an rvalue.
3431 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3432 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003433 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003434 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003435 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003436 Sequence);
3437 if (ConvOvlResult == OR_Success)
3438 return;
John McCall1d318332010-01-12 00:44:57 +00003439 if (ConvOvlResult != OR_No_Viable_Function) {
3440 Sequence.SetOverloadFailure(
3441 InitializationSequence::FK_ReferenceInitOverloadFailed,
3442 ConvOvlResult);
3443 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003444 }
3445 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003446
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003447 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003448 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003449 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003450 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003451 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3452 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3453 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003454 Sequence.SetOverloadFailure(
3455 InitializationSequence::FK_ReferenceInitOverloadFailed,
3456 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003457 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003458 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003459 ? (RefRelationship == Sema::Ref_Related
3460 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3461 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3462 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003463
Douglas Gregor20093b42009-12-09 23:02:17 +00003464 return;
3465 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003466
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003467 // - If the initializer expression
3468 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3469 // "cv1 T1" is reference-compatible with "cv2 T2"
3470 // Note: functions are handled below.
3471 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003472 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003473 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003474 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003475 (InitCategory.isXValue() ||
3476 (InitCategory.isPRValue() && T2->isRecordType()) ||
3477 (InitCategory.isPRValue() && T2->isArrayType()))) {
3478 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3479 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003480 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3481 // compiler the freedom to perform a copy here or bind to the
3482 // object, while C++0x requires that we bind directly to the
3483 // object. Hence, we always bind to the object without making an
3484 // extra copy. However, in C++03 requires that we check for the
3485 // presence of a suitable copy constructor:
3486 //
3487 // The constructor that would be used to make the copy shall
3488 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003489 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003490 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith83da2e72011-10-19 16:55:56 +00003491 else if (S.getLangOptions().CPlusPlus0x)
3492 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003493 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003494
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003495 if (DerivedToBase)
3496 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3497 ValueKind);
3498 else if (ObjCConversion)
3499 Sequence.AddObjCObjectConversionStep(
3500 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003501
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003502 if (T1Quals != T2Quals)
3503 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbourne65bfd682011-11-13 00:51:30 +00003505 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003506 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003507 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003508
3509 // - has a class type (i.e., T2 is a class type), where T1 is not
3510 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003511 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3512 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003513 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003514 if (RefRelationship == Sema::Ref_Incompatible) {
3515 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3516 Kind, Initializer,
3517 /*AllowRValues=*/true,
3518 Sequence);
3519 if (ConvOvlResult)
3520 Sequence.SetOverloadFailure(
3521 InitializationSequence::FK_ReferenceInitOverloadFailed,
3522 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003523
Douglas Gregor20093b42009-12-09 23:02:17 +00003524 return;
3525 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003526
Douglas Gregor20093b42009-12-09 23:02:17 +00003527 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3528 return;
3529 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003530
3531 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003532 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003533 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003534 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003535
Douglas Gregor20093b42009-12-09 23:02:17 +00003536 // Determine whether we are allowed to call explicit constructors or
3537 // explicit conversion operators.
3538 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003539
3540 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3541
John McCallf85e1932011-06-15 23:02:42 +00003542 ImplicitConversionSequence ICS
3543 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003544 /*SuppressUserConversions*/ false,
3545 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003546 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003547 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3548 /*AllowObjCWritebackConversion=*/false);
3549
3550 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003551 // FIXME: Use the conversion function set stored in ICS to turn
3552 // this into an overloading ambiguity diagnostic. However, we need
3553 // to keep that set as an OverloadCandidateSet rather than as some
3554 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003555 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3556 Sequence.SetOverloadFailure(
3557 InitializationSequence::FK_ReferenceInitOverloadFailed,
3558 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003559 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3560 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003561 else
3562 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003563 return;
John McCallf85e1932011-06-15 23:02:42 +00003564 } else {
3565 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003566 }
3567
3568 // [...] If T1 is reference-related to T2, cv1 must be the
3569 // same cv-qualification as, or greater cv-qualification
3570 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003571 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3572 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003573 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003574 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003575 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3576 return;
3577 }
3578
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003579 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003580 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003581 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003582 InitCategory.isLValue()) {
3583 Sequence.SetFailed(
3584 InitializationSequence::FK_RValueReferenceBindingToLValue);
3585 return;
3586 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003587
Douglas Gregor20093b42009-12-09 23:02:17 +00003588 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3589 return;
3590}
3591
3592/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003593/// (C++ [dcl.init.string], C99 6.7.8).
3594static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003595 const InitializedEntity &Entity,
3596 const InitializationKind &Kind,
3597 Expr *Initializer,
3598 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003599 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003600}
3601
Douglas Gregor71d17402009-12-15 00:01:57 +00003602/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003603static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003604 const InitializedEntity &Entity,
3605 const InitializationKind &Kind,
3606 InitializationSequence &Sequence) {
3607 // C++ [dcl.init]p5:
3608 //
3609 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003610 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003611
Douglas Gregor71d17402009-12-15 00:01:57 +00003612 // -- if T is an array type, then each element is value-initialized;
3613 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3614 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003615
Douglas Gregor71d17402009-12-15 00:01:57 +00003616 if (const RecordType *RT = T->getAs<RecordType>()) {
3617 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3618 // -- if T is a class type (clause 9) with a user-declared
3619 // constructor (12.1), then the default constructor for T is
3620 // called (and the initialization is ill-formed if T has no
3621 // accessible default constructor);
3622 //
3623 // FIXME: we really want to refer to a single subobject of the array,
3624 // but Entity doesn't have a way to capture that (yet).
3625 if (ClassDecl->hasUserDeclaredConstructor())
3626 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003627
Douglas Gregor16006c92009-12-16 18:50:27 +00003628 // -- if T is a (possibly cv-qualified) non-union class type
3629 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003630 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003631 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003632 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003633 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003634 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003635 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003636 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003637 }
3638 }
3639
Douglas Gregord6542d82009-12-22 15:35:07 +00003640 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003641}
3642
Douglas Gregor99a2e602009-12-16 01:38:02 +00003643/// \brief Attempt default initialization (C++ [dcl.init]p6).
3644static void TryDefaultInitialization(Sema &S,
3645 const InitializedEntity &Entity,
3646 const InitializationKind &Kind,
3647 InitializationSequence &Sequence) {
3648 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003649
Douglas Gregor99a2e602009-12-16 01:38:02 +00003650 // C++ [dcl.init]p6:
3651 // To default-initialize an object of type T means:
3652 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003653 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3654
Douglas Gregor99a2e602009-12-16 01:38:02 +00003655 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3656 // constructor for T is called (and the initialization is ill-formed if
3657 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003658 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003659 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3660 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003662
Douglas Gregor99a2e602009-12-16 01:38:02 +00003663 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664
Douglas Gregor99a2e602009-12-16 01:38:02 +00003665 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003666 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003667 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003668 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003669 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003670 return;
3671 }
3672
3673 // If the destination type has a lifetime property, zero-initialize it.
3674 if (DestType.getQualifiers().hasObjCLifetime()) {
3675 Sequence.AddZeroInitializationStep(Entity.getType());
3676 return;
3677 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003678}
3679
Douglas Gregor20093b42009-12-09 23:02:17 +00003680/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3681/// which enumerates all conversion functions and performs overload resolution
3682/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003683static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003684 const InitializedEntity &Entity,
3685 const InitializationKind &Kind,
3686 Expr *Initializer,
3687 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003688 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003689 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3690 QualType SourceType = Initializer->getType();
3691 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3692 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003693
Douglas Gregor4a520a22009-12-14 17:27:33 +00003694 // Build the candidate set directly in the initialization sequence
3695 // structure, so that it will persist if we fail.
3696 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3697 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698
Douglas Gregor4a520a22009-12-14 17:27:33 +00003699 // Determine whether we are allowed to call explicit constructors or
3700 // explicit conversion operators.
3701 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003702
Douglas Gregor4a520a22009-12-14 17:27:33 +00003703 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3704 // The type we're converting to is a class type. Enumerate its constructors
3705 // to see if there is a suitable conversion.
3706 CXXRecordDecl *DestRecordDecl
3707 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003709 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003710 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003711 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003712 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003713 Con != ConEnd; ++Con) {
3714 NamedDecl *D = *Con;
3715 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003716
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003717 // Find the constructor (which may be a template).
3718 CXXConstructorDecl *Constructor = 0;
3719 FunctionTemplateDecl *ConstructorTmpl
3720 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003721 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003722 Constructor = cast<CXXConstructorDecl>(
3723 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003724 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003725 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003726
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003727 if (!Constructor->isInvalidDecl() &&
3728 Constructor->isConvertingConstructor(AllowExplicit)) {
3729 if (ConstructorTmpl)
3730 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3731 /*ExplicitArgs*/ 0,
3732 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003733 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003734 else
3735 S.AddOverloadCandidate(Constructor, FoundDecl,
3736 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003737 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003739 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003740 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003741 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003742
3743 SourceLocation DeclLoc = Initializer->getLocStart();
3744
Douglas Gregor4a520a22009-12-14 17:27:33 +00003745 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3746 // The type we're converting from is a class type, enumerate its conversion
3747 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003748
Eli Friedman33c2da92009-12-20 22:12:03 +00003749 // We can only enumerate the conversion functions for a complete type; if
3750 // the type isn't complete, simply skip this step.
3751 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3752 CXXRecordDecl *SourceRecordDecl
3753 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003754
John McCalleec51cf2010-01-20 00:46:10 +00003755 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003756 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003757 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003758 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003759 I != E; ++I) {
3760 NamedDecl *D = *I;
3761 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3762 if (isa<UsingShadowDecl>(D))
3763 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003764
Eli Friedman33c2da92009-12-20 22:12:03 +00003765 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3766 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003767 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003768 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003769 else
John McCall32daa422010-03-31 01:36:47 +00003770 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003771
Eli Friedman33c2da92009-12-20 22:12:03 +00003772 if (AllowExplicit || !Conv->isExplicit()) {
3773 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003774 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003775 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003776 CandidateSet);
3777 else
John McCall9aa472c2010-03-19 07:35:19 +00003778 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003779 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003780 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003781 }
3782 }
3783 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003784
3785 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003786 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003787 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003788 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003789 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003791 Result);
3792 return;
3793 }
John McCall1d318332010-01-12 00:44:57 +00003794
Douglas Gregor4a520a22009-12-14 17:27:33 +00003795 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003796 S.MarkDeclarationReferenced(DeclLoc, Function);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003797 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798
Douglas Gregor4a520a22009-12-14 17:27:33 +00003799 if (isa<CXXConstructorDecl>(Function)) {
3800 // Add the user-defined conversion step. Any cv-qualification conversion is
3801 // subsumed by the initialization.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003802 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3803 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003804 return;
3805 }
3806
3807 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003808 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003809 if (ConvType->getAs<RecordType>()) {
3810 // If we're converting to a class type, there may be an copy if
3811 // the resulting temporary object (possible to create an object of
3812 // a base class type). That copy is not a separate conversion, so
3813 // we just make a note of the actual destination type (possibly a
3814 // base class of the type returned by the conversion function) and
3815 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003816 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3817 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003818 return;
3819 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003820
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003821 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3822 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003824 // If the conversion following the call to the conversion function
3825 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003826 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3827 Best->FinalConversion.Third) {
3828 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003829 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003830 ICS.Standard = Best->FinalConversion;
3831 Sequence.AddConversionSequenceStep(ICS, DestType);
3832 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003833}
3834
John McCallf85e1932011-06-15 23:02:42 +00003835/// The non-zero enum values here are indexes into diagnostic alternatives.
3836enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3837
3838/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003839static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3840 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003841 // Skip parens.
3842 e = e->IgnoreParens();
3843
3844 // Skip address-of nodes.
3845 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3846 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003847 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003848
3849 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003850 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3851 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003852 case CK_Dependent:
3853 case CK_BitCast:
3854 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003855 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003856 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003857
3858 case CK_ArrayToPointerDecay:
3859 return IIK_nonscalar;
3860
3861 case CK_NullToPointer:
3862 return IIK_okay;
3863
3864 default:
3865 break;
3866 }
3867
3868 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003869 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3870 if (!isAddressOf) return IIK_nonlocal;
3871
3872 VarDecl *var;
3873 if (isa<DeclRefExpr>(e)) {
3874 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3875 if (!var) return IIK_nonlocal;
3876 } else {
3877 var = cast<BlockDeclRefExpr>(e)->getDecl();
3878 }
3879
3880 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003881
3882 // If we have a conditional operator, check both sides.
3883 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003884 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003885 return iik;
3886
John McCallc03fa492011-06-27 23:59:58 +00003887 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003888
3889 // These are never scalar.
3890 } else if (isa<ArraySubscriptExpr>(e)) {
3891 return IIK_nonscalar;
3892
3893 // Otherwise, it needs to be a null pointer constant.
3894 } else {
3895 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3896 ? IIK_okay : IIK_nonlocal);
3897 }
3898
3899 return IIK_nonlocal;
3900}
3901
3902/// Check whether the given expression is a valid operand for an
3903/// indirect copy/restore.
3904static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3905 assert(src->isRValue());
3906
John McCallc03fa492011-06-27 23:59:58 +00003907 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003908 if (iik == IIK_okay) return;
3909
3910 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3911 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3912 << src->getSourceRange();
3913}
3914
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003915/// \brief Determine whether we have compatible array types for the
3916/// purposes of GNU by-copy array initialization.
3917static bool hasCompatibleArrayTypes(ASTContext &Context,
3918 const ArrayType *Dest,
3919 const ArrayType *Source) {
3920 // If the source and destination array types are equivalent, we're
3921 // done.
3922 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3923 return true;
3924
3925 // Make sure that the element types are the same.
3926 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3927 return false;
3928
3929 // The only mismatch we allow is when the destination is an
3930 // incomplete array type and the source is a constant array type.
3931 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3932}
3933
John McCallf85e1932011-06-15 23:02:42 +00003934static bool tryObjCWritebackConversion(Sema &S,
3935 InitializationSequence &Sequence,
3936 const InitializedEntity &Entity,
3937 Expr *Initializer) {
3938 bool ArrayDecay = false;
3939 QualType ArgType = Initializer->getType();
3940 QualType ArgPointee;
3941 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3942 ArrayDecay = true;
3943 ArgPointee = ArgArrayType->getElementType();
3944 ArgType = S.Context.getPointerType(ArgPointee);
3945 }
3946
3947 // Handle write-back conversion.
3948 QualType ConvertedArgType;
3949 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3950 ConvertedArgType))
3951 return false;
3952
3953 // We should copy unless we're passing to an argument explicitly
3954 // marked 'out'.
3955 bool ShouldCopy = true;
3956 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3957 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3958
3959 // Do we need an lvalue conversion?
3960 if (ArrayDecay || Initializer->isGLValue()) {
3961 ImplicitConversionSequence ICS;
3962 ICS.setStandard();
3963 ICS.Standard.setAsIdentityConversion();
3964
3965 QualType ResultType;
3966 if (ArrayDecay) {
3967 ICS.Standard.First = ICK_Array_To_Pointer;
3968 ResultType = S.Context.getPointerType(ArgPointee);
3969 } else {
3970 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3971 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3972 }
3973
3974 Sequence.AddConversionSequenceStep(ICS, ResultType);
3975 }
3976
3977 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3978 return true;
3979}
3980
Douglas Gregor20093b42009-12-09 23:02:17 +00003981InitializationSequence::InitializationSequence(Sema &S,
3982 const InitializedEntity &Entity,
3983 const InitializationKind &Kind,
3984 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003985 unsigned NumArgs)
3986 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003987 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003988
Douglas Gregor20093b42009-12-09 23:02:17 +00003989 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003990 // The semantics of initializers are as follows. The destination type is
3991 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003992 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003993 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003994 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003995 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003996
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003997 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003998 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3999 SequenceKind = DependentSequence;
4000 return;
4001 }
4002
Sebastian Redl7491c492011-06-05 13:59:11 +00004003 // Almost everything is a normal sequence.
4004 setSequenceKind(NormalSequence);
4005
John McCall241d5582010-12-07 22:54:16 +00004006 for (unsigned I = 0; I != NumArgs; ++I)
John McCall32509f12011-11-15 01:35:18 +00004007 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +00004008 // FIXME: should we be doing this here?
John McCall32509f12011-11-15 01:35:18 +00004009 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4010 if (result.isInvalid()) {
4011 SetFailed(FK_PlaceholderType);
4012 return;
John McCall5acb0c92011-10-17 18:40:02 +00004013 }
John McCall32509f12011-11-15 01:35:18 +00004014 Args[I] = result.take();
John Wiegley429bb272011-04-08 18:41:53 +00004015 }
John McCall241d5582010-12-07 22:54:16 +00004016
John McCall5acb0c92011-10-17 18:40:02 +00004017
Douglas Gregor20093b42009-12-09 23:02:17 +00004018 QualType SourceType;
4019 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004020 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004021 Initializer = Args[0];
4022 if (!isa<InitListExpr>(Initializer))
4023 SourceType = Initializer->getType();
4024 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004025
4026 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00004027 // list-initialized (8.5.4).
4028 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004029 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004030 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00004031 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004032
Douglas Gregor20093b42009-12-09 23:02:17 +00004033 // - If the destination type is a reference type, see 8.5.3.
4034 if (DestType->isReferenceType()) {
4035 // C++0x [dcl.init.ref]p1:
4036 // A variable declared to be a T& or T&&, that is, "reference to type T"
4037 // (8.3.2), shall be initialized by an object, or function, of type T or
4038 // by an object that can be converted into a T.
4039 // (Therefore, multiple arguments are not permitted.)
4040 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004041 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004042 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004043 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004044 return;
4045 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004046
Douglas Gregor20093b42009-12-09 23:02:17 +00004047 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004048 if (Kind.getKind() == InitializationKind::IK_Value ||
4049 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004050 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004051 return;
4052 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004053
Douglas Gregor99a2e602009-12-16 01:38:02 +00004054 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004055 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004056 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004057 return;
4058 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004059
John McCallce6c9b72011-02-21 07:22:22 +00004060 // - If the destination type is an array of characters, an array of
4061 // char16_t, an array of char32_t, or an array of wchar_t, and the
4062 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004064 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004065 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4066 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004067 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004068 return;
4069 }
4070
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004071 // Note: as an GNU C extension, we allow initialization of an
4072 // array from a compound literal that creates an array of the same
4073 // type, so long as the initializer has no side effects.
4074 if (!S.getLangOptions().CPlusPlus && Initializer &&
4075 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4076 Initializer->getType()->isArrayType()) {
4077 const ArrayType *SourceAT
4078 = Context.getAsArrayType(Initializer->getType());
4079 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004080 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004081 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004082 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004083 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004084 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004085 }
4086 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004087 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004088 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004089 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004090
Douglas Gregor20093b42009-12-09 23:02:17 +00004091 return;
4092 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004093
John McCallf85e1932011-06-15 23:02:42 +00004094 // Determine whether we should consider writeback conversions for
4095 // Objective-C ARC.
4096 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4097 Entity.getKind() == InitializedEntity::EK_Parameter;
4098
4099 // We're at the end of the line for C: it's either a write-back conversion
4100 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004101 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004102 // If allowed, check whether this is an Objective-C writeback conversion.
4103 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004104 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004105 return;
4106 }
4107
4108 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004109 AddCAssignmentStep(DestType);
4110 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004111 return;
4112 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004113
John McCallf85e1932011-06-15 23:02:42 +00004114 assert(S.getLangOptions().CPlusPlus);
4115
Douglas Gregor20093b42009-12-09 23:02:17 +00004116 // - If the destination type is a (possibly cv-qualified) class type:
4117 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004118 // - If the initialization is direct-initialization, or if it is
4119 // copy-initialization where the cv-unqualified version of the
4120 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004121 // class of the destination, constructors are considered. [...]
4122 if (Kind.getKind() == InitializationKind::IK_Direct ||
4123 (Kind.getKind() == InitializationKind::IK_Copy &&
4124 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4125 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004126 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004127 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004128 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004129 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004130 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004131 // used) to a derived class thereof are enumerated as described in
4132 // 13.3.1.4, and the best one is chosen through overload resolution
4133 // (13.3).
4134 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004135 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004136 return;
4137 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004138
Douglas Gregor99a2e602009-12-16 01:38:02 +00004139 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004140 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004141 return;
4142 }
4143 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144
4145 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004146 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004147 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004148 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4149 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004150 return;
4151 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152
Douglas Gregor20093b42009-12-09 23:02:17 +00004153 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004154 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004155 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004156 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004157 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004158
4159 ImplicitConversionSequence ICS
4160 = S.TryImplicitConversion(Initializer, Entity.getType(),
4161 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004162 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004163 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004164 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4165 allowObjCWritebackConversion);
4166
4167 if (ICS.isStandard() &&
4168 ICS.Standard.Second == ICK_Writeback_Conversion) {
4169 // Objective-C ARC writeback conversion.
4170
4171 // We should copy unless we're passing to an argument explicitly
4172 // marked 'out'.
4173 bool ShouldCopy = true;
4174 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4175 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4176
4177 // If there was an lvalue adjustment, add it as a separate conversion.
4178 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4179 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4180 ImplicitConversionSequence LvalueICS;
4181 LvalueICS.setStandard();
4182 LvalueICS.Standard.setAsIdentityConversion();
4183 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4184 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004185 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004186 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004187
4188 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004189 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004190 DeclAccessPair dap;
4191 if (Initializer->getType() == Context.OverloadTy &&
4192 !S.ResolveAddressOfOverloadedFunction(Initializer
4193 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004194 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004195 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004196 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004197 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004198 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004199
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004200 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004201 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004202}
4203
4204InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004205 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004206 StepEnd = Steps.end();
4207 Step != StepEnd; ++Step)
4208 Step->Destroy();
4209}
4210
4211//===----------------------------------------------------------------------===//
4212// Perform initialization
4213//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004214static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004215getAssignmentAction(const InitializedEntity &Entity) {
4216 switch(Entity.getKind()) {
4217 case InitializedEntity::EK_Variable:
4218 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004219 case InitializedEntity::EK_Exception:
4220 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004221 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004222 return Sema::AA_Initializing;
4223
4224 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004225 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004226 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4227 return Sema::AA_Sending;
4228
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004229 return Sema::AA_Passing;
4230
4231 case InitializedEntity::EK_Result:
4232 return Sema::AA_Returning;
4233
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004234 case InitializedEntity::EK_Temporary:
4235 // FIXME: Can we tell apart casting vs. converting?
4236 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004237
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004238 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004239 case InitializedEntity::EK_ArrayElement:
4240 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004241 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004242 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004243 return Sema::AA_Initializing;
4244 }
4245
4246 return Sema::AA_Converting;
4247}
4248
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004249/// \brief Whether we should binding a created object as a temporary when
4250/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004251static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004252 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004253 case InitializedEntity::EK_ArrayElement:
4254 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004255 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004256 case InitializedEntity::EK_New:
4257 case InitializedEntity::EK_Variable:
4258 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004259 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004260 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004261 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004262 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004263 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004264 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004266 case InitializedEntity::EK_Parameter:
4267 case InitializedEntity::EK_Temporary:
4268 return true;
4269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004270
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004271 llvm_unreachable("missed an InitializedEntity kind?");
4272}
4273
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004274/// \brief Whether the given entity, when initialized with an object
4275/// created for that initialization, requires destruction.
4276static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4277 switch (Entity.getKind()) {
4278 case InitializedEntity::EK_Member:
4279 case InitializedEntity::EK_Result:
4280 case InitializedEntity::EK_New:
4281 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004282 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004283 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004284 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004285 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004286 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004287
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004288 case InitializedEntity::EK_Variable:
4289 case InitializedEntity::EK_Parameter:
4290 case InitializedEntity::EK_Temporary:
4291 case InitializedEntity::EK_ArrayElement:
4292 case InitializedEntity::EK_Exception:
4293 return true;
4294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004295
4296 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004297}
4298
Richard Smith83da2e72011-10-19 16:55:56 +00004299/// \brief Look for copy and move constructors and constructor templates, for
4300/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4301static void LookupCopyAndMoveConstructors(Sema &S,
4302 OverloadCandidateSet &CandidateSet,
4303 CXXRecordDecl *Class,
4304 Expr *CurInitExpr) {
4305 DeclContext::lookup_iterator Con, ConEnd;
4306 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4307 Con != ConEnd; ++Con) {
4308 CXXConstructorDecl *Constructor = 0;
4309
4310 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4311 // Handle copy/moveconstructors, only.
4312 if (!Constructor || Constructor->isInvalidDecl() ||
4313 !Constructor->isCopyOrMoveConstructor() ||
4314 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4315 continue;
4316
4317 DeclAccessPair FoundDecl
4318 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4319 S.AddOverloadCandidate(Constructor, FoundDecl,
4320 &CurInitExpr, 1, CandidateSet);
4321 continue;
4322 }
4323
4324 // Handle constructor templates.
4325 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4326 if (ConstructorTmpl->isInvalidDecl())
4327 continue;
4328
4329 Constructor = cast<CXXConstructorDecl>(
4330 ConstructorTmpl->getTemplatedDecl());
4331 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4332 continue;
4333
4334 // FIXME: Do we need to limit this to copy-constructor-like
4335 // candidates?
4336 DeclAccessPair FoundDecl
4337 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4338 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4339 &CurInitExpr, 1, CandidateSet, true);
4340 }
4341}
4342
4343/// \brief Get the location at which initialization diagnostics should appear.
4344static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4345 Expr *Initializer) {
4346 switch (Entity.getKind()) {
4347 case InitializedEntity::EK_Result:
4348 return Entity.getReturnLoc();
4349
4350 case InitializedEntity::EK_Exception:
4351 return Entity.getThrowLoc();
4352
4353 case InitializedEntity::EK_Variable:
4354 return Entity.getDecl()->getLocation();
4355
4356 case InitializedEntity::EK_ArrayElement:
4357 case InitializedEntity::EK_Member:
4358 case InitializedEntity::EK_Parameter:
4359 case InitializedEntity::EK_Temporary:
4360 case InitializedEntity::EK_New:
4361 case InitializedEntity::EK_Base:
4362 case InitializedEntity::EK_Delegating:
4363 case InitializedEntity::EK_VectorElement:
4364 case InitializedEntity::EK_ComplexElement:
4365 case InitializedEntity::EK_BlockElement:
4366 return Initializer->getLocStart();
4367 }
4368 llvm_unreachable("missed an InitializedEntity kind?");
4369}
4370
Douglas Gregor523d46a2010-04-18 07:40:54 +00004371/// \brief Make a (potentially elidable) temporary copy of the object
4372/// provided by the given initializer by calling the appropriate copy
4373/// constructor.
4374///
4375/// \param S The Sema object used for type-checking.
4376///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004377/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004378/// the type of the initializer expression or a superclass thereof.
4379///
4380/// \param Enter The entity being initialized.
4381///
4382/// \param CurInit The initializer expression.
4383///
4384/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4385/// is permitted in C++03 (but not C++0x) when binding a reference to
4386/// an rvalue.
4387///
4388/// \returns An expression that copies the initializer expression into
4389/// a temporary object, or an error expression if a copy could not be
4390/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004391static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004392 QualType T,
4393 const InitializedEntity &Entity,
4394 ExprResult CurInit,
4395 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004396 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004397 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004398 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004399 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004400 Class = cast<CXXRecordDecl>(Record->getDecl());
4401 if (!Class)
4402 return move(CurInit);
4403
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004404 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004405 // When certain criteria are met, an implementation is allowed to
4406 // omit the copy/move construction of a class object, even if the
4407 // copy/move constructor and/or destructor for the object have
4408 // side effects. [...]
4409 // - when a temporary class object that has not been bound to a
4410 // reference (12.2) would be copied/moved to a class object
4411 // with the same cv-unqualified type, the copy/move operation
4412 // can be omitted by constructing the temporary object
4413 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004414 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004415 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004416 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004417 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004418 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004419 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004420 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004421
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004422 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004423 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4424 return move(CurInit);
4425
Douglas Gregorcc15f012011-01-21 19:38:21 +00004426 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004427 // Only consider constructors and constructor templates. Per
4428 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4429 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004430 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004431 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004432
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004433 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4434
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004435 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004436 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004437 case OR_Success:
4438 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004440 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004441 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4442 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4443 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004444 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004445 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004446 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004447 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004448 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004449 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004450
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004451 case OR_Ambiguous:
4452 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004453 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004454 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004455 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004456 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004458 case OR_Deleted:
4459 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004460 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004461 << CurInitExpr->getSourceRange();
4462 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004463 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004464 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004465 }
4466
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004467 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004468 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004469 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004470
Anders Carlsson9a68a672010-04-21 18:47:17 +00004471 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004472 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004473
4474 if (IsExtraneousCopy) {
4475 // If this is a totally extraneous copy for C++03 reference
4476 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004477 // expression. We don't generate an (elided) copy operation here
4478 // because doing so would require us to pass down a flag to avoid
4479 // infinite recursion, where each step adds another extraneous,
4480 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004481
Douglas Gregor2559a702010-04-18 07:57:34 +00004482 // Instantiate the default arguments of any extra parameters in
4483 // the selected copy constructor, as if we were going to create a
4484 // proper call to the copy constructor.
4485 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4486 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4487 if (S.RequireCompleteType(Loc, Parm->getType(),
4488 S.PDiag(diag::err_call_incomplete_argument)))
4489 break;
4490
4491 // Build the default argument expression; we don't actually care
4492 // if this succeeds or not, because this routine will complain
4493 // if there was a problem.
4494 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4495 }
4496
Douglas Gregor523d46a2010-04-18 07:40:54 +00004497 return S.Owned(CurInitExpr);
4498 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499
Chandler Carruth25ca4212011-02-25 19:41:05 +00004500 S.MarkDeclarationReferenced(Loc, Constructor);
4501
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004502 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004503 // constructor call (we might have derived-to-base conversions, or
4504 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004505 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004506 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004507 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004508
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004509 // Actually perform the constructor call.
4510 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004511 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004512 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004513 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004514 CXXConstructExpr::CK_Complete,
4515 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004516
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004517 // If we're supposed to bind temporaries, do so.
4518 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4519 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4520 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004521}
Douglas Gregor20093b42009-12-09 23:02:17 +00004522
Richard Smith83da2e72011-10-19 16:55:56 +00004523/// \brief Check whether elidable copy construction for binding a reference to
4524/// a temporary would have succeeded if we were building in C++98 mode, for
4525/// -Wc++98-compat.
4526static void CheckCXX98CompatAccessibleCopy(Sema &S,
4527 const InitializedEntity &Entity,
4528 Expr *CurInitExpr) {
4529 assert(S.getLangOptions().CPlusPlus0x);
4530
4531 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4532 if (!Record)
4533 return;
4534
4535 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4536 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4537 == DiagnosticsEngine::Ignored)
4538 return;
4539
4540 // Find constructors which would have been considered.
4541 OverloadCandidateSet CandidateSet(Loc);
4542 LookupCopyAndMoveConstructors(
4543 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4544
4545 // Perform overload resolution.
4546 OverloadCandidateSet::iterator Best;
4547 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4548
4549 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4550 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4551 << CurInitExpr->getSourceRange();
4552
4553 switch (OR) {
4554 case OR_Success:
4555 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4556 Best->FoundDecl.getAccess(), Diag);
4557 // FIXME: Check default arguments as far as that's possible.
4558 break;
4559
4560 case OR_No_Viable_Function:
4561 S.Diag(Loc, Diag);
4562 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4563 break;
4564
4565 case OR_Ambiguous:
4566 S.Diag(Loc, Diag);
4567 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4568 break;
4569
4570 case OR_Deleted:
4571 S.Diag(Loc, Diag);
4572 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4573 << 1 << Best->Function->isDeleted();
4574 break;
4575 }
4576}
4577
Douglas Gregora41a8c52010-04-22 00:20:18 +00004578void InitializationSequence::PrintInitLocationNote(Sema &S,
4579 const InitializedEntity &Entity) {
4580 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4581 if (Entity.getDecl()->getLocation().isInvalid())
4582 return;
4583
4584 if (Entity.getDecl()->getDeclName())
4585 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4586 << Entity.getDecl()->getDeclName();
4587 else
4588 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4589 }
4590}
4591
Sebastian Redl3b802322011-07-14 19:07:55 +00004592static bool isReferenceBinding(const InitializationSequence::Step &s) {
4593 return s.Kind == InitializationSequence::SK_BindReference ||
4594 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4595}
4596
Sebastian Redl10f04a62011-12-22 14:44:04 +00004597static ExprResult
4598PerformConstructorInitialization(Sema &S,
4599 const InitializedEntity &Entity,
4600 const InitializationKind &Kind,
4601 MultiExprArg Args,
4602 const InitializationSequence::Step& Step,
4603 bool &ConstructorInitRequiresZeroInit) {
4604 unsigned NumArgs = Args.size();
4605 CXXConstructorDecl *Constructor
4606 = cast<CXXConstructorDecl>(Step.Function.Function);
4607 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4608
4609 // Build a call to the selected constructor.
4610 ASTOwningVector<Expr*> ConstructorArgs(S);
4611 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4612 ? Kind.getEqualLoc()
4613 : Kind.getLocation();
4614
4615 if (Kind.getKind() == InitializationKind::IK_Default) {
4616 // Force even a trivial, implicit default constructor to be
4617 // semantically checked. We do this explicitly because we don't build
4618 // the definition for completely trivial constructors.
4619 CXXRecordDecl *ClassDecl = Constructor->getParent();
4620 assert(ClassDecl && "No parent class for constructor.");
4621 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4622 ClassDecl->hasTrivialDefaultConstructor() &&
4623 !Constructor->isUsed(false))
4624 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4625 }
4626
4627 ExprResult CurInit = S.Owned((Expr *)0);
4628
4629 // Determine the arguments required to actually perform the constructor
4630 // call.
4631 if (S.CompleteConstructorCall(Constructor, move(Args),
4632 Loc, ConstructorArgs))
4633 return ExprError();
4634
4635
4636 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4637 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4638 (Kind.getKind() == InitializationKind::IK_Direct ||
4639 Kind.getKind() == InitializationKind::IK_Value)) {
4640 // An explicitly-constructed temporary, e.g., X(1, 2).
4641 unsigned NumExprs = ConstructorArgs.size();
4642 Expr **Exprs = (Expr **)ConstructorArgs.take();
4643 S.MarkDeclarationReferenced(Loc, Constructor);
4644 S.DiagnoseUseOfDecl(Constructor, Loc);
4645
4646 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4647 if (!TSInfo)
4648 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4649
4650 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4651 Constructor,
4652 TSInfo,
4653 Exprs,
4654 NumExprs,
4655 Kind.getParenRange(),
4656 HadMultipleCandidates,
4657 ConstructorInitRequiresZeroInit));
4658 } else {
4659 CXXConstructExpr::ConstructionKind ConstructKind =
4660 CXXConstructExpr::CK_Complete;
4661
4662 if (Entity.getKind() == InitializedEntity::EK_Base) {
4663 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4664 CXXConstructExpr::CK_VirtualBase :
4665 CXXConstructExpr::CK_NonVirtualBase;
4666 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4667 ConstructKind = CXXConstructExpr::CK_Delegating;
4668 }
4669
4670 // Only get the parenthesis range if it is a direct construction.
4671 SourceRange parenRange =
4672 Kind.getKind() == InitializationKind::IK_Direct ?
4673 Kind.getParenRange() : SourceRange();
4674
4675 // If the entity allows NRVO, mark the construction as elidable
4676 // unconditionally.
4677 if (Entity.allowsNRVO())
4678 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4679 Constructor, /*Elidable=*/true,
4680 move_arg(ConstructorArgs),
4681 HadMultipleCandidates,
4682 ConstructorInitRequiresZeroInit,
4683 ConstructKind,
4684 parenRange);
4685 else
4686 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4687 Constructor,
4688 move_arg(ConstructorArgs),
4689 HadMultipleCandidates,
4690 ConstructorInitRequiresZeroInit,
4691 ConstructKind,
4692 parenRange);
4693 }
4694 if (CurInit.isInvalid())
4695 return ExprError();
4696
4697 // Only check access if all of that succeeded.
4698 S.CheckConstructorAccess(Loc, Constructor, Entity,
4699 Step.Function.FoundDecl.getAccess());
4700 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4701
4702 if (shouldBindAsTemporary(Entity))
4703 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4704
4705 return move(CurInit);
4706}
4707
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004708ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004709InitializationSequence::Perform(Sema &S,
4710 const InitializedEntity &Entity,
4711 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004712 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004713 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004714 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004715 unsigned NumArgs = Args.size();
4716 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004717 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004718 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004719
Sebastian Redl7491c492011-06-05 13:59:11 +00004720 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004721 // If the declaration is a non-dependent, incomplete array type
4722 // that has an initializer, then its type will be completed once
4723 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004724 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004725 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004726 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004727 if (const IncompleteArrayType *ArrayT
4728 = S.Context.getAsIncompleteArrayType(DeclType)) {
4729 // FIXME: We don't currently have the ability to accurately
4730 // compute the length of an initializer list without
4731 // performing full type-checking of the initializer list
4732 // (since we have to determine where braces are implicitly
4733 // introduced and such). So, we fall back to making the array
4734 // type a dependently-sized array type with no specified
4735 // bound.
4736 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4737 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004738
Douglas Gregord87b61f2009-12-10 17:56:55 +00004739 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004740 if (DeclaratorDecl *DD = Entity.getDecl()) {
4741 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4742 TypeLoc TL = TInfo->getTypeLoc();
4743 if (IncompleteArrayTypeLoc *ArrayLoc
4744 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4745 Brackets = ArrayLoc->getBracketsRange();
4746 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004747 }
4748
4749 *ResultType
4750 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4751 /*NumElts=*/0,
4752 ArrayT->getSizeModifier(),
4753 ArrayT->getIndexTypeCVRQualifiers(),
4754 Brackets);
4755 }
4756
4757 }
4758 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004759 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4760 Kind.isExplicitCast());
4761 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004762 }
4763
Sebastian Redl7491c492011-06-05 13:59:11 +00004764 // No steps means no initialization.
4765 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004766 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004767
Douglas Gregord6542d82009-12-22 15:35:07 +00004768 QualType DestType = Entity.getType().getNonReferenceType();
4769 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004770 // the same as Entity.getDecl()->getType() in cases involving type merging,
4771 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004772 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004773 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004774 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004775
John McCall60d7b3a2010-08-24 06:29:42 +00004776 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004777
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004778 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004779 // grab the only argument out the Args and place it into the "current"
4780 // initializer.
4781 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004782 case SK_ResolveAddressOfOverloadedFunction:
4783 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004784 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004785 case SK_CastDerivedToBaseLValue:
4786 case SK_BindReference:
4787 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004788 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004789 case SK_UserConversion:
4790 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004791 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004792 case SK_QualificationConversionRValue:
4793 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004794 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004795 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004796 case SK_UnwrapInitList:
4797 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004798 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004799 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004800 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004801 case SK_ArrayInit:
4802 case SK_PassByIndirectCopyRestore:
4803 case SK_PassByIndirectRestore:
4804 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004805 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004806 CurInit = Args.get()[0];
4807 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004808 break;
John McCallf6a16482010-12-04 03:47:34 +00004809 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004810
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004811 case SK_ConstructorInitialization:
4812 case SK_ZeroInitialization:
4813 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004814 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004815
4816 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004817 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004818 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004819 for (step_iterator Step = step_begin(), StepEnd = step_end();
4820 Step != StepEnd; ++Step) {
4821 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004822 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004823
John Wiegley429bb272011-04-08 18:41:53 +00004824 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004825
Douglas Gregor20093b42009-12-09 23:02:17 +00004826 switch (Step->Kind) {
4827 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004828 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004829 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004830 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004831 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004832 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004833 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004834 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004835 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004836
Douglas Gregor20093b42009-12-09 23:02:17 +00004837 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004838 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004839 case SK_CastDerivedToBaseLValue: {
4840 // We have a derived-to-base cast that produces either an rvalue or an
4841 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004842
John McCallf871d0c2010-08-07 06:22:56 +00004843 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004844
Douglas Gregor20093b42009-12-09 23:02:17 +00004845 // Casts to inaccessible base classes are allowed with C-style casts.
4846 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4847 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004848 CurInit.get()->getLocStart(),
4849 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004850 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004851 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004852
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004853 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4854 QualType T = SourceType;
4855 if (const PointerType *Pointer = T->getAs<PointerType>())
4856 T = Pointer->getPointeeType();
4857 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004858 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004859 cast<CXXRecordDecl>(RecordTy->getDecl()));
4860 }
4861
John McCall5baba9d2010-08-25 10:28:54 +00004862 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004863 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004864 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004865 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004866 VK_XValue :
4867 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004868 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4869 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004870 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004871 CurInit.get(),
4872 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004873 break;
4874 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004875
Douglas Gregor20093b42009-12-09 23:02:17 +00004876 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004877 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004878 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4879 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004880 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004881 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004882 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004883 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004884 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004885 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004886
John Wiegley429bb272011-04-08 18:41:53 +00004887 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004888 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004889 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4890 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004891 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004892 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004893 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004894 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004895
Douglas Gregor20093b42009-12-09 23:02:17 +00004896 // Reference binding does not have any corresponding ASTs.
4897
4898 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004899 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004900 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004901
Douglas Gregor20093b42009-12-09 23:02:17 +00004902 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004903
Douglas Gregor20093b42009-12-09 23:02:17 +00004904 case SK_BindReferenceToTemporary:
4905 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004906 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004907 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004908
Douglas Gregor03e80032011-06-21 17:03:29 +00004909 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004910 CurInit = new (S.Context) MaterializeTemporaryExpr(
4911 Entity.getType().getNonReferenceType(),
4912 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004913 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004914
4915 // If we're binding to an Objective-C object that has lifetime, we
4916 // need cleanups.
4917 if (S.getLangOptions().ObjCAutoRefCount &&
4918 CurInit.get()->getType()->isObjCLifetimeType())
4919 S.ExprNeedsCleanups = true;
4920
Douglas Gregor20093b42009-12-09 23:02:17 +00004921 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004922
Douglas Gregor523d46a2010-04-18 07:40:54 +00004923 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004924 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004925 /*IsExtraneousCopy=*/true);
4926 break;
4927
Douglas Gregor20093b42009-12-09 23:02:17 +00004928 case SK_UserConversion: {
4929 // We have a user-defined conversion that invokes either a constructor
4930 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004931 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004932 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004933 FunctionDecl *Fn = Step->Function.Function;
4934 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004935 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004936 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00004937 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004938 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004939 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004940 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004941 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004942
Douglas Gregor20093b42009-12-09 23:02:17 +00004943 // Determine the arguments required to actually perform the constructor
4944 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004945 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004946 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004947 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004948 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004949 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004950
Douglas Gregor20093b42009-12-09 23:02:17 +00004951 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004952 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004953 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004954 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004955 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004956 CXXConstructExpr::CK_Complete,
4957 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004958 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004959 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004960
Anders Carlsson9a68a672010-04-21 18:47:17 +00004961 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004962 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004963 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004964
John McCall2de56d12010-08-25 11:45:40 +00004965 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004966 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4967 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4968 S.IsDerivedFrom(SourceType, Class))
4969 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004970
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004971 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004972 } else {
4973 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004974 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00004975 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004976 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004977 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004978
4979 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004980 // derived-to-base conversion? I believe the answer is "no", because
4981 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004982 ExprResult CurInitExprRes =
4983 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4984 FoundFn, Conversion);
4985 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004986 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004987 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004988
Douglas Gregor20093b42009-12-09 23:02:17 +00004989 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004990 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4991 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00004992 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004993 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004994
John McCall2de56d12010-08-25 11:45:40 +00004995 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004996
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004997 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004999
Sebastian Redl3b802322011-07-14 19:07:55 +00005000 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005001 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5002
5003 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005004 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005005 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005006 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005007 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005008 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005009 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00005010 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
5011 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005012 }
5013 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005014
John McCallf871d0c2010-08-07 06:22:56 +00005015 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005016 CurInit.get()->getType(),
5017 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005018 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005019 if (MaybeBindToTemp)
5020 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005021 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005022 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5023 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005024 break;
5025 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005026
Douglas Gregor20093b42009-12-09 23:02:17 +00005027 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005028 case SK_QualificationConversionXValue:
5029 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005030 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005031 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005032 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005033 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005034 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005035 VK_XValue :
5036 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005037 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005038 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005039 }
5040
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005041 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005042 Sema::CheckedConversionKind CCK
5043 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5044 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005045 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005046 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005047 ExprResult CurInitExprRes =
5048 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005049 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005050 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005051 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005052 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00005053 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005054 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005055
Douglas Gregord87b61f2009-12-10 17:56:55 +00005056 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005057 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005058 // Hack: We must pass *ResultType if available in order to set the type
5059 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5060 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5061 // temporary, not a reference, so we should pass Ty.
5062 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5063 // Since this step is never used for a reference directly, we explicitly
5064 // unwrap references here and rewrap them afterwards.
5065 // We also need to create a InitializeTemporary entity for this.
5066 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5067 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5068 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5069 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5070 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redlc2235182011-10-16 18:19:28 +00005071 Kind.getKind() != InitializationKind::IK_Direct ||
5072 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005073 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005074 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005075
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005076 if (ResultType) {
5077 if ((*ResultType)->isRValueReferenceType())
5078 Ty = S.Context.getRValueReferenceType(Ty);
5079 else if ((*ResultType)->isLValueReferenceType())
5080 Ty = S.Context.getLValueReferenceType(Ty,
5081 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5082 *ResultType = Ty;
5083 }
5084
5085 InitListExpr *StructuredInitList =
5086 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005087 CurInit.release();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005088 CurInit = S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005089 break;
5090 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005091
Sebastian Redl10f04a62011-12-22 14:44:04 +00005092 case SK_ListConstructorCall: {
5093 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5094 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5095 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5096 move(Arg), *Step,
5097 ConstructorInitRequiresZeroInit);
5098 break;
5099 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005100
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005101 case SK_UnwrapInitList:
5102 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5103 break;
5104
5105 case SK_RewrapInitList: {
5106 Expr *E = CurInit.take();
5107 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5108 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5109 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5110 ILE->setSyntacticForm(Syntactic);
5111 ILE->setType(E->getType());
5112 ILE->setValueKind(E->getValueKind());
5113 CurInit = S.Owned(ILE);
5114 break;
5115 }
5116
Sebastian Redl10f04a62011-12-22 14:44:04 +00005117 case SK_ConstructorInitialization:
5118 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5119 *Step,
5120 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005121 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005122
Douglas Gregor71d17402009-12-15 00:01:57 +00005123 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005124 step_iterator NextStep = Step;
5125 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005126 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005127 NextStep->Kind == SK_ConstructorInitialization) {
5128 // The need for zero-initialization is recorded directly into
5129 // the call to the object's constructor within the next step.
5130 ConstructorInitRequiresZeroInit = true;
5131 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5132 S.getLangOptions().CPlusPlus &&
5133 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005134 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5135 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005136 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005137 Kind.getRange().getBegin());
5138
5139 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5140 TSInfo->getType().getNonLValueExprType(S.Context),
5141 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005142 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005143 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005144 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005145 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005146 break;
5147 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005148
5149 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005150 QualType SourceType = CurInit.get()->getType();
5151 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005152 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005153 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5154 if (Result.isInvalid())
5155 return ExprError();
5156 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00005157
5158 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005159 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00005160 if (ConvTy != Sema::Compatible &&
5161 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005162 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005163 == Sema::Compatible)
5164 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005165 if (CurInitExprRes.isInvalid())
5166 return ExprError();
5167 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00005168
Douglas Gregora41a8c52010-04-22 00:20:18 +00005169 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005170 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5171 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005172 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005173 getAssignmentAction(Entity),
5174 &Complained)) {
5175 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005176 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005177 } else if (Complained)
5178 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005179 break;
5180 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005181
5182 case SK_StringInit: {
5183 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005184 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005185 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005186 break;
5187 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005188
5189 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005190 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005191 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005192 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005193 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005194
5195 case SK_ArrayInit:
5196 // Okay: we checked everything before creating this step. Note that
5197 // this is a GNU extension.
5198 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005199 << Step->Type << CurInit.get()->getType()
5200 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005201
5202 // If the destination type is an incomplete array type, update the
5203 // type accordingly.
5204 if (ResultType) {
5205 if (const IncompleteArrayType *IncompleteDest
5206 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5207 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005208 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005209 *ResultType = S.Context.getConstantArrayType(
5210 IncompleteDest->getElementType(),
5211 ConstantSource->getSize(),
5212 ArrayType::Normal, 0);
5213 }
5214 }
5215 }
John McCallf85e1932011-06-15 23:02:42 +00005216 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005217
John McCallf85e1932011-06-15 23:02:42 +00005218 case SK_PassByIndirectCopyRestore:
5219 case SK_PassByIndirectRestore:
5220 checkIndirectCopyRestoreSource(S, CurInit.get());
5221 CurInit = S.Owned(new (S.Context)
5222 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5223 Step->Kind == SK_PassByIndirectCopyRestore));
5224 break;
5225
5226 case SK_ProduceObjCObject:
5227 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005228 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005229 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005230 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005231 }
5232 }
John McCall15d7d122010-11-11 03:21:53 +00005233
5234 // Diagnose non-fatal problems with the completed initialization.
5235 if (Entity.getKind() == InitializedEntity::EK_Member &&
5236 cast<FieldDecl>(Entity.getDecl())->isBitField())
5237 S.CheckBitFieldInitialization(Kind.getLocation(),
5238 cast<FieldDecl>(Entity.getDecl()),
5239 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005240
Douglas Gregor20093b42009-12-09 23:02:17 +00005241 return move(CurInit);
5242}
5243
5244//===----------------------------------------------------------------------===//
5245// Diagnose initialization failures
5246//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005247bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005248 const InitializedEntity &Entity,
5249 const InitializationKind &Kind,
5250 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005251 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005252 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005253
Douglas Gregord6542d82009-12-22 15:35:07 +00005254 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005255 switch (Failure) {
5256 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005257 // FIXME: Customize for the initialized entity?
5258 if (NumArgs == 0)
5259 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5260 << DestType.getNonReferenceType();
5261 else // FIXME: diagnostic below could be better!
5262 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5263 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005264 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005265
Douglas Gregor20093b42009-12-09 23:02:17 +00005266 case FK_ArrayNeedsInitList:
5267 case FK_ArrayNeedsInitListOrStringLiteral:
5268 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5269 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5270 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005271
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005272 case FK_ArrayTypeMismatch:
5273 case FK_NonConstantArrayInit:
5274 S.Diag(Kind.getLocation(),
5275 (Failure == FK_ArrayTypeMismatch
5276 ? diag::err_array_init_different_type
5277 : diag::err_array_init_non_constant_array))
5278 << DestType.getNonReferenceType()
5279 << Args[0]->getType()
5280 << Args[0]->getSourceRange();
5281 break;
5282
John McCall6bb80172010-03-30 21:47:33 +00005283 case FK_AddressOfOverloadFailed: {
5284 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005285 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005286 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005287 true,
5288 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005289 break;
John McCall6bb80172010-03-30 21:47:33 +00005290 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005291
Douglas Gregor20093b42009-12-09 23:02:17 +00005292 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005293 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005294 switch (FailedOverloadResult) {
5295 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005296 if (Failure == FK_UserConversionOverloadFailed)
5297 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5298 << Args[0]->getType() << DestType
5299 << Args[0]->getSourceRange();
5300 else
5301 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5302 << DestType << Args[0]->getType()
5303 << Args[0]->getSourceRange();
5304
John McCall120d63c2010-08-24 20:38:10 +00005305 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005306 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005307
Douglas Gregor20093b42009-12-09 23:02:17 +00005308 case OR_No_Viable_Function:
5309 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5310 << Args[0]->getType() << DestType.getNonReferenceType()
5311 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00005312 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005313 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005314
Douglas Gregor20093b42009-12-09 23:02:17 +00005315 case OR_Deleted: {
5316 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5317 << Args[0]->getType() << DestType.getNonReferenceType()
5318 << Args[0]->getSourceRange();
5319 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005320 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005321 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5322 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005323 if (Ovl == OR_Deleted) {
5324 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005325 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00005326 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005327 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005328 }
5329 break;
5330 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005331
Douglas Gregor20093b42009-12-09 23:02:17 +00005332 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005333 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005334 break;
5335 }
5336 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005337
Douglas Gregor20093b42009-12-09 23:02:17 +00005338 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005339 if (isa<InitListExpr>(Args[0])) {
5340 S.Diag(Kind.getLocation(),
5341 diag::err_lvalue_reference_bind_to_initlist)
5342 << DestType.getNonReferenceType().isVolatileQualified()
5343 << DestType.getNonReferenceType()
5344 << Args[0]->getSourceRange();
5345 break;
5346 }
5347 // Intentional fallthrough
5348
Douglas Gregor20093b42009-12-09 23:02:17 +00005349 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005350 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005351 Failure == FK_NonConstLValueReferenceBindingToTemporary
5352 ? diag::err_lvalue_reference_bind_to_temporary
5353 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005354 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005355 << DestType.getNonReferenceType()
5356 << Args[0]->getType()
5357 << Args[0]->getSourceRange();
5358 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005359
Douglas Gregor20093b42009-12-09 23:02:17 +00005360 case FK_RValueReferenceBindingToLValue:
5361 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005362 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005363 << Args[0]->getSourceRange();
5364 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005365
Douglas Gregor20093b42009-12-09 23:02:17 +00005366 case FK_ReferenceInitDropsQualifiers:
5367 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5368 << DestType.getNonReferenceType()
5369 << Args[0]->getType()
5370 << Args[0]->getSourceRange();
5371 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005372
Douglas Gregor20093b42009-12-09 23:02:17 +00005373 case FK_ReferenceInitFailed:
5374 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5375 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005376 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005377 << Args[0]->getType()
5378 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005379 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5380 Args[0]->getType()->isObjCObjectPointerType())
5381 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005382 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005383
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005384 case FK_ConversionFailed: {
5385 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005386 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005387 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005388 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005389 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005390 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005391 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005392 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5393 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor926df6c2011-06-11 01:09:30 +00005394 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5395 Args[0]->getType()->isObjCObjectPointerType())
5396 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005397 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005398 }
John Wiegley429bb272011-04-08 18:41:53 +00005399
5400 case FK_ConversionFromPropertyFailed:
5401 // No-op. This error has already been reported.
5402 break;
5403
Douglas Gregord87b61f2009-12-10 17:56:55 +00005404 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005405 SourceRange R;
5406
5407 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005408 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005409 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005410 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005411 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005412
Douglas Gregor19311e72010-09-08 21:40:08 +00005413 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5414 if (Kind.isCStyleOrFunctionalCast())
5415 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5416 << R;
5417 else
5418 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5419 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005420 break;
5421 }
5422
5423 case FK_ReferenceBindingToInitList:
5424 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5425 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5426 break;
5427
5428 case FK_InitListBadDestinationType:
5429 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5430 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5431 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005432
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005433 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005434 case FK_ConstructorOverloadFailed: {
5435 SourceRange ArgsRange;
5436 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005437 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005438 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005439
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005440 if (Failure == FK_ListConstructorOverloadFailed) {
5441 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5442 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5443 Args = InitList->getInits();
5444 NumArgs = InitList->getNumInits();
5445 }
5446
Douglas Gregor51c56d62009-12-14 20:49:26 +00005447 // FIXME: Using "DestType" for the entity we're printing is probably
5448 // bad.
5449 switch (FailedOverloadResult) {
5450 case OR_Ambiguous:
5451 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5452 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005453 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5454 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005455 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005456
Douglas Gregor51c56d62009-12-14 20:49:26 +00005457 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005458 if (Kind.getKind() == InitializationKind::IK_Default &&
5459 (Entity.getKind() == InitializedEntity::EK_Base ||
5460 Entity.getKind() == InitializedEntity::EK_Member) &&
5461 isa<CXXConstructorDecl>(S.CurContext)) {
5462 // This is implicit default initialization of a member or
5463 // base within a constructor. If no viable function was
5464 // found, notify the user that she needs to explicitly
5465 // initialize this base/member.
5466 CXXConstructorDecl *Constructor
5467 = cast<CXXConstructorDecl>(S.CurContext);
5468 if (Entity.getKind() == InitializedEntity::EK_Base) {
5469 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5470 << Constructor->isImplicit()
5471 << S.Context.getTypeDeclType(Constructor->getParent())
5472 << /*base=*/0
5473 << Entity.getType();
5474
5475 RecordDecl *BaseDecl
5476 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5477 ->getDecl();
5478 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5479 << S.Context.getTagDeclType(BaseDecl);
5480 } else {
5481 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5482 << Constructor->isImplicit()
5483 << S.Context.getTypeDeclType(Constructor->getParent())
5484 << /*member=*/1
5485 << Entity.getName();
5486 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5487
5488 if (const RecordType *Record
5489 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005490 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005491 diag::note_previous_decl)
5492 << S.Context.getTagDeclType(Record->getDecl());
5493 }
5494 break;
5495 }
5496
Douglas Gregor51c56d62009-12-14 20:49:26 +00005497 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5498 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005499 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005500 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005501
Douglas Gregor51c56d62009-12-14 20:49:26 +00005502 case OR_Deleted: {
5503 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5504 << true << DestType << ArgsRange;
5505 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005506 OverloadingResult Ovl
5507 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005508 if (Ovl == OR_Deleted) {
5509 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005510 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005511 } else {
5512 llvm_unreachable("Inconsistent overload resolution?");
5513 }
5514 break;
5515 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005516
Douglas Gregor51c56d62009-12-14 20:49:26 +00005517 case OR_Success:
5518 llvm_unreachable("Conversion did not fail!");
5519 break;
5520 }
5521 break;
5522 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005523
Douglas Gregor99a2e602009-12-16 01:38:02 +00005524 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005525 if (Entity.getKind() == InitializedEntity::EK_Member &&
5526 isa<CXXConstructorDecl>(S.CurContext)) {
5527 // This is implicit default-initialization of a const member in
5528 // a constructor. Complain that it needs to be explicitly
5529 // initialized.
5530 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5531 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5532 << Constructor->isImplicit()
5533 << S.Context.getTypeDeclType(Constructor->getParent())
5534 << /*const=*/1
5535 << Entity.getName();
5536 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5537 << Entity.getName();
5538 } else {
5539 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5540 << DestType << (bool)DestType->getAs<RecordType>();
5541 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005542 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005543
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005544 case FK_Incomplete:
5545 S.RequireCompleteType(Kind.getLocation(), DestType,
5546 diag::err_init_incomplete_type);
5547 break;
5548
Sebastian Redl14b0c192011-09-24 17:48:00 +00005549 case FK_ListInitializationFailed: {
5550 // Run the init list checker again to emit diagnostics.
5551 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5552 QualType DestType = Entity.getType();
5553 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00005554 DestType, /*VerifyOnly=*/false,
5555 Kind.getKind() != InitializationKind::IK_Direct ||
5556 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005557 assert(DiagnoseInitList.HadError() &&
5558 "Inconsistent init list check result.");
5559 break;
5560 }
John McCall5acb0c92011-10-17 18:40:02 +00005561
5562 case FK_PlaceholderType: {
5563 // FIXME: Already diagnosed!
5564 break;
5565 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005567
Douglas Gregora41a8c52010-04-22 00:20:18 +00005568 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005569 return true;
5570}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005571
Chris Lattner5f9e2722011-07-23 10:55:15 +00005572void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005573 switch (SequenceKind) {
5574 case FailedSequence: {
5575 OS << "Failed sequence: ";
5576 switch (Failure) {
5577 case FK_TooManyInitsForReference:
5578 OS << "too many initializers for reference";
5579 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005580
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005581 case FK_ArrayNeedsInitList:
5582 OS << "array requires initializer list";
5583 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005584
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005585 case FK_ArrayNeedsInitListOrStringLiteral:
5586 OS << "array requires initializer list or string literal";
5587 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005588
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005589 case FK_ArrayTypeMismatch:
5590 OS << "array type mismatch";
5591 break;
5592
5593 case FK_NonConstantArrayInit:
5594 OS << "non-constant array initializer";
5595 break;
5596
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005597 case FK_AddressOfOverloadFailed:
5598 OS << "address of overloaded function failed";
5599 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005600
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005601 case FK_ReferenceInitOverloadFailed:
5602 OS << "overload resolution for reference initialization failed";
5603 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005604
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005605 case FK_NonConstLValueReferenceBindingToTemporary:
5606 OS << "non-const lvalue reference bound to temporary";
5607 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005608
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005609 case FK_NonConstLValueReferenceBindingToUnrelated:
5610 OS << "non-const lvalue reference bound to unrelated type";
5611 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005612
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005613 case FK_RValueReferenceBindingToLValue:
5614 OS << "rvalue reference bound to an lvalue";
5615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005616
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005617 case FK_ReferenceInitDropsQualifiers:
5618 OS << "reference initialization drops qualifiers";
5619 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005620
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005621 case FK_ReferenceInitFailed:
5622 OS << "reference initialization failed";
5623 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005624
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005625 case FK_ConversionFailed:
5626 OS << "conversion failed";
5627 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005628
John Wiegley429bb272011-04-08 18:41:53 +00005629 case FK_ConversionFromPropertyFailed:
5630 OS << "conversion from property failed";
5631 break;
5632
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005633 case FK_TooManyInitsForScalar:
5634 OS << "too many initializers for scalar";
5635 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005636
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005637 case FK_ReferenceBindingToInitList:
5638 OS << "referencing binding to initializer list";
5639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005640
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005641 case FK_InitListBadDestinationType:
5642 OS << "initializer list for non-aggregate, non-scalar type";
5643 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005644
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005645 case FK_UserConversionOverloadFailed:
5646 OS << "overloading failed for user-defined conversion";
5647 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005648
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005649 case FK_ConstructorOverloadFailed:
5650 OS << "constructor overloading failed";
5651 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005652
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005653 case FK_DefaultInitOfConst:
5654 OS << "default initialization of a const variable";
5655 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005656
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005657 case FK_Incomplete:
5658 OS << "initialization of incomplete type";
5659 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005660
5661 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005662 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00005663 break;
5664
5665 case FK_PlaceholderType:
5666 OS << "initializer expression isn't contextually valid";
5667 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00005668
5669 case FK_ListConstructorOverloadFailed:
5670 OS << "list constructor overloading failed";
5671 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005672 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005673 OS << '\n';
5674 return;
5675 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005676
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005677 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005678 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005679 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005680
Sebastian Redl7491c492011-06-05 13:59:11 +00005681 case NormalSequence:
5682 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005683 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005685
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005686 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5687 if (S != step_begin()) {
5688 OS << " -> ";
5689 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005690
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005691 switch (S->Kind) {
5692 case SK_ResolveAddressOfOverloadedFunction:
5693 OS << "resolve address of overloaded function";
5694 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005695
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005696 case SK_CastDerivedToBaseRValue:
5697 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5698 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005699
Sebastian Redl906082e2010-07-20 04:20:21 +00005700 case SK_CastDerivedToBaseXValue:
5701 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5702 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005703
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005704 case SK_CastDerivedToBaseLValue:
5705 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5706 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005707
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005708 case SK_BindReference:
5709 OS << "bind reference to lvalue";
5710 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005711
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005712 case SK_BindReferenceToTemporary:
5713 OS << "bind reference to a temporary";
5714 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005715
Douglas Gregor523d46a2010-04-18 07:40:54 +00005716 case SK_ExtraneousCopyToTemporary:
5717 OS << "extraneous C++03 copy to temporary";
5718 break;
5719
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005720 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005721 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005722 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005723
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005724 case SK_QualificationConversionRValue:
5725 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005726 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005727
Sebastian Redl906082e2010-07-20 04:20:21 +00005728 case SK_QualificationConversionXValue:
5729 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005730 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005731
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005732 case SK_QualificationConversionLValue:
5733 OS << "qualification conversion (lvalue)";
5734 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005735
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005736 case SK_ConversionSequence:
5737 OS << "implicit conversion sequence (";
5738 S->ICS->DebugPrint(); // FIXME: use OS
5739 OS << ")";
5740 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005741
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005742 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005743 OS << "list aggregate initialization";
5744 break;
5745
5746 case SK_ListConstructorCall:
5747 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005748 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005749
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005750 case SK_UnwrapInitList:
5751 OS << "unwrap reference initializer list";
5752 break;
5753
5754 case SK_RewrapInitList:
5755 OS << "rewrap reference initializer list";
5756 break;
5757
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005758 case SK_ConstructorInitialization:
5759 OS << "constructor initialization";
5760 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005761
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005762 case SK_ZeroInitialization:
5763 OS << "zero initialization";
5764 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005765
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005766 case SK_CAssignment:
5767 OS << "C assignment";
5768 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005769
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005770 case SK_StringInit:
5771 OS << "string initialization";
5772 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005773
5774 case SK_ObjCObjectConversion:
5775 OS << "Objective-C object conversion";
5776 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005777
5778 case SK_ArrayInit:
5779 OS << "array initialization";
5780 break;
John McCallf85e1932011-06-15 23:02:42 +00005781
5782 case SK_PassByIndirectCopyRestore:
5783 OS << "pass by indirect copy and restore";
5784 break;
5785
5786 case SK_PassByIndirectRestore:
5787 OS << "pass by indirect restore";
5788 break;
5789
5790 case SK_ProduceObjCObject:
5791 OS << "Objective-C object retension";
5792 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005793 }
5794 }
5795}
5796
5797void InitializationSequence::dump() const {
5798 dump(llvm::errs());
5799}
5800
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005801static void DiagnoseNarrowingInInitList(
5802 Sema& S, QualType EntityType, const Expr *InitE,
5803 bool Constant, const APValue &ConstantValue) {
5804 if (Constant) {
5805 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005806 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005807 ? diag::err_init_list_constant_narrowing
5808 : diag::warn_init_list_constant_narrowing)
5809 << InitE->getSourceRange()
Richard Smith08d6e032011-12-16 19:06:07 +00005810 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005811 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005812 } else
5813 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005814 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005815 ? diag::err_init_list_variable_narrowing
5816 : diag::warn_init_list_variable_narrowing)
5817 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005818 << InitE->getType().getLocalUnqualifiedType()
5819 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005820
5821 llvm::SmallString<128> StaticCast;
5822 llvm::raw_svector_ostream OS(StaticCast);
5823 OS << "static_cast<";
5824 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5825 // It's important to use the typedef's name if there is one so that the
5826 // fixit doesn't break code using types like int64_t.
5827 //
5828 // FIXME: This will break if the typedef requires qualification. But
5829 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005830 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005831 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5832 OS << BT->getName(S.getLangOptions());
5833 else {
5834 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5835 // with a broken cast.
5836 return;
5837 }
5838 OS << ">(";
5839 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5840 << InitE->getSourceRange()
5841 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5842 << FixItHint::CreateInsertion(
5843 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5844}
5845
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005846//===----------------------------------------------------------------------===//
5847// Initialization helper functions
5848//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005849bool
5850Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5851 ExprResult Init) {
5852 if (Init.isInvalid())
5853 return false;
5854
5855 Expr *InitE = Init.get();
5856 assert(InitE && "No initialization expression");
5857
5858 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5859 SourceLocation());
5860 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005861 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005862}
5863
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005864ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005865Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5866 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005867 ExprResult Init,
5868 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005869 if (Init.isInvalid())
5870 return ExprError();
5871
John McCall15d7d122010-11-11 03:21:53 +00005872 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005873 assert(InitE && "No initialization expression?");
5874
5875 if (EqualLoc.isInvalid())
5876 EqualLoc = InitE->getLocStart();
5877
5878 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5879 EqualLoc);
5880 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5881 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005882
5883 bool Constant = false;
5884 APValue Result;
5885 if (TopLevelOfInitList &&
5886 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5887 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5888 Constant, Result);
5889 }
John McCallf312b1e2010-08-26 23:41:50 +00005890 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005891}