blob: 59901cb11b02bedfda92b9a74624e979203bc102 [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)
473 : 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) {
795 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,
801 Result.takeAs<Expr>());
802 }
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);
992 if (isa<InitListExpr>(expr)) {
993 // FIXME: Allowed in C++11.
994 if (!VerifyOnly)
995 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
996 << DeclType << IList->getSourceRange();
997 hadError = true;
998 ++Index;
999 ++StructuredIndex;
1000 return;
1001 }
1002
1003 if (VerifyOnly) {
1004 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1005 hadError = true;
1006 ++Index;
1007 return;
1008 }
1009
1010 ExprResult Result =
1011 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1012 SemaRef.Owned(expr),
1013 /*TopLevelOfInitList=*/true);
1014
1015 if (Result.isInvalid())
1016 hadError = true;
1017
1018 expr = Result.takeAs<Expr>();
1019 IList->setInit(Index, expr);
1020
1021 if (hadError)
1022 ++StructuredIndex;
1023 else
1024 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1025 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001026}
1027
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001028void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001029 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001030 unsigned &Index,
1031 InitListExpr *StructuredList,
1032 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001033 const VectorType *VT = DeclType->getAs<VectorType>();
1034 unsigned maxElements = VT->getNumElements();
1035 unsigned numEltsInit = 0;
1036 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001037
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001038 if (Index >= IList->getNumInits()) {
1039 // Make sure the element type can be value-initialized.
1040 if (VerifyOnly)
1041 CheckValueInitializable(
1042 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1043 return;
1044 }
1045
John McCall20e047a2010-10-30 00:11:39 +00001046 if (!SemaRef.getLangOptions().OpenCL) {
1047 // If the initializing element is a vector, try to copy-initialize
1048 // instead of breaking it apart (which is doomed to failure anyway).
1049 Expr *Init = IList->getInit(Index);
1050 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001051 if (VerifyOnly) {
1052 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1053 hadError = true;
1054 ++Index;
1055 return;
1056 }
1057
John McCall20e047a2010-10-30 00:11:39 +00001058 ExprResult Result =
1059 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001060 SemaRef.Owned(Init),
1061 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001062
1063 Expr *ResultExpr = 0;
1064 if (Result.isInvalid())
1065 hadError = true; // types weren't compatible.
1066 else {
1067 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
John McCall20e047a2010-10-30 00:11:39 +00001069 if (ResultExpr != Init) {
1070 // The type was promoted, update initializer list.
1071 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001072 }
1073 }
John McCall20e047a2010-10-30 00:11:39 +00001074 if (hadError)
1075 ++StructuredIndex;
1076 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001077 UpdateStructuredListElement(StructuredList, StructuredIndex,
1078 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001079 ++Index;
1080 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
John McCall20e047a2010-10-30 00:11:39 +00001083 InitializedEntity ElementEntity =
1084 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
John McCall20e047a2010-10-30 00:11:39 +00001086 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1087 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001088 if (Index >= IList->getNumInits()) {
1089 if (VerifyOnly)
1090 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001091 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001092 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001093
John McCall20e047a2010-10-30 00:11:39 +00001094 ElementEntity.setElementIndex(Index);
1095 CheckSubElementType(ElementEntity, IList, elementType, Index,
1096 StructuredList, StructuredIndex);
1097 }
1098 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001099 }
John McCall20e047a2010-10-30 00:11:39 +00001100
1101 InitializedEntity ElementEntity =
1102 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001103
John McCall20e047a2010-10-30 00:11:39 +00001104 // OpenCL initializers allows vectors to be constructed from vectors.
1105 for (unsigned i = 0; i < maxElements; ++i) {
1106 // Don't attempt to go past the end of the init list
1107 if (Index >= IList->getNumInits())
1108 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001109
John McCall20e047a2010-10-30 00:11:39 +00001110 ElementEntity.setElementIndex(Index);
1111
1112 QualType IType = IList->getInit(Index)->getType();
1113 if (!IType->isVectorType()) {
1114 CheckSubElementType(ElementEntity, IList, elementType, Index,
1115 StructuredList, StructuredIndex);
1116 ++numEltsInit;
1117 } else {
1118 QualType VecType;
1119 const VectorType *IVT = IType->getAs<VectorType>();
1120 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001121
John McCall20e047a2010-10-30 00:11:39 +00001122 if (IType->isExtVectorType())
1123 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1124 else
1125 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001126 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001127 CheckSubElementType(ElementEntity, IList, VecType, Index,
1128 StructuredList, StructuredIndex);
1129 numEltsInit += numIElts;
1130 }
1131 }
1132
1133 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001134 if (numEltsInit != maxElements) {
1135 if (!VerifyOnly)
1136 SemaRef.Diag(IList->getSourceRange().getBegin(),
1137 diag::err_vector_incorrect_num_initializers)
1138 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1139 hadError = true;
1140 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001141}
1142
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001143void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001144 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001145 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001146 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001147 unsigned &Index,
1148 InitListExpr *StructuredList,
1149 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001150 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1151
Steve Naroff0cca7492008-05-01 22:18:59 +00001152 // Check for the special-case of initializing an array with a string.
1153 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001154 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001155 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001156 // We place the string literal directly into the resulting
1157 // initializer list. This is the only place where the structure
1158 // of the structured initializer list doesn't match exactly,
1159 // because doing so would involve allocating one character
1160 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001161 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001162 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001163 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1164 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1165 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001166 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001167 return;
1168 }
1169 }
John McCallce6c9b72011-02-21 07:22:22 +00001170 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001171 // Check for VLAs; in standard C it would be possible to check this
1172 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1173 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001174 if (!VerifyOnly)
1175 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1176 diag::err_variable_object_no_init)
1177 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001178 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001179 ++Index;
1180 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001181 return;
1182 }
1183
Douglas Gregor05c13a32009-01-22 00:58:24 +00001184 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001185 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1186 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001188 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001189 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001190 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001191 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001192 maxElementsKnown = true;
1193 }
1194
John McCallce6c9b72011-02-21 07:22:22 +00001195 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001196 while (Index < IList->getNumInits()) {
1197 Expr *Init = IList->getInit(Index);
1198 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001199 // If we're not the subobject that matches up with the '{' for
1200 // the designator, we shouldn't be handling the
1201 // designator. Return immediately.
1202 if (!SubobjectIsDesignatorContext)
1203 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001204
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001205 // Handle this designated initializer. elementIndex will be
1206 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001207 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001208 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001209 StructuredList, StructuredIndex, true,
1210 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001211 hadError = true;
1212 continue;
1213 }
1214
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001215 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001216 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001217 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001218 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001219 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001220
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001221 // If the array is of incomplete type, keep track of the number of
1222 // elements in the initializer.
1223 if (!maxElementsKnown && elementIndex > maxElements)
1224 maxElements = elementIndex;
1225
Douglas Gregor05c13a32009-01-22 00:58:24 +00001226 continue;
1227 }
1228
1229 // If we know the maximum number of elements, and we've already
1230 // hit it, stop consuming elements in the initializer list.
1231 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001232 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001233
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001234 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001235 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001236 Entity);
1237 // Check this element.
1238 CheckSubElementType(ElementEntity, IList, elementType, Index,
1239 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001240 ++elementIndex;
1241
1242 // If the array is of incomplete type, keep track of the number of
1243 // elements in the initializer.
1244 if (!maxElementsKnown && elementIndex > maxElements)
1245 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001246 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001247 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001248 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001249 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001250 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001251 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001252 // Sizing an array implicitly to zero is not allowed by ISO C,
1253 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001254 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001255 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001256 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001257
Mike Stump1eb44332009-09-09 15:08:12 +00001258 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001259 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001260 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001261 if (!hadError && VerifyOnly) {
1262 // Check if there are any members of the array that get value-initialized.
1263 // If so, check if doing that is possible.
1264 // FIXME: This needs to detect holes left by designated initializers too.
1265 if (maxElementsKnown && elementIndex < maxElements)
1266 CheckValueInitializable(InitializedEntity::InitializeElement(
1267 SemaRef.Context, 0, Entity));
1268 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001269}
1270
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001271bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1272 Expr *InitExpr,
1273 FieldDecl *Field,
1274 bool TopLevelObject) {
1275 // Handle GNU flexible array initializers.
1276 unsigned FlexArrayDiag;
1277 if (isa<InitListExpr>(InitExpr) &&
1278 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1279 // Empty flexible array init always allowed as an extension
1280 FlexArrayDiag = diag::ext_flexible_array_init;
1281 } else if (SemaRef.getLangOptions().CPlusPlus) {
1282 // Disallow flexible array init in C++; it is not required for gcc
1283 // compatibility, and it needs work to IRGen correctly in general.
1284 FlexArrayDiag = diag::err_flexible_array_init;
1285 } else if (!TopLevelObject) {
1286 // Disallow flexible array init on non-top-level object
1287 FlexArrayDiag = diag::err_flexible_array_init;
1288 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1289 // Disallow flexible array init on anything which is not a variable.
1290 FlexArrayDiag = diag::err_flexible_array_init;
1291 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1292 // Disallow flexible array init on local variables.
1293 FlexArrayDiag = diag::err_flexible_array_init;
1294 } else {
1295 // Allow other cases.
1296 FlexArrayDiag = diag::ext_flexible_array_init;
1297 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001298
1299 if (!VerifyOnly) {
1300 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1301 FlexArrayDiag)
1302 << InitExpr->getSourceRange().getBegin();
1303 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1304 << Field;
1305 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001306
1307 return FlexArrayDiag != diag::ext_flexible_array_init;
1308}
1309
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001310void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001311 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001312 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001313 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001314 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001315 unsigned &Index,
1316 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001317 unsigned &StructuredIndex,
1318 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001319 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Eli Friedmanb85f7072008-05-19 19:16:24 +00001321 // If the record is invalid, some of it's members are invalid. To avoid
1322 // confusion, we forgo checking the intializer for the entire record.
1323 if (structDecl->isInvalidDecl()) {
1324 hadError = true;
1325 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001326 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001327
1328 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001329 // Value-initialize the first named member of the union.
1330 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1331 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1332 Field != FieldEnd; ++Field) {
1333 if (Field->getDeclName()) {
1334 if (VerifyOnly)
1335 CheckValueInitializable(
1336 InitializedEntity::InitializeMember(*Field, &Entity));
1337 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001338 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001339 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001340 }
1341 }
1342 return;
1343 }
1344
Douglas Gregor05c13a32009-01-22 00:58:24 +00001345 // If structDecl is a forward declaration, this loop won't do
1346 // anything except look at designated initializers; That's okay,
1347 // because an error should get printed out elsewhere. It might be
1348 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001349 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001350 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001351 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001352 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001353 while (Index < IList->getNumInits()) {
1354 Expr *Init = IList->getInit(Index);
1355
1356 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001357 // If we're not the subobject that matches up with the '{' for
1358 // the designator, we shouldn't be handling the
1359 // designator. Return immediately.
1360 if (!SubobjectIsDesignatorContext)
1361 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001362
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001363 // Handle this designated initializer. Field will be updated to
1364 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001365 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001366 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001367 StructuredList, StructuredIndex,
1368 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001369 hadError = true;
1370
Douglas Gregordfb5e592009-02-12 19:00:39 +00001371 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001372
1373 // Disable check for missing fields when designators are used.
1374 // This matches gcc behaviour.
1375 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001376 continue;
1377 }
1378
1379 if (Field == FieldEnd) {
1380 // We've run out of fields. We're done.
1381 break;
1382 }
1383
Douglas Gregordfb5e592009-02-12 19:00:39 +00001384 // We've already initialized a member of a union. We're done.
1385 if (InitializedSomething && DeclType->isUnionType())
1386 break;
1387
Douglas Gregor44b43212008-12-11 16:49:14 +00001388 // If we've hit the flexible array member at the end, we're done.
1389 if (Field->getType()->isIncompleteArrayType())
1390 break;
1391
Douglas Gregor0bb76892009-01-29 16:53:55 +00001392 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001394 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001395 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001396 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001397
Douglas Gregor54001c12011-06-29 21:51:31 +00001398 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001399 bool InvalidUse;
1400 if (VerifyOnly)
1401 InvalidUse = !SemaRef.CanUseDecl(*Field);
1402 else
1403 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1404 IList->getInit(Index)->getLocStart());
1405 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001406 ++Index;
1407 ++Field;
1408 hadError = true;
1409 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001410 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001411
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001412 InitializedEntity MemberEntity =
1413 InitializedEntity::InitializeMember(*Field, &Entity);
1414 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1415 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001416 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001417
Sebastian Redl14b0c192011-09-24 17:48:00 +00001418 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001419 // Initialize the first field within the union.
1420 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001421 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001422
1423 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001424 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001425
John McCall80639de2010-03-11 19:32:38 +00001426 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001427 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1428 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1429 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001430 // It is possible we have one or more unnamed bitfields remaining.
1431 // Find first (if any) named field and emit warning.
1432 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1433 it != end; ++it) {
1434 if (!it->isUnnamedBitfield()) {
1435 SemaRef.Diag(IList->getSourceRange().getEnd(),
1436 diag::warn_missing_field_initializers) << it->getName();
1437 break;
1438 }
1439 }
1440 }
1441
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001442 // Check that any remaining fields can be value-initialized.
1443 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1444 !Field->getType()->isIncompleteArrayType()) {
1445 // FIXME: Should check for holes left by designated initializers too.
1446 for (; Field != FieldEnd && !hadError; ++Field) {
1447 if (!Field->isUnnamedBitfield())
1448 CheckValueInitializable(
1449 InitializedEntity::InitializeMember(*Field, &Entity));
1450 }
1451 }
1452
Mike Stump1eb44332009-09-09 15:08:12 +00001453 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001454 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001455 return;
1456
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001457 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1458 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001459 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001460 ++Index;
1461 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001462 }
1463
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001464 InitializedEntity MemberEntity =
1465 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001467 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001469 StructuredList, StructuredIndex);
1470 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001471 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001472 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001473}
Steve Naroff0cca7492008-05-01 22:18:59 +00001474
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001475/// \brief Expand a field designator that refers to a member of an
1476/// anonymous struct or union into a series of field designators that
1477/// refers to the field within the appropriate subobject.
1478///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001479static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001480 DesignatedInitExpr *DIE,
1481 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001482 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001483 typedef DesignatedInitExpr::Designator Designator;
1484
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001485 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001486 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001487 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1488 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1489 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001490 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001491 DIE->getDesignator(DesigIdx)->getDotLoc(),
1492 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1493 else
1494 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1495 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001496 assert(isa<FieldDecl>(*PI));
1497 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001498 }
1499
1500 // Expand the current designator into the set of replacement
1501 // designators, so we have a full subobject path down to where the
1502 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001503 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001504 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001505}
Mike Stump1eb44332009-09-09 15:08:12 +00001506
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001507/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001508/// corresponds to FieldName.
1509static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1510 IdentifierInfo *FieldName) {
1511 assert(AnonField->isAnonymousStructOrUnion());
1512 Decl *NextDecl = AnonField->getNextDeclInContext();
1513 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1514 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1515 return IF;
1516 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001517 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001518 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001519}
1520
Sebastian Redl14b0c192011-09-24 17:48:00 +00001521static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1522 DesignatedInitExpr *DIE) {
1523 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1524 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1525 for (unsigned I = 0; I < NumIndexExprs; ++I)
1526 IndexExprs[I] = DIE->getSubExpr(I + 1);
1527 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1528 DIE->size(), IndexExprs.data(),
1529 NumIndexExprs, DIE->getEqualOrColonLoc(),
1530 DIE->usesGNUSyntax(), DIE->getInit());
1531}
1532
Douglas Gregor05c13a32009-01-22 00:58:24 +00001533/// @brief Check the well-formedness of a C99 designated initializer.
1534///
1535/// Determines whether the designated initializer @p DIE, which
1536/// resides at the given @p Index within the initializer list @p
1537/// IList, is well-formed for a current object of type @p DeclType
1538/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001539/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001540/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001541///
1542/// @param IList The initializer list in which this designated
1543/// initializer occurs.
1544///
Douglas Gregor71199712009-04-15 04:56:10 +00001545/// @param DIE The designated initializer expression.
1546///
1547/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001548///
1549/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1550/// into which the designation in @p DIE should refer.
1551///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001552/// @param NextField If non-NULL and the first designator in @p DIE is
1553/// a field, this will be set to the field declaration corresponding
1554/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001555///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001556/// @param NextElementIndex If non-NULL and the first designator in @p
1557/// DIE is an array designator or GNU array-range designator, this
1558/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001559///
1560/// @param Index Index into @p IList where the designated initializer
1561/// @p DIE occurs.
1562///
Douglas Gregor4c678342009-01-28 21:54:33 +00001563/// @param StructuredList The initializer list expression that
1564/// describes all of the subobject initializers in the order they'll
1565/// actually be initialized.
1566///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001567/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001568bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001569InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001570 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001571 DesignatedInitExpr *DIE,
1572 unsigned DesigIdx,
1573 QualType &CurrentObjectType,
1574 RecordDecl::field_iterator *NextField,
1575 llvm::APSInt *NextElementIndex,
1576 unsigned &Index,
1577 InitListExpr *StructuredList,
1578 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001579 bool FinishSubobjectInit,
1580 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001581 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001582 // Check the actual initialization for the designated object type.
1583 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001584
1585 // Temporarily remove the designator expression from the
1586 // initializer list that the child calls see, so that we don't try
1587 // to re-process the designator.
1588 unsigned OldIndex = Index;
1589 IList->setInit(OldIndex, DIE->getInit());
1590
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001591 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001592 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001593
1594 // Restore the designated initializer expression in the syntactic
1595 // form of the initializer list.
1596 if (IList->getInit(OldIndex) != DIE->getInit())
1597 DIE->setInit(IList->getInit(OldIndex));
1598 IList->setInit(OldIndex, DIE);
1599
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001600 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001601 }
1602
Douglas Gregor71199712009-04-15 04:56:10 +00001603 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001604 bool IsFirstDesignator = (DesigIdx == 0);
1605 if (!VerifyOnly) {
1606 assert((IsFirstDesignator || StructuredList) &&
1607 "Need a non-designated initializer list to start from");
1608
1609 // Determine the structural initializer list that corresponds to the
1610 // current subobject.
1611 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1612 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1613 StructuredList, StructuredIndex,
1614 SourceRange(D->getStartLocation(),
1615 DIE->getSourceRange().getEnd()));
1616 assert(StructuredList && "Expected a structured initializer list");
1617 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001618
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001619 if (D->isFieldDesignator()) {
1620 // C99 6.7.8p7:
1621 //
1622 // If a designator has the form
1623 //
1624 // . identifier
1625 //
1626 // then the current object (defined below) shall have
1627 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001628 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001629 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001630 if (!RT) {
1631 SourceLocation Loc = D->getDotLoc();
1632 if (Loc.isInvalid())
1633 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001634 if (!VerifyOnly)
1635 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1636 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001637 ++Index;
1638 return true;
1639 }
1640
Douglas Gregor4c678342009-01-28 21:54:33 +00001641 // Note: we perform a linear search of the fields here, despite
1642 // the fact that we have a faster lookup method, because we always
1643 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001644 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001645 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001646 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001647 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001648 Field = RT->getDecl()->field_begin(),
1649 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001650 for (; Field != FieldEnd; ++Field) {
1651 if (Field->isUnnamedBitfield())
1652 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001653
Francois Picheta0e27f02010-12-22 03:46:10 +00001654 // If we find a field representing an anonymous field, look in the
1655 // IndirectFieldDecl that follow for the designated initializer.
1656 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1657 if (IndirectFieldDecl *IF =
1658 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001659 // In verify mode, don't modify the original.
1660 if (VerifyOnly)
1661 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001662 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1663 D = DIE->getDesignator(DesigIdx);
1664 break;
1665 }
1666 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001667 if (KnownField && KnownField == *Field)
1668 break;
1669 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001670 break;
1671
1672 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001673 }
1674
Douglas Gregor4c678342009-01-28 21:54:33 +00001675 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001676 if (VerifyOnly) {
1677 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001678 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001679 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001680
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001681 // There was no normal field in the struct with the designated
1682 // name. Perform another lookup for this name, which may find
1683 // something that we can't designate (e.g., a member function),
1684 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001685 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001686 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001687 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001688 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001689 // Name lookup didn't find anything. Determine whether this
1690 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001691 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001692 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001693 TypoCorrection Corrected = SemaRef.CorrectTypo(
1694 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1695 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1696 RT->getDecl(), false, Sema::CTC_NoKeywords);
1697 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001698 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001699 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001700 std::string CorrectedStr(
1701 Corrected.getAsString(SemaRef.getLangOptions()));
1702 std::string CorrectedQuotedStr(
1703 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001705 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001706 << FieldName << CurrentObjectType << CorrectedQuotedStr
1707 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001708 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001709 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001710 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001711 } else {
1712 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1713 << FieldName << CurrentObjectType;
1714 ++Index;
1715 return true;
1716 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001717 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001718
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001719 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001720 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001721 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001722 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001723 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001724 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001725 ++Index;
1726 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001727 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001728
Francois Picheta0e27f02010-12-22 03:46:10 +00001729 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001730 // The replacement field comes from typo correction; find it
1731 // in the list of fields.
1732 FieldIndex = 0;
1733 Field = RT->getDecl()->field_begin();
1734 for (; Field != FieldEnd; ++Field) {
1735 if (Field->isUnnamedBitfield())
1736 continue;
1737
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001738 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001739 Field->getIdentifier() == ReplacementField->getIdentifier())
1740 break;
1741
1742 ++FieldIndex;
1743 }
1744 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001745 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001746
1747 // All of the fields of a union are located at the same place in
1748 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001749 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001750 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001751 if (!VerifyOnly)
1752 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001753 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001754
Douglas Gregor54001c12011-06-29 21:51:31 +00001755 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001756 bool InvalidUse;
1757 if (VerifyOnly)
1758 InvalidUse = !SemaRef.CanUseDecl(*Field);
1759 else
1760 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1761 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001762 ++Index;
1763 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001764 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001765
Sebastian Redl14b0c192011-09-24 17:48:00 +00001766 if (!VerifyOnly) {
1767 // Update the designator with the field declaration.
1768 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Sebastian Redl14b0c192011-09-24 17:48:00 +00001770 // Make sure that our non-designated initializer list has space
1771 // for a subobject corresponding to this field.
1772 if (FieldIndex >= StructuredList->getNumInits())
1773 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1774 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001775
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001776 // This designator names a flexible array member.
1777 if (Field->getType()->isIncompleteArrayType()) {
1778 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001779 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001780 // We can't designate an object within the flexible array
1781 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001782 if (!VerifyOnly) {
1783 DesignatedInitExpr::Designator *NextD
1784 = DIE->getDesignator(DesigIdx + 1);
1785 SemaRef.Diag(NextD->getStartLocation(),
1786 diag::err_designator_into_flexible_array_member)
1787 << SourceRange(NextD->getStartLocation(),
1788 DIE->getSourceRange().getEnd());
1789 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1790 << *Field;
1791 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001792 Invalid = true;
1793 }
1794
Chris Lattner9046c222010-10-10 17:49:49 +00001795 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1796 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001797 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001798 if (!VerifyOnly) {
1799 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1800 diag::err_flexible_array_init_needs_braces)
1801 << DIE->getInit()->getSourceRange();
1802 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1803 << *Field;
1804 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001805 Invalid = true;
1806 }
1807
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001808 // Check GNU flexible array initializer.
1809 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1810 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001811 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001812
1813 if (Invalid) {
1814 ++Index;
1815 return true;
1816 }
1817
1818 // Initialize the array.
1819 bool prevHadError = hadError;
1820 unsigned newStructuredIndex = FieldIndex;
1821 unsigned OldIndex = Index;
1822 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001823
1824 InitializedEntity MemberEntity =
1825 InitializedEntity::InitializeMember(*Field, &Entity);
1826 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001827 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001828
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001829 IList->setInit(OldIndex, DIE);
1830 if (hadError && !prevHadError) {
1831 ++Field;
1832 ++FieldIndex;
1833 if (NextField)
1834 *NextField = Field;
1835 StructuredIndex = FieldIndex;
1836 return true;
1837 }
1838 } else {
1839 // Recurse to check later designated subobjects.
1840 QualType FieldType = (*Field)->getType();
1841 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001842
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001843 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001844 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001845 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1846 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001847 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001848 true, false))
1849 return true;
1850 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001851
1852 // Find the position of the next field to be initialized in this
1853 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001854 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001855 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001856
1857 // If this the first designator, our caller will continue checking
1858 // the rest of this struct/class/union subobject.
1859 if (IsFirstDesignator) {
1860 if (NextField)
1861 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001862 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001863 return false;
1864 }
1865
Douglas Gregor34e79462009-01-28 23:36:17 +00001866 if (!FinishSubobjectInit)
1867 return false;
1868
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001869 // We've already initialized something in the union; we're done.
1870 if (RT->getDecl()->isUnion())
1871 return hadError;
1872
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001873 // Check the remaining fields within this class/struct/union subobject.
1874 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001875
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001876 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001877 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001878 return hadError && !prevHadError;
1879 }
1880
1881 // C99 6.7.8p6:
1882 //
1883 // If a designator has the form
1884 //
1885 // [ constant-expression ]
1886 //
1887 // then the current object (defined below) shall have array
1888 // type and the expression shall be an integer constant
1889 // expression. If the array is of unknown size, any
1890 // nonnegative value is valid.
1891 //
1892 // Additionally, cope with the GNU extension that permits
1893 // designators of the form
1894 //
1895 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001896 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001897 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001898 if (!VerifyOnly)
1899 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1900 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001901 ++Index;
1902 return true;
1903 }
1904
1905 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001906 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1907 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001908 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001909 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001910 DesignatedEndIndex = DesignatedStartIndex;
1911 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001912 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001913
Mike Stump1eb44332009-09-09 15:08:12 +00001914 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001915 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001916 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001917 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001918 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001919
Chris Lattnere0fd8322011-02-19 22:28:58 +00001920 // Codegen can't handle evaluating array range designators that have side
1921 // effects, because we replicate the AST value for each initialized element.
1922 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1923 // elements with something that has a side effect, so codegen can emit an
1924 // "error unsupported" error instead of miscompiling the app.
1925 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001926 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001927 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001928 }
1929
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001930 if (isa<ConstantArrayType>(AT)) {
1931 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001932 DesignatedStartIndex
1933 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001934 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001935 DesignatedEndIndex
1936 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001937 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1938 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001939 if (!VerifyOnly)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001940 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1941 diag::err_array_designator_too_large)
1942 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1943 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001944 ++Index;
1945 return true;
1946 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001947 } else {
1948 // Make sure the bit-widths and signedness match.
1949 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001950 DesignatedEndIndex
1951 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001952 else if (DesignatedStartIndex.getBitWidth() <
1953 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001954 DesignatedStartIndex
1955 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001956 DesignatedStartIndex.setIsUnsigned(true);
1957 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Douglas Gregor4c678342009-01-28 21:54:33 +00001960 // Make sure that our non-designated initializer list has space
1961 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001962 if (!VerifyOnly &&
1963 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001964 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001965 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001966
Douglas Gregor34e79462009-01-28 23:36:17 +00001967 // Repeatedly perform subobject initializations in the range
1968 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001969
Douglas Gregor34e79462009-01-28 23:36:17 +00001970 // Move to the next designator
1971 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1972 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001973
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001974 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001975 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001976
Douglas Gregor34e79462009-01-28 23:36:17 +00001977 while (DesignatedStartIndex <= DesignatedEndIndex) {
1978 // Recurse to check later designated subobjects.
1979 QualType ElementType = AT->getElementType();
1980 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001981
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001982 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001983 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1984 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001985 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001986 (DesignatedStartIndex == DesignatedEndIndex),
1987 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001988 return true;
1989
1990 // Move to the next index in the array that we'll be initializing.
1991 ++DesignatedStartIndex;
1992 ElementIndex = DesignatedStartIndex.getZExtValue();
1993 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001994
1995 // If this the first designator, our caller will continue checking
1996 // the rest of this array subobject.
1997 if (IsFirstDesignator) {
1998 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001999 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002000 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002001 return false;
2002 }
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Douglas Gregor34e79462009-01-28 23:36:17 +00002004 if (!FinishSubobjectInit)
2005 return false;
2006
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002007 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002008 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002009 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002010 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002011 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002012 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002013}
2014
Douglas Gregor4c678342009-01-28 21:54:33 +00002015// Get the structured initializer list for a subobject of type
2016// @p CurrentObjectType.
2017InitListExpr *
2018InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2019 QualType CurrentObjectType,
2020 InitListExpr *StructuredList,
2021 unsigned StructuredIndex,
2022 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002023 if (VerifyOnly)
2024 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002025 Expr *ExistingInit = 0;
2026 if (!StructuredList)
2027 ExistingInit = SyntacticToSemantic[IList];
2028 else if (StructuredIndex < StructuredList->getNumInits())
2029 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Douglas Gregor4c678342009-01-28 21:54:33 +00002031 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2032 return Result;
2033
2034 if (ExistingInit) {
2035 // We are creating an initializer list that initializes the
2036 // subobjects of the current object, but there was already an
2037 // initialization that completely initialized the current
2038 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002039 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002040 // struct X { int a, b; };
2041 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002042 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002043 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2044 // designated initializer re-initializes the whole
2045 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002046 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002047 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002048 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00002049 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002050 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002051 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002052 << ExistingInit->getSourceRange();
2053 }
2054
Mike Stump1eb44332009-09-09 15:08:12 +00002055 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002056 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2057 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002058 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002059
Douglas Gregor63982352010-07-13 18:40:04 +00002060 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00002061
Douglas Gregorfa219202009-03-20 23:58:33 +00002062 // Pre-allocate storage for the structured initializer list.
2063 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002064 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002065 bool GotNumInits = false;
2066 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002067 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002068 GotNumInits = true;
2069 } else if (Index < IList->getNumInits()) {
2070 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002071 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002072 GotNumInits = true;
2073 }
Douglas Gregor08457732009-03-21 18:13:52 +00002074 }
2075
Mike Stump1eb44332009-09-09 15:08:12 +00002076 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002077 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2078 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2079 NumElements = CAType->getSize().getZExtValue();
2080 // Simple heuristic so that we don't allocate a very large
2081 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002082 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002083 NumElements = 0;
2084 }
John McCall183700f2009-09-21 23:43:11 +00002085 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002086 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002087 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002088 RecordDecl *RDecl = RType->getDecl();
2089 if (RDecl->isUnion())
2090 NumElements = 1;
2091 else
Mike Stump1eb44332009-09-09 15:08:12 +00002092 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002093 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002094 }
2095
Ted Kremenek709210f2010-04-13 23:39:13 +00002096 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002097
Douglas Gregor4c678342009-01-28 21:54:33 +00002098 // Link this new initializer list into the structured initializer
2099 // lists.
2100 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002101 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002102 else {
2103 Result->setSyntacticForm(IList);
2104 SyntacticToSemantic[IList] = Result;
2105 }
2106
2107 return Result;
2108}
2109
2110/// Update the initializer at index @p StructuredIndex within the
2111/// structured initializer list to the value @p expr.
2112void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2113 unsigned &StructuredIndex,
2114 Expr *expr) {
2115 // No structured initializer list to update
2116 if (!StructuredList)
2117 return;
2118
Ted Kremenek709210f2010-04-13 23:39:13 +00002119 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2120 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002121 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00002122 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002123 diag::warn_initializer_overrides)
2124 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002125 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002126 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002127 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002128 << PrevInit->getSourceRange();
2129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Douglas Gregor4c678342009-01-28 21:54:33 +00002131 ++StructuredIndex;
2132}
2133
Douglas Gregor05c13a32009-01-22 00:58:24 +00002134/// Check that the given Index expression is a valid array designator
2135/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002136/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002137/// and produces a reasonable diagnostic if there is a
2138/// failure. Returns true if there was an error, false otherwise. If
2139/// everything went okay, Value will receive the value of the constant
2140/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002141static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00002142CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002143 SourceLocation Loc = Index->getSourceRange().getBegin();
2144
2145 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00002146 if (S.VerifyIntegerConstantExpression(Index, &Value))
2147 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002148
Chris Lattner3bf68932009-04-25 21:59:05 +00002149 if (Value.isSigned() && Value.isNegative())
2150 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002151 << Value.toString(10) << Index->getSourceRange();
2152
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002153 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002154 return false;
2155}
2156
John McCall60d7b3a2010-08-24 06:29:42 +00002157ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002158 SourceLocation Loc,
2159 bool GNUSyntax,
2160 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002161 typedef DesignatedInitExpr::Designator ASTDesignator;
2162
2163 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002164 SmallVector<ASTDesignator, 32> Designators;
2165 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002166
2167 // Build designators and check array designator expressions.
2168 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2169 const Designator &D = Desig.getDesignator(Idx);
2170 switch (D.getKind()) {
2171 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002172 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002173 D.getFieldLoc()));
2174 break;
2175
2176 case Designator::ArrayDesignator: {
2177 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2178 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002179 if (!Index->isTypeDependent() &&
2180 !Index->isValueDependent() &&
2181 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002182 Invalid = true;
2183 else {
2184 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002185 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002186 D.getRBracketLoc()));
2187 InitExpressions.push_back(Index);
2188 }
2189 break;
2190 }
2191
2192 case Designator::ArrayRangeDesignator: {
2193 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2194 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2195 llvm::APSInt StartValue;
2196 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002197 bool StartDependent = StartIndex->isTypeDependent() ||
2198 StartIndex->isValueDependent();
2199 bool EndDependent = EndIndex->isTypeDependent() ||
2200 EndIndex->isValueDependent();
2201 if ((!StartDependent &&
2202 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2203 (!EndDependent &&
2204 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002205 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002206 else {
2207 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002208 if (StartDependent || EndDependent) {
2209 // Nothing to compute.
2210 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002211 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002212 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002213 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002214
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002215 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002216 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002217 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002218 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2219 Invalid = true;
2220 } else {
2221 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002222 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002223 D.getEllipsisLoc(),
2224 D.getRBracketLoc()));
2225 InitExpressions.push_back(StartIndex);
2226 InitExpressions.push_back(EndIndex);
2227 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002228 }
2229 break;
2230 }
2231 }
2232 }
2233
2234 if (Invalid || Init.isInvalid())
2235 return ExprError();
2236
2237 // Clear out the expressions within the designation.
2238 Desig.ClearExprs(*this);
2239
2240 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002241 = DesignatedInitExpr::Create(Context,
2242 Designators.data(), Designators.size(),
2243 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002244 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002245
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002246 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002247 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2248 << DIE->getSourceRange();
2249 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002250 Diag(DIE->getLocStart(), diag::ext_designated_init)
2251 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002252
Douglas Gregor05c13a32009-01-22 00:58:24 +00002253 return Owned(DIE);
2254}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002255
Douglas Gregor20093b42009-12-09 23:02:17 +00002256//===----------------------------------------------------------------------===//
2257// Initialization entity
2258//===----------------------------------------------------------------------===//
2259
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002260InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002261 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002262 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002263{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002264 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2265 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002266 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002267 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002268 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002269 Type = VT->getElementType();
2270 } else {
2271 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2272 assert(CT && "Unexpected type");
2273 Kind = EK_ComplexElement;
2274 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002275 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002276}
2277
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002278InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002279 CXXBaseSpecifier *Base,
2280 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002281{
2282 InitializedEntity Result;
2283 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002284 Result.Base = reinterpret_cast<uintptr_t>(Base);
2285 if (IsInheritedVirtualBase)
2286 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002287
Douglas Gregord6542d82009-12-22 15:35:07 +00002288 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002289 return Result;
2290}
2291
Douglas Gregor99a2e602009-12-16 01:38:02 +00002292DeclarationName InitializedEntity::getName() const {
2293 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002294 case EK_Parameter: {
2295 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2296 return (D ? D->getDeclName() : DeclarationName());
2297 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002298
2299 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002300 case EK_Member:
2301 return VariableOrMember->getDeclName();
2302
2303 case EK_Result:
2304 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002305 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002306 case EK_Temporary:
2307 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002308 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002309 case EK_ArrayElement:
2310 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002311 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002312 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002313 return DeclarationName();
2314 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002315
Douglas Gregor99a2e602009-12-16 01:38:02 +00002316 // Silence GCC warning
2317 return DeclarationName();
2318}
2319
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002320DeclaratorDecl *InitializedEntity::getDecl() const {
2321 switch (getKind()) {
2322 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002323 case EK_Member:
2324 return VariableOrMember;
2325
John McCallf85e1932011-06-15 23:02:42 +00002326 case EK_Parameter:
2327 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2328
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002329 case EK_Result:
2330 case EK_Exception:
2331 case EK_New:
2332 case EK_Temporary:
2333 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002334 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002335 case EK_ArrayElement:
2336 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002337 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002338 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002339 return 0;
2340 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002341
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002342 // Silence GCC warning
2343 return 0;
2344}
2345
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002346bool InitializedEntity::allowsNRVO() const {
2347 switch (getKind()) {
2348 case EK_Result:
2349 case EK_Exception:
2350 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002351
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002352 case EK_Variable:
2353 case EK_Parameter:
2354 case EK_Member:
2355 case EK_New:
2356 case EK_Temporary:
2357 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002358 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002359 case EK_ArrayElement:
2360 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002361 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002362 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002363 break;
2364 }
2365
2366 return false;
2367}
2368
Douglas Gregor20093b42009-12-09 23:02:17 +00002369//===----------------------------------------------------------------------===//
2370// Initialization sequence
2371//===----------------------------------------------------------------------===//
2372
2373void InitializationSequence::Step::Destroy() {
2374 switch (Kind) {
2375 case SK_ResolveAddressOfOverloadedFunction:
2376 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002377 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002378 case SK_CastDerivedToBaseLValue:
2379 case SK_BindReference:
2380 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002381 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002382 case SK_UserConversion:
2383 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002384 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002385 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002386 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002387 case SK_ListConstructorCall:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002388 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002389 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002390 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002391 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002392 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002393 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002394 case SK_PassByIndirectCopyRestore:
2395 case SK_PassByIndirectRestore:
2396 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002397 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002398
Douglas Gregor20093b42009-12-09 23:02:17 +00002399 case SK_ConversionSequence:
2400 delete ICS;
2401 }
2402}
2403
Douglas Gregorb70cf442010-03-26 20:14:36 +00002404bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002405 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002406}
2407
2408bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002409 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002410 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002411
Douglas Gregorb70cf442010-03-26 20:14:36 +00002412 switch (getFailureKind()) {
2413 case FK_TooManyInitsForReference:
2414 case FK_ArrayNeedsInitList:
2415 case FK_ArrayNeedsInitListOrStringLiteral:
2416 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2417 case FK_NonConstLValueReferenceBindingToTemporary:
2418 case FK_NonConstLValueReferenceBindingToUnrelated:
2419 case FK_RValueReferenceBindingToLValue:
2420 case FK_ReferenceInitDropsQualifiers:
2421 case FK_ReferenceInitFailed:
2422 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002423 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002424 case FK_TooManyInitsForScalar:
2425 case FK_ReferenceBindingToInitList:
2426 case FK_InitListBadDestinationType:
2427 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002428 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002429 case FK_ArrayTypeMismatch:
2430 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002431 case FK_ListInitializationFailed:
John McCall5acb0c92011-10-17 18:40:02 +00002432 case FK_PlaceholderType:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002433 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002434
Douglas Gregorb70cf442010-03-26 20:14:36 +00002435 case FK_ReferenceInitOverloadFailed:
2436 case FK_UserConversionOverloadFailed:
2437 case FK_ConstructorOverloadFailed:
2438 return FailedOverloadResult == OR_Ambiguous;
2439 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002440
Douglas Gregorb70cf442010-03-26 20:14:36 +00002441 return false;
2442}
2443
Douglas Gregord6e44a32010-04-16 22:09:46 +00002444bool InitializationSequence::isConstructorInitialization() const {
2445 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2446}
2447
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002448bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2449 const Expr *Initializer,
2450 bool *isInitializerConstant,
2451 APValue *ConstantValue) const {
2452 if (Steps.empty() || Initializer->isValueDependent())
2453 return false;
2454
2455 const Step &LastStep = Steps.back();
2456 if (LastStep.Kind != SK_ConversionSequence)
2457 return false;
2458
2459 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2460 const StandardConversionSequence *SCS = NULL;
2461 switch (ICS.getKind()) {
2462 case ImplicitConversionSequence::StandardConversion:
2463 SCS = &ICS.Standard;
2464 break;
2465 case ImplicitConversionSequence::UserDefinedConversion:
2466 SCS = &ICS.UserDefined.After;
2467 break;
2468 case ImplicitConversionSequence::AmbiguousConversion:
2469 case ImplicitConversionSequence::EllipsisConversion:
2470 case ImplicitConversionSequence::BadConversion:
2471 return false;
2472 }
2473
2474 // Check if SCS represents a narrowing conversion, according to C++0x
2475 // [dcl.init.list]p7:
2476 //
2477 // A narrowing conversion is an implicit conversion ...
2478 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2479 QualType FromType = SCS->getToType(0);
2480 QualType ToType = SCS->getToType(1);
2481 switch (PossibleNarrowing) {
2482 // * from a floating-point type to an integer type, or
2483 //
2484 // * from an integer type or unscoped enumeration type to a floating-point
2485 // type, except where the source is a constant expression and the actual
2486 // value after conversion will fit into the target type and will produce
2487 // the original value when converted back to the original type, or
2488 case ICK_Floating_Integral:
2489 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2490 *isInitializerConstant = false;
2491 return true;
2492 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2493 llvm::APSInt IntConstantValue;
2494 if (Initializer &&
2495 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2496 // Convert the integer to the floating type.
2497 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2498 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2499 llvm::APFloat::rmNearestTiesToEven);
2500 // And back.
2501 llvm::APSInt ConvertedValue = IntConstantValue;
2502 bool ignored;
2503 Result.convertToInteger(ConvertedValue,
2504 llvm::APFloat::rmTowardZero, &ignored);
2505 // If the resulting value is different, this was a narrowing conversion.
2506 if (IntConstantValue != ConvertedValue) {
2507 *isInitializerConstant = true;
2508 *ConstantValue = APValue(IntConstantValue);
2509 return true;
2510 }
2511 } else {
2512 // Variables are always narrowings.
2513 *isInitializerConstant = false;
2514 return true;
2515 }
2516 }
2517 return false;
2518
2519 // * from long double to double or float, or from double to float, except
2520 // where the source is a constant expression and the actual value after
2521 // conversion is within the range of values that can be represented (even
2522 // if it cannot be represented exactly), or
2523 case ICK_Floating_Conversion:
2524 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2525 // FromType is larger than ToType.
2526 Expr::EvalResult InitializerValue;
2527 // FIXME: Check whether Initializer is a constant expression according
2528 // to C++0x [expr.const], rather than just whether it can be folded.
2529 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2530 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2531 // Constant! (Except for FIXME above.)
2532 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2533 // Convert the source value into the target type.
2534 bool ignored;
2535 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2536 Ctx.getFloatTypeSemantics(ToType),
2537 llvm::APFloat::rmNearestTiesToEven, &ignored);
2538 // If there was no overflow, the source value is within the range of
2539 // values that can be represented.
2540 if (ConvertStatus & llvm::APFloat::opOverflow) {
2541 *isInitializerConstant = true;
2542 *ConstantValue = InitializerValue.Val;
2543 return true;
2544 }
2545 } else {
2546 *isInitializerConstant = false;
2547 return true;
2548 }
2549 }
2550 return false;
2551
2552 // * from an integer type or unscoped enumeration type to an integer type
2553 // that cannot represent all the values of the original type, except where
2554 // the source is a constant expression and the actual value after
2555 // conversion will fit into the target type and will produce the original
2556 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002557 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002558 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2559 // Boolean conversions can be from pointers and pointers to members
2560 // [conv.bool], and those aren't considered narrowing conversions.
2561 return false;
2562 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002563 case ICK_Integral_Conversion: {
2564 assert(FromType->isIntegralOrUnscopedEnumerationType());
2565 assert(ToType->isIntegralOrUnscopedEnumerationType());
2566 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2567 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2568 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2569 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2570
2571 if (FromWidth > ToWidth ||
2572 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2573 // Not all values of FromType can be represented in ToType.
2574 llvm::APSInt InitializerValue;
2575 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2576 *isInitializerConstant = true;
2577 *ConstantValue = APValue(InitializerValue);
2578
2579 // Add a bit to the InitializerValue so we don't have to worry about
2580 // signed vs. unsigned comparisons.
2581 InitializerValue = InitializerValue.extend(
2582 InitializerValue.getBitWidth() + 1);
2583 // Convert the initializer to and from the target width and signed-ness.
2584 llvm::APSInt ConvertedValue = InitializerValue;
2585 ConvertedValue = ConvertedValue.trunc(ToWidth);
2586 ConvertedValue.setIsSigned(ToSigned);
2587 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2588 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2589 // If the result is different, this was a narrowing conversion.
2590 return ConvertedValue != InitializerValue;
2591 } else {
2592 // Variables are always narrowings.
2593 *isInitializerConstant = false;
2594 return true;
2595 }
2596 }
2597 return false;
2598 }
2599
2600 default:
2601 // Other kinds of conversions are not narrowings.
2602 return false;
2603 }
2604}
2605
Douglas Gregor20093b42009-12-09 23:02:17 +00002606void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002607 FunctionDecl *Function,
2608 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002609 Step S;
2610 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2611 S.Type = Function->getType();
Benjamin Kramer85035642011-10-09 17:58:25 +00002612 S.Function.HadMultipleCandidates = false;
John McCall9aa472c2010-03-19 07:35:19 +00002613 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002614 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002615 Steps.push_back(S);
2616}
2617
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002618void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002619 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002620 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002621 switch (VK) {
2622 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2623 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2624 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002625 default: llvm_unreachable("No such category");
2626 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002627 S.Type = BaseType;
2628 Steps.push_back(S);
2629}
2630
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002631void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002632 bool BindingTemporary) {
2633 Step S;
2634 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2635 S.Type = T;
2636 Steps.push_back(S);
2637}
2638
Douglas Gregor523d46a2010-04-18 07:40:54 +00002639void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2640 Step S;
2641 S.Kind = SK_ExtraneousCopyToTemporary;
2642 S.Type = T;
2643 Steps.push_back(S);
2644}
2645
Eli Friedman03981012009-12-11 02:42:07 +00002646void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002647 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002648 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002649 Step S;
2650 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002651 S.Type = T;
Benjamin Kramer85035642011-10-09 17:58:25 +00002652 S.Function.HadMultipleCandidates = false;
John McCall9aa472c2010-03-19 07:35:19 +00002653 S.Function.Function = Function;
2654 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002655 Steps.push_back(S);
2656}
2657
2658void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002659 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002660 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002661 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002662 switch (VK) {
2663 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002664 S.Kind = SK_QualificationConversionRValue;
2665 break;
John McCall5baba9d2010-08-25 10:28:54 +00002666 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002667 S.Kind = SK_QualificationConversionXValue;
2668 break;
John McCall5baba9d2010-08-25 10:28:54 +00002669 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002670 S.Kind = SK_QualificationConversionLValue;
2671 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002672 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002673 S.Type = Ty;
2674 Steps.push_back(S);
2675}
2676
2677void InitializationSequence::AddConversionSequenceStep(
2678 const ImplicitConversionSequence &ICS,
2679 QualType T) {
2680 Step S;
2681 S.Kind = SK_ConversionSequence;
2682 S.Type = T;
2683 S.ICS = new ImplicitConversionSequence(ICS);
2684 Steps.push_back(S);
2685}
2686
Douglas Gregord87b61f2009-12-10 17:56:55 +00002687void InitializationSequence::AddListInitializationStep(QualType T) {
2688 Step S;
2689 S.Kind = SK_ListInitialization;
2690 S.Type = T;
2691 Steps.push_back(S);
2692}
2693
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002694void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002695InitializationSequence::AddConstructorInitializationStep(
2696 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002697 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002698 QualType T) {
2699 Step S;
2700 S.Kind = SK_ConstructorInitialization;
2701 S.Type = T;
Benjamin Kramer85035642011-10-09 17:58:25 +00002702 S.Function.HadMultipleCandidates = false;
John McCall9aa472c2010-03-19 07:35:19 +00002703 S.Function.Function = Constructor;
2704 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002705 Steps.push_back(S);
2706}
2707
Douglas Gregor71d17402009-12-15 00:01:57 +00002708void InitializationSequence::AddZeroInitializationStep(QualType T) {
2709 Step S;
2710 S.Kind = SK_ZeroInitialization;
2711 S.Type = T;
2712 Steps.push_back(S);
2713}
2714
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002715void InitializationSequence::AddCAssignmentStep(QualType T) {
2716 Step S;
2717 S.Kind = SK_CAssignment;
2718 S.Type = T;
2719 Steps.push_back(S);
2720}
2721
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002722void InitializationSequence::AddStringInitStep(QualType T) {
2723 Step S;
2724 S.Kind = SK_StringInit;
2725 S.Type = T;
2726 Steps.push_back(S);
2727}
2728
Douglas Gregor569c3162010-08-07 11:51:51 +00002729void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2730 Step S;
2731 S.Kind = SK_ObjCObjectConversion;
2732 S.Type = T;
2733 Steps.push_back(S);
2734}
2735
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002736void InitializationSequence::AddArrayInitStep(QualType T) {
2737 Step S;
2738 S.Kind = SK_ArrayInit;
2739 S.Type = T;
2740 Steps.push_back(S);
2741}
2742
John McCallf85e1932011-06-15 23:02:42 +00002743void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2744 bool shouldCopy) {
2745 Step s;
2746 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2747 : SK_PassByIndirectRestore);
2748 s.Type = type;
2749 Steps.push_back(s);
2750}
2751
2752void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2753 Step S;
2754 S.Kind = SK_ProduceObjCObject;
2755 S.Type = T;
2756 Steps.push_back(S);
2757}
2758
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002759void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002760 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002761 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002762 this->Failure = Failure;
2763 this->FailedOverloadResult = Result;
2764}
2765
2766//===----------------------------------------------------------------------===//
2767// Attempt initialization
2768//===----------------------------------------------------------------------===//
2769
John McCallf85e1932011-06-15 23:02:42 +00002770static void MaybeProduceObjCObject(Sema &S,
2771 InitializationSequence &Sequence,
2772 const InitializedEntity &Entity) {
2773 if (!S.getLangOptions().ObjCAutoRefCount) return;
2774
2775 /// When initializing a parameter, produce the value if it's marked
2776 /// __attribute__((ns_consumed)).
2777 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2778 if (!Entity.isParameterConsumed())
2779 return;
2780
2781 assert(Entity.getType()->isObjCRetainableType() &&
2782 "consuming an object of unretainable type?");
2783 Sequence.AddProduceObjCObjectStep(Entity.getType());
2784
2785 /// When initializing a return value, if the return type is a
2786 /// retainable type, then returns need to immediately retain the
2787 /// object. If an autorelease is required, it will be done at the
2788 /// last instant.
2789 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2790 if (!Entity.getType()->isObjCRetainableType())
2791 return;
2792
2793 Sequence.AddProduceObjCObjectStep(Entity.getType());
2794 }
2795}
2796
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002797/// \brief Attempt list initialization (C++0x [dcl.init.list])
2798static void TryListInitialization(Sema &S,
2799 const InitializedEntity &Entity,
2800 const InitializationKind &Kind,
2801 InitListExpr *InitList,
2802 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002803 QualType DestType = Entity.getType();
2804
Sebastian Redl14b0c192011-09-24 17:48:00 +00002805 // C++ doesn't allow scalar initialization with more than one argument.
2806 // But C99 complex numbers are scalars and it makes sense there.
2807 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2808 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2809 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2810 return;
2811 }
2812 // FIXME: C++0x defines behavior for these two cases.
2813 if (DestType->isReferenceType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002814 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2815 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002816 }
2817 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002818 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00002819 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002820 }
2821
Sebastian Redl14b0c192011-09-24 17:48:00 +00002822 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00002823 DestType, /*VerifyOnly=*/true,
2824 Kind.getKind() != InitializationKind::IK_Direct ||
2825 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00002826 if (CheckInitList.HadError()) {
2827 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2828 return;
2829 }
2830
2831 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002832 Sequence.AddListInitializationStep(DestType);
2833}
Douglas Gregor20093b42009-12-09 23:02:17 +00002834
2835/// \brief Try a reference initialization that involves calling a conversion
2836/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002837static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2838 const InitializedEntity &Entity,
2839 const InitializationKind &Kind,
2840 Expr *Initializer,
2841 bool AllowRValues,
2842 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002843 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002844 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2845 QualType T1 = cv1T1.getUnqualifiedType();
2846 QualType cv2T2 = Initializer->getType();
2847 QualType T2 = cv2T2.getUnqualifiedType();
2848
2849 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002850 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002851 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002852 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002853 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002854 ObjCConversion,
2855 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002856 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002857 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002858 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002859 (void)ObjCLifetimeConversion;
2860
Douglas Gregor20093b42009-12-09 23:02:17 +00002861 // Build the candidate set directly in the initialization sequence
2862 // structure, so that it will persist if we fail.
2863 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2864 CandidateSet.clear();
2865
2866 // Determine whether we are allowed to call explicit constructors or
2867 // explicit conversion operators.
2868 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002869
Douglas Gregor20093b42009-12-09 23:02:17 +00002870 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002871 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2872 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002873 // The type we're converting to is a class type. Enumerate its constructors
2874 // to see if there is a suitable conversion.
2875 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002876
Douglas Gregor20093b42009-12-09 23:02:17 +00002877 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002878 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002879 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002880 NamedDecl *D = *Con;
2881 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2882
Douglas Gregor20093b42009-12-09 23:02:17 +00002883 // Find the constructor (which may be a template).
2884 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002885 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002886 if (ConstructorTmpl)
2887 Constructor = cast<CXXConstructorDecl>(
2888 ConstructorTmpl->getTemplatedDecl());
2889 else
John McCall9aa472c2010-03-19 07:35:19 +00002890 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002891
Douglas Gregor20093b42009-12-09 23:02:17 +00002892 if (!Constructor->isInvalidDecl() &&
2893 Constructor->isConvertingConstructor(AllowExplicit)) {
2894 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002895 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002896 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002897 &Initializer, 1, CandidateSet,
2898 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002899 else
John McCall9aa472c2010-03-19 07:35:19 +00002900 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002901 &Initializer, 1, CandidateSet,
2902 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002903 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002904 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002905 }
John McCall572fc622010-08-17 07:23:57 +00002906 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2907 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002908
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002909 const RecordType *T2RecordType = 0;
2910 if ((T2RecordType = T2->getAs<RecordType>()) &&
2911 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002912 // The type we're converting from is a class type, enumerate its conversion
2913 // functions.
2914 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2915
John McCalleec51cf2010-01-20 00:46:10 +00002916 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002917 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002918 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2919 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002920 NamedDecl *D = *I;
2921 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2922 if (isa<UsingShadowDecl>(D))
2923 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002924
Douglas Gregor20093b42009-12-09 23:02:17 +00002925 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2926 CXXConversionDecl *Conv;
2927 if (ConvTemplate)
2928 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2929 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002930 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002931
Douglas Gregor20093b42009-12-09 23:02:17 +00002932 // If the conversion function doesn't return a reference type,
2933 // it can't be considered for this conversion unless we're allowed to
2934 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002935 // FIXME: Do we need to make sure that we only consider conversion
2936 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002937 // break recursion.
2938 if ((AllowExplicit || !Conv->isExplicit()) &&
2939 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2940 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002941 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002942 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002943 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002944 else
John McCall9aa472c2010-03-19 07:35:19 +00002945 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002946 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002947 }
2948 }
2949 }
John McCall572fc622010-08-17 07:23:57 +00002950 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2951 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002952
Douglas Gregor20093b42009-12-09 23:02:17 +00002953 SourceLocation DeclLoc = Initializer->getLocStart();
2954
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002955 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002956 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002957 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002958 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002959 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002960
Douglas Gregor20093b42009-12-09 23:02:17 +00002961 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002962
Chandler Carruth25ca4212011-02-25 19:41:05 +00002963 // This is the overload that will actually be used for the initialization, so
2964 // mark it as used.
2965 S.MarkDeclarationReferenced(DeclLoc, Function);
2966
Eli Friedman03981012009-12-11 02:42:07 +00002967 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002968 if (isa<CXXConversionDecl>(Function))
2969 T2 = Function->getResultType();
2970 else
2971 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002972
2973 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002974 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002975 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002976
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002977 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002978 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002979 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002980 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002981 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002982 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002983 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002984
Douglas Gregor20093b42009-12-09 23:02:17 +00002985 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002986 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002987 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002988 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002989 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002990 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002991 NewDerivedToBase, NewObjCConversion,
2992 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002993 if (NewRefRelationship == Sema::Ref_Incompatible) {
2994 // If the type we've converted to is not reference-related to the
2995 // type we're looking for, then there is another conversion step
2996 // we need to perform to produce a temporary of the right type
2997 // that we'll be binding to.
2998 ImplicitConversionSequence ICS;
2999 ICS.setStandard();
3000 ICS.Standard = Best->FinalConversion;
3001 T2 = ICS.Standard.getToType(2);
3002 Sequence.AddConversionSequenceStep(ICS, T2);
3003 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003004 Sequence.AddDerivedToBaseCastStep(
3005 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003006 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003007 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003008 else if (NewObjCConversion)
3009 Sequence.AddObjCObjectConversionStep(
3010 S.Context.getQualifiedType(T1,
3011 T2.getNonReferenceType().getQualifiers()));
3012
Douglas Gregor20093b42009-12-09 23:02:17 +00003013 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003014 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003015
Douglas Gregor20093b42009-12-09 23:02:17 +00003016 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3017 return OR_Success;
3018}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019
Richard Smith83da2e72011-10-19 16:55:56 +00003020static void CheckCXX98CompatAccessibleCopy(Sema &S,
3021 const InitializedEntity &Entity,
3022 Expr *CurInitExpr);
3023
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003024/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3025static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003026 const InitializedEntity &Entity,
3027 const InitializationKind &Kind,
3028 Expr *Initializer,
3029 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003030 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003031 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003032 Qualifiers T1Quals;
3033 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003034 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003035 Qualifiers T2Quals;
3036 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003037 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00003038
Douglas Gregor20093b42009-12-09 23:02:17 +00003039 // If the initializer is the address of an overloaded function, try
3040 // to resolve the overloaded function. If all goes well, T2 is the
3041 // type of the resulting function.
3042 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00003043 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003044 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00003045 T1,
3046 false,
3047 Found)) {
3048 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
3049 cv2T2 = Fn->getType();
3050 T2 = cv2T2.getUnqualifiedType();
3051 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003052 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3053 return;
3054 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003055 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003056
Douglas Gregor20093b42009-12-09 23:02:17 +00003057 // Compute some basic properties of the types and the initializer.
3058 bool isLValueRef = DestType->isLValueReferenceType();
3059 bool isRValueRef = !isLValueRef;
3060 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003061 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003062 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003063 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003064 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003065 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003066 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003067
Douglas Gregor20093b42009-12-09 23:02:17 +00003068 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003069 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003070 // "cv2 T2" as follows:
3071 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003072 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003073 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003074 // Note the analogous bullet points for rvlaue refs to functions. Because
3075 // there are no function rvalues in C++, rvalue refs to functions are treated
3076 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003077 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003078 bool T1Function = T1->isFunctionType();
3079 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003080 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003081 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003082 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003083 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003084 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003085 // reference-compatible with "cv2 T2," or
3086 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003087 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003088 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003089 // can occur. However, we do pay attention to whether it is a bit-field
3090 // to decide whether we're actually binding to a temporary created from
3091 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003092 if (DerivedToBase)
3093 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003094 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003095 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003096 else if (ObjCConversion)
3097 Sequence.AddObjCObjectConversionStep(
3098 S.Context.getQualifiedType(T1, T2Quals));
3099
Chandler Carruth5535c382010-01-12 20:32:25 +00003100 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003101 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003102 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003103 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003104 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003105 return;
3106 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003107
3108 // - has a class type (i.e., T2 is a class type), where T1 is not
3109 // reference-related to T2, and can be implicitly converted to an
3110 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3111 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003112 // applicable conversion functions (13.3.1.6) and choosing the best
3113 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003114 // If we have an rvalue ref to function type here, the rhs must be
3115 // an rvalue.
3116 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3117 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003118 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003119 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003120 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003121 Sequence);
3122 if (ConvOvlResult == OR_Success)
3123 return;
John McCall1d318332010-01-12 00:44:57 +00003124 if (ConvOvlResult != OR_No_Viable_Function) {
3125 Sequence.SetOverloadFailure(
3126 InitializationSequence::FK_ReferenceInitOverloadFailed,
3127 ConvOvlResult);
3128 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003129 }
3130 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003131
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003132 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003133 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003134 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003135 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003136 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3137 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3138 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003139 Sequence.SetOverloadFailure(
3140 InitializationSequence::FK_ReferenceInitOverloadFailed,
3141 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003142 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003143 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003144 ? (RefRelationship == Sema::Ref_Related
3145 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3146 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3147 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003148
Douglas Gregor20093b42009-12-09 23:02:17 +00003149 return;
3150 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003151
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003152 // - If the initializer expression
3153 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3154 // "cv1 T1" is reference-compatible with "cv2 T2"
3155 // Note: functions are handled below.
3156 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003157 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003158 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003159 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003160 (InitCategory.isXValue() ||
3161 (InitCategory.isPRValue() && T2->isRecordType()) ||
3162 (InitCategory.isPRValue() && T2->isArrayType()))) {
3163 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3164 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003165 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3166 // compiler the freedom to perform a copy here or bind to the
3167 // object, while C++0x requires that we bind directly to the
3168 // object. Hence, we always bind to the object without making an
3169 // extra copy. However, in C++03 requires that we check for the
3170 // presence of a suitable copy constructor:
3171 //
3172 // The constructor that would be used to make the copy shall
3173 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003174 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003175 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith83da2e72011-10-19 16:55:56 +00003176 else if (S.getLangOptions().CPlusPlus0x)
3177 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003178 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003179
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003180 if (DerivedToBase)
3181 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3182 ValueKind);
3183 else if (ObjCConversion)
3184 Sequence.AddObjCObjectConversionStep(
3185 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003186
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003187 if (T1Quals != T2Quals)
3188 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003189 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003190 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003191 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003192 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193
3194 // - has a class type (i.e., T2 is a class type), where T1 is not
3195 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003196 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3197 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003198 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003199 if (RefRelationship == Sema::Ref_Incompatible) {
3200 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3201 Kind, Initializer,
3202 /*AllowRValues=*/true,
3203 Sequence);
3204 if (ConvOvlResult)
3205 Sequence.SetOverloadFailure(
3206 InitializationSequence::FK_ReferenceInitOverloadFailed,
3207 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003208
Douglas Gregor20093b42009-12-09 23:02:17 +00003209 return;
3210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211
Douglas Gregor20093b42009-12-09 23:02:17 +00003212 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3213 return;
3214 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003215
3216 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003217 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003219 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003220
Douglas Gregor20093b42009-12-09 23:02:17 +00003221 // Determine whether we are allowed to call explicit constructors or
3222 // explicit conversion operators.
3223 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003224
3225 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3226
John McCallf85e1932011-06-15 23:02:42 +00003227 ImplicitConversionSequence ICS
3228 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003229 /*SuppressUserConversions*/ false,
3230 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003231 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003232 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3233 /*AllowObjCWritebackConversion=*/false);
3234
3235 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003236 // FIXME: Use the conversion function set stored in ICS to turn
3237 // this into an overloading ambiguity diagnostic. However, we need
3238 // to keep that set as an OverloadCandidateSet rather than as some
3239 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003240 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3241 Sequence.SetOverloadFailure(
3242 InitializationSequence::FK_ReferenceInitOverloadFailed,
3243 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003244 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3245 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003246 else
3247 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003248 return;
John McCallf85e1932011-06-15 23:02:42 +00003249 } else {
3250 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003251 }
3252
3253 // [...] If T1 is reference-related to T2, cv1 must be the
3254 // same cv-qualification as, or greater cv-qualification
3255 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003256 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3257 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003259 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003260 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3261 return;
3262 }
3263
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003265 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003266 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003267 InitCategory.isLValue()) {
3268 Sequence.SetFailed(
3269 InitializationSequence::FK_RValueReferenceBindingToLValue);
3270 return;
3271 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003272
Douglas Gregor20093b42009-12-09 23:02:17 +00003273 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3274 return;
3275}
3276
3277/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003278/// (C++ [dcl.init.string], C99 6.7.8).
3279static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003280 const InitializedEntity &Entity,
3281 const InitializationKind &Kind,
3282 Expr *Initializer,
3283 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003284 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003285}
3286
Douglas Gregor20093b42009-12-09 23:02:17 +00003287/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3288/// enumerates the constructors of the initialized entity and performs overload
3289/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003290static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003291 const InitializedEntity &Entity,
3292 const InitializationKind &Kind,
3293 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003294 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003295 InitializationSequence &Sequence) {
Richard Trieu898267f2011-09-01 21:44:13 +00003296 // Check constructor arguments for self reference.
3297 if (DeclaratorDecl *DD = Entity.getDecl())
3298 // Parameters arguments are occassionially constructed with itself,
3299 // for instance, in recursive functions. Skip them.
3300 if (!isa<ParmVarDecl>(DD))
3301 for (unsigned i = 0; i < NumArgs; ++i)
3302 S.CheckSelfReference(DD, Args[i]);
3303
Douglas Gregor51c56d62009-12-14 20:49:26 +00003304 // Build the candidate set directly in the initialization sequence
3305 // structure, so that it will persist if we fail.
3306 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3307 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003308
Douglas Gregor51c56d62009-12-14 20:49:26 +00003309 // Determine whether we are allowed to call explicit constructors or
3310 // explicit conversion operators.
3311 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3312 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003313 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003314
3315 // The type we're constructing needs to be complete.
3316 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003317 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003318 return;
3319 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003320
Douglas Gregor51c56d62009-12-14 20:49:26 +00003321 // The type we're converting to is a class type. Enumerate its constructors
3322 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003323 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003324 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003325 CXXRecordDecl *DestRecordDecl
3326 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327
Douglas Gregor51c56d62009-12-14 20:49:26 +00003328 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003329 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003330 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003331 NamedDecl *D = *Con;
3332 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003333 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003334
Douglas Gregor51c56d62009-12-14 20:49:26 +00003335 // Find the constructor (which may be a template).
3336 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003337 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003338 if (ConstructorTmpl)
3339 Constructor = cast<CXXConstructorDecl>(
3340 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003341 else {
John McCall9aa472c2010-03-19 07:35:19 +00003342 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003343
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003345 // suppress user-defined conversions on the arguments.
3346 // FIXME: Move constructors?
3347 if (Kind.getKind() == InitializationKind::IK_Copy &&
3348 Constructor->isCopyConstructor())
3349 SuppressUserConversions = true;
3350 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003351
Douglas Gregor51c56d62009-12-14 20:49:26 +00003352 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003353 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003354 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003355 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003356 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003357 Args, NumArgs, CandidateSet,
3358 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003359 else
John McCall9aa472c2010-03-19 07:35:19 +00003360 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003361 Args, NumArgs, CandidateSet,
3362 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003363 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364 }
3365
Douglas Gregor51c56d62009-12-14 20:49:26 +00003366 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003367
3368 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003369 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003370 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003371 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003372 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003374 Result);
3375 return;
3376 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003377
3378 // C++0x [dcl.init]p6:
3379 // If a program calls for the default initialization of an object
3380 // of a const-qualified type T, T shall be a class type with a
3381 // user-provided default constructor.
3382 if (Kind.getKind() == InitializationKind::IK_Default &&
3383 Entity.getType().isConstQualified() &&
3384 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3385 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3386 return;
3387 }
3388
Douglas Gregor51c56d62009-12-14 20:49:26 +00003389 // Add the constructor initialization step. Any cv-qualification conversion is
3390 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003391 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003393 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003394 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003395}
3396
Douglas Gregor71d17402009-12-15 00:01:57 +00003397/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003398static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003399 const InitializedEntity &Entity,
3400 const InitializationKind &Kind,
3401 InitializationSequence &Sequence) {
3402 // C++ [dcl.init]p5:
3403 //
3404 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003405 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003406
Douglas Gregor71d17402009-12-15 00:01:57 +00003407 // -- if T is an array type, then each element is value-initialized;
3408 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3409 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410
Douglas Gregor71d17402009-12-15 00:01:57 +00003411 if (const RecordType *RT = T->getAs<RecordType>()) {
3412 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3413 // -- if T is a class type (clause 9) with a user-declared
3414 // constructor (12.1), then the default constructor for T is
3415 // called (and the initialization is ill-formed if T has no
3416 // accessible default constructor);
3417 //
3418 // FIXME: we really want to refer to a single subobject of the array,
3419 // but Entity doesn't have a way to capture that (yet).
3420 if (ClassDecl->hasUserDeclaredConstructor())
3421 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003422
Douglas Gregor16006c92009-12-16 18:50:27 +00003423 // -- if T is a (possibly cv-qualified) non-union class type
3424 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003425 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003426 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003427 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003428 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003429 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003430 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003431 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003432 }
3433 }
3434
Douglas Gregord6542d82009-12-22 15:35:07 +00003435 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003436}
3437
Douglas Gregor99a2e602009-12-16 01:38:02 +00003438/// \brief Attempt default initialization (C++ [dcl.init]p6).
3439static void TryDefaultInitialization(Sema &S,
3440 const InitializedEntity &Entity,
3441 const InitializationKind &Kind,
3442 InitializationSequence &Sequence) {
3443 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003444
Douglas Gregor99a2e602009-12-16 01:38:02 +00003445 // C++ [dcl.init]p6:
3446 // To default-initialize an object of type T means:
3447 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003448 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3449
Douglas Gregor99a2e602009-12-16 01:38:02 +00003450 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3451 // constructor for T is called (and the initialization is ill-formed if
3452 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003453 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003454 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3455 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003456 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003457
Douglas Gregor99a2e602009-12-16 01:38:02 +00003458 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003459
Douglas Gregor99a2e602009-12-16 01:38:02 +00003460 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003461 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003462 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003463 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003464 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003465 return;
3466 }
3467
3468 // If the destination type has a lifetime property, zero-initialize it.
3469 if (DestType.getQualifiers().hasObjCLifetime()) {
3470 Sequence.AddZeroInitializationStep(Entity.getType());
3471 return;
3472 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003473}
3474
Douglas Gregor20093b42009-12-09 23:02:17 +00003475/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3476/// which enumerates all conversion functions and performs overload resolution
3477/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003479 const InitializedEntity &Entity,
3480 const InitializationKind &Kind,
3481 Expr *Initializer,
3482 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003483 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003484 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3485 QualType SourceType = Initializer->getType();
3486 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3487 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003488
Douglas Gregor4a520a22009-12-14 17:27:33 +00003489 // Build the candidate set directly in the initialization sequence
3490 // structure, so that it will persist if we fail.
3491 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3492 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493
Douglas Gregor4a520a22009-12-14 17:27:33 +00003494 // Determine whether we are allowed to call explicit constructors or
3495 // explicit conversion operators.
3496 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003497
Douglas Gregor4a520a22009-12-14 17:27:33 +00003498 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3499 // The type we're converting to is a class type. Enumerate its constructors
3500 // to see if there is a suitable conversion.
3501 CXXRecordDecl *DestRecordDecl
3502 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003503
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003504 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003505 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003506 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003507 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003508 Con != ConEnd; ++Con) {
3509 NamedDecl *D = *Con;
3510 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003511
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003512 // Find the constructor (which may be a template).
3513 CXXConstructorDecl *Constructor = 0;
3514 FunctionTemplateDecl *ConstructorTmpl
3515 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003516 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003517 Constructor = cast<CXXConstructorDecl>(
3518 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003519 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003520 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003521
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003522 if (!Constructor->isInvalidDecl() &&
3523 Constructor->isConvertingConstructor(AllowExplicit)) {
3524 if (ConstructorTmpl)
3525 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3526 /*ExplicitArgs*/ 0,
3527 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003528 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003529 else
3530 S.AddOverloadCandidate(Constructor, FoundDecl,
3531 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003532 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003533 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003535 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003536 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003537
3538 SourceLocation DeclLoc = Initializer->getLocStart();
3539
Douglas Gregor4a520a22009-12-14 17:27:33 +00003540 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3541 // The type we're converting from is a class type, enumerate its conversion
3542 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003543
Eli Friedman33c2da92009-12-20 22:12:03 +00003544 // We can only enumerate the conversion functions for a complete type; if
3545 // the type isn't complete, simply skip this step.
3546 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3547 CXXRecordDecl *SourceRecordDecl
3548 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549
John McCalleec51cf2010-01-20 00:46:10 +00003550 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003551 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003552 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003553 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003554 I != E; ++I) {
3555 NamedDecl *D = *I;
3556 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3557 if (isa<UsingShadowDecl>(D))
3558 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559
Eli Friedman33c2da92009-12-20 22:12:03 +00003560 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3561 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003562 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003563 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003564 else
John McCall32daa422010-03-31 01:36:47 +00003565 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566
Eli Friedman33c2da92009-12-20 22:12:03 +00003567 if (AllowExplicit || !Conv->isExplicit()) {
3568 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003569 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003570 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003571 CandidateSet);
3572 else
John McCall9aa472c2010-03-19 07:35:19 +00003573 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003574 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003575 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003576 }
3577 }
3578 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003579
3580 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003581 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003582 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003583 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003584 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003585 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003586 Result);
3587 return;
3588 }
John McCall1d318332010-01-12 00:44:57 +00003589
Douglas Gregor4a520a22009-12-14 17:27:33 +00003590 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003591 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003592
Douglas Gregor4a520a22009-12-14 17:27:33 +00003593 if (isa<CXXConstructorDecl>(Function)) {
3594 // Add the user-defined conversion step. Any cv-qualification conversion is
3595 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003596 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003597 return;
3598 }
3599
3600 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003601 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003602 if (ConvType->getAs<RecordType>()) {
3603 // If we're converting to a class type, there may be an copy if
3604 // the resulting temporary object (possible to create an object of
3605 // a base class type). That copy is not a separate conversion, so
3606 // we just make a note of the actual destination type (possibly a
3607 // base class of the type returned by the conversion function) and
3608 // let the user-defined conversion step handle the conversion.
3609 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3610 return;
3611 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003612
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003613 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003614
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003615 // If the conversion following the call to the conversion function
3616 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003617 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3618 Best->FinalConversion.Third) {
3619 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003620 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003621 ICS.Standard = Best->FinalConversion;
3622 Sequence.AddConversionSequenceStep(ICS, DestType);
3623 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003624}
3625
John McCallf85e1932011-06-15 23:02:42 +00003626/// The non-zero enum values here are indexes into diagnostic alternatives.
3627enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3628
3629/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003630static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3631 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003632 // Skip parens.
3633 e = e->IgnoreParens();
3634
3635 // Skip address-of nodes.
3636 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3637 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003638 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003639
3640 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003641 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3642 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003643 case CK_Dependent:
3644 case CK_BitCast:
3645 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003646 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003647 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003648
3649 case CK_ArrayToPointerDecay:
3650 return IIK_nonscalar;
3651
3652 case CK_NullToPointer:
3653 return IIK_okay;
3654
3655 default:
3656 break;
3657 }
3658
3659 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003660 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3661 if (!isAddressOf) return IIK_nonlocal;
3662
3663 VarDecl *var;
3664 if (isa<DeclRefExpr>(e)) {
3665 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3666 if (!var) return IIK_nonlocal;
3667 } else {
3668 var = cast<BlockDeclRefExpr>(e)->getDecl();
3669 }
3670
3671 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003672
3673 // If we have a conditional operator, check both sides.
3674 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003675 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003676 return iik;
3677
John McCallc03fa492011-06-27 23:59:58 +00003678 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003679
3680 // These are never scalar.
3681 } else if (isa<ArraySubscriptExpr>(e)) {
3682 return IIK_nonscalar;
3683
3684 // Otherwise, it needs to be a null pointer constant.
3685 } else {
3686 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3687 ? IIK_okay : IIK_nonlocal);
3688 }
3689
3690 return IIK_nonlocal;
3691}
3692
3693/// Check whether the given expression is a valid operand for an
3694/// indirect copy/restore.
3695static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3696 assert(src->isRValue());
3697
John McCallc03fa492011-06-27 23:59:58 +00003698 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003699 if (iik == IIK_okay) return;
3700
3701 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3702 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3703 << src->getSourceRange();
3704}
3705
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003706/// \brief Determine whether we have compatible array types for the
3707/// purposes of GNU by-copy array initialization.
3708static bool hasCompatibleArrayTypes(ASTContext &Context,
3709 const ArrayType *Dest,
3710 const ArrayType *Source) {
3711 // If the source and destination array types are equivalent, we're
3712 // done.
3713 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3714 return true;
3715
3716 // Make sure that the element types are the same.
3717 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3718 return false;
3719
3720 // The only mismatch we allow is when the destination is an
3721 // incomplete array type and the source is a constant array type.
3722 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3723}
3724
John McCallf85e1932011-06-15 23:02:42 +00003725static bool tryObjCWritebackConversion(Sema &S,
3726 InitializationSequence &Sequence,
3727 const InitializedEntity &Entity,
3728 Expr *Initializer) {
3729 bool ArrayDecay = false;
3730 QualType ArgType = Initializer->getType();
3731 QualType ArgPointee;
3732 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3733 ArrayDecay = true;
3734 ArgPointee = ArgArrayType->getElementType();
3735 ArgType = S.Context.getPointerType(ArgPointee);
3736 }
3737
3738 // Handle write-back conversion.
3739 QualType ConvertedArgType;
3740 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3741 ConvertedArgType))
3742 return false;
3743
3744 // We should copy unless we're passing to an argument explicitly
3745 // marked 'out'.
3746 bool ShouldCopy = true;
3747 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3748 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3749
3750 // Do we need an lvalue conversion?
3751 if (ArrayDecay || Initializer->isGLValue()) {
3752 ImplicitConversionSequence ICS;
3753 ICS.setStandard();
3754 ICS.Standard.setAsIdentityConversion();
3755
3756 QualType ResultType;
3757 if (ArrayDecay) {
3758 ICS.Standard.First = ICK_Array_To_Pointer;
3759 ResultType = S.Context.getPointerType(ArgPointee);
3760 } else {
3761 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3762 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3763 }
3764
3765 Sequence.AddConversionSequenceStep(ICS, ResultType);
3766 }
3767
3768 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3769 return true;
3770}
3771
Douglas Gregor20093b42009-12-09 23:02:17 +00003772InitializationSequence::InitializationSequence(Sema &S,
3773 const InitializedEntity &Entity,
3774 const InitializationKind &Kind,
3775 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003776 unsigned NumArgs)
3777 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003778 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003779
Douglas Gregor20093b42009-12-09 23:02:17 +00003780 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003781 // The semantics of initializers are as follows. The destination type is
3782 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003783 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003784 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003785 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003786 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003787
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003788 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003789 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3790 SequenceKind = DependentSequence;
3791 return;
3792 }
3793
Sebastian Redl7491c492011-06-05 13:59:11 +00003794 // Almost everything is a normal sequence.
3795 setSequenceKind(NormalSequence);
3796
John McCall241d5582010-12-07 22:54:16 +00003797 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003798 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3799 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3800 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003801 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003802 return;
3803 }
3804 Args[I] = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00003805 } else if (const BuiltinType *PlaceholderTy
3806 = Args[I]->getType()->getAsPlaceholderType()) {
3807 // FIXME: should we be doing this here?
3808 if (PlaceholderTy->getKind() != BuiltinType::Overload) {
3809 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3810 if (result.isInvalid()) {
3811 SetFailed(FK_PlaceholderType);
3812 return;
3813 }
3814 Args[I] = result.take();
3815 }
John Wiegley429bb272011-04-08 18:41:53 +00003816 }
John McCall241d5582010-12-07 22:54:16 +00003817
John McCall5acb0c92011-10-17 18:40:02 +00003818
Douglas Gregor20093b42009-12-09 23:02:17 +00003819 QualType SourceType;
3820 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003821 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003822 Initializer = Args[0];
3823 if (!isa<InitListExpr>(Initializer))
3824 SourceType = Initializer->getType();
3825 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826
3827 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003828 // list-initialized (8.5.4).
3829 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003830 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003831 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003832 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003833
Douglas Gregor20093b42009-12-09 23:02:17 +00003834 // - If the destination type is a reference type, see 8.5.3.
3835 if (DestType->isReferenceType()) {
3836 // C++0x [dcl.init.ref]p1:
3837 // A variable declared to be a T& or T&&, that is, "reference to type T"
3838 // (8.3.2), shall be initialized by an object, or function, of type T or
3839 // by an object that can be converted into a T.
3840 // (Therefore, multiple arguments are not permitted.)
3841 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003842 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003843 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003844 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003845 return;
3846 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003847
Douglas Gregor20093b42009-12-09 23:02:17 +00003848 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003849 if (Kind.getKind() == InitializationKind::IK_Value ||
3850 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003851 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003852 return;
3853 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003854
Douglas Gregor99a2e602009-12-16 01:38:02 +00003855 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003856 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003857 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003858 return;
3859 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003860
John McCallce6c9b72011-02-21 07:22:22 +00003861 // - If the destination type is an array of characters, an array of
3862 // char16_t, an array of char32_t, or an array of wchar_t, and the
3863 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003865 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003866 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3867 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003868 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003869 return;
3870 }
3871
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003872 // Note: as an GNU C extension, we allow initialization of an
3873 // array from a compound literal that creates an array of the same
3874 // type, so long as the initializer has no side effects.
3875 if (!S.getLangOptions().CPlusPlus && Initializer &&
3876 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3877 Initializer->getType()->isArrayType()) {
3878 const ArrayType *SourceAT
3879 = Context.getAsArrayType(Initializer->getType());
3880 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003881 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003882 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003883 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003884 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003885 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003886 }
3887 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003888 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003889 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003890 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003891
Douglas Gregor20093b42009-12-09 23:02:17 +00003892 return;
3893 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003894
John McCallf85e1932011-06-15 23:02:42 +00003895 // Determine whether we should consider writeback conversions for
3896 // Objective-C ARC.
3897 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3898 Entity.getKind() == InitializedEntity::EK_Parameter;
3899
3900 // We're at the end of the line for C: it's either a write-back conversion
3901 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003902 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003903 // If allowed, check whether this is an Objective-C writeback conversion.
3904 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003905 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003906 return;
3907 }
3908
3909 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003910 AddCAssignmentStep(DestType);
3911 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003912 return;
3913 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003914
John McCallf85e1932011-06-15 23:02:42 +00003915 assert(S.getLangOptions().CPlusPlus);
3916
Douglas Gregor20093b42009-12-09 23:02:17 +00003917 // - If the destination type is a (possibly cv-qualified) class type:
3918 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003919 // - If the initialization is direct-initialization, or if it is
3920 // copy-initialization where the cv-unqualified version of the
3921 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003922 // class of the destination, constructors are considered. [...]
3923 if (Kind.getKind() == InitializationKind::IK_Direct ||
3924 (Kind.getKind() == InitializationKind::IK_Copy &&
3925 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3926 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003927 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003928 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003929 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003930 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003931 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003932 // used) to a derived class thereof are enumerated as described in
3933 // 13.3.1.4, and the best one is chosen through overload resolution
3934 // (13.3).
3935 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003936 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003937 return;
3938 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003939
Douglas Gregor99a2e602009-12-16 01:38:02 +00003940 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003941 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003942 return;
3943 }
3944 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945
3946 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003947 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003948 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003949 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3950 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003951 return;
3952 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003953
Douglas Gregor20093b42009-12-09 23:02:17 +00003954 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003955 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003956 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003957 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003958 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003959
3960 ImplicitConversionSequence ICS
3961 = S.TryImplicitConversion(Initializer, Entity.getType(),
3962 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003963 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003964 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003965 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3966 allowObjCWritebackConversion);
3967
3968 if (ICS.isStandard() &&
3969 ICS.Standard.Second == ICK_Writeback_Conversion) {
3970 // Objective-C ARC writeback conversion.
3971
3972 // We should copy unless we're passing to an argument explicitly
3973 // marked 'out'.
3974 bool ShouldCopy = true;
3975 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3976 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3977
3978 // If there was an lvalue adjustment, add it as a separate conversion.
3979 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3980 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3981 ImplicitConversionSequence LvalueICS;
3982 LvalueICS.setStandard();
3983 LvalueICS.Standard.setAsIdentityConversion();
3984 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3985 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003986 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003987 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003988
3989 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003990 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003991 DeclAccessPair dap;
3992 if (Initializer->getType() == Context.OverloadTy &&
3993 !S.ResolveAddressOfOverloadedFunction(Initializer
3994 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003995 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003996 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003997 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003998 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003999 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004000
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004001 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004002 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004003}
4004
4005InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004006 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004007 StepEnd = Steps.end();
4008 Step != StepEnd; ++Step)
4009 Step->Destroy();
4010}
4011
4012//===----------------------------------------------------------------------===//
4013// Perform initialization
4014//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004015static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004016getAssignmentAction(const InitializedEntity &Entity) {
4017 switch(Entity.getKind()) {
4018 case InitializedEntity::EK_Variable:
4019 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004020 case InitializedEntity::EK_Exception:
4021 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004022 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004023 return Sema::AA_Initializing;
4024
4025 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004026 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004027 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4028 return Sema::AA_Sending;
4029
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004030 return Sema::AA_Passing;
4031
4032 case InitializedEntity::EK_Result:
4033 return Sema::AA_Returning;
4034
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004035 case InitializedEntity::EK_Temporary:
4036 // FIXME: Can we tell apart casting vs. converting?
4037 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004038
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004039 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004040 case InitializedEntity::EK_ArrayElement:
4041 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004042 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004043 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004044 return Sema::AA_Initializing;
4045 }
4046
4047 return Sema::AA_Converting;
4048}
4049
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004050/// \brief Whether we should binding a created object as a temporary when
4051/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004052static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004053 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004054 case InitializedEntity::EK_ArrayElement:
4055 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004056 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004057 case InitializedEntity::EK_New:
4058 case InitializedEntity::EK_Variable:
4059 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004060 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004061 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004062 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004063 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004064 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004065 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004066
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004067 case InitializedEntity::EK_Parameter:
4068 case InitializedEntity::EK_Temporary:
4069 return true;
4070 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004071
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004072 llvm_unreachable("missed an InitializedEntity kind?");
4073}
4074
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004075/// \brief Whether the given entity, when initialized with an object
4076/// created for that initialization, requires destruction.
4077static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4078 switch (Entity.getKind()) {
4079 case InitializedEntity::EK_Member:
4080 case InitializedEntity::EK_Result:
4081 case InitializedEntity::EK_New:
4082 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004083 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004084 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004085 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004086 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004087 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004088
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004089 case InitializedEntity::EK_Variable:
4090 case InitializedEntity::EK_Parameter:
4091 case InitializedEntity::EK_Temporary:
4092 case InitializedEntity::EK_ArrayElement:
4093 case InitializedEntity::EK_Exception:
4094 return true;
4095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004096
4097 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004098}
4099
Richard Smith83da2e72011-10-19 16:55:56 +00004100/// \brief Look for copy and move constructors and constructor templates, for
4101/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4102static void LookupCopyAndMoveConstructors(Sema &S,
4103 OverloadCandidateSet &CandidateSet,
4104 CXXRecordDecl *Class,
4105 Expr *CurInitExpr) {
4106 DeclContext::lookup_iterator Con, ConEnd;
4107 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4108 Con != ConEnd; ++Con) {
4109 CXXConstructorDecl *Constructor = 0;
4110
4111 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4112 // Handle copy/moveconstructors, only.
4113 if (!Constructor || Constructor->isInvalidDecl() ||
4114 !Constructor->isCopyOrMoveConstructor() ||
4115 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4116 continue;
4117
4118 DeclAccessPair FoundDecl
4119 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4120 S.AddOverloadCandidate(Constructor, FoundDecl,
4121 &CurInitExpr, 1, CandidateSet);
4122 continue;
4123 }
4124
4125 // Handle constructor templates.
4126 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4127 if (ConstructorTmpl->isInvalidDecl())
4128 continue;
4129
4130 Constructor = cast<CXXConstructorDecl>(
4131 ConstructorTmpl->getTemplatedDecl());
4132 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4133 continue;
4134
4135 // FIXME: Do we need to limit this to copy-constructor-like
4136 // candidates?
4137 DeclAccessPair FoundDecl
4138 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4139 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4140 &CurInitExpr, 1, CandidateSet, true);
4141 }
4142}
4143
4144/// \brief Get the location at which initialization diagnostics should appear.
4145static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4146 Expr *Initializer) {
4147 switch (Entity.getKind()) {
4148 case InitializedEntity::EK_Result:
4149 return Entity.getReturnLoc();
4150
4151 case InitializedEntity::EK_Exception:
4152 return Entity.getThrowLoc();
4153
4154 case InitializedEntity::EK_Variable:
4155 return Entity.getDecl()->getLocation();
4156
4157 case InitializedEntity::EK_ArrayElement:
4158 case InitializedEntity::EK_Member:
4159 case InitializedEntity::EK_Parameter:
4160 case InitializedEntity::EK_Temporary:
4161 case InitializedEntity::EK_New:
4162 case InitializedEntity::EK_Base:
4163 case InitializedEntity::EK_Delegating:
4164 case InitializedEntity::EK_VectorElement:
4165 case InitializedEntity::EK_ComplexElement:
4166 case InitializedEntity::EK_BlockElement:
4167 return Initializer->getLocStart();
4168 }
4169 llvm_unreachable("missed an InitializedEntity kind?");
4170}
4171
Douglas Gregor523d46a2010-04-18 07:40:54 +00004172/// \brief Make a (potentially elidable) temporary copy of the object
4173/// provided by the given initializer by calling the appropriate copy
4174/// constructor.
4175///
4176/// \param S The Sema object used for type-checking.
4177///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004178/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004179/// the type of the initializer expression or a superclass thereof.
4180///
4181/// \param Enter The entity being initialized.
4182///
4183/// \param CurInit The initializer expression.
4184///
4185/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4186/// is permitted in C++03 (but not C++0x) when binding a reference to
4187/// an rvalue.
4188///
4189/// \returns An expression that copies the initializer expression into
4190/// a temporary object, or an error expression if a copy could not be
4191/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004192static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004193 QualType T,
4194 const InitializedEntity &Entity,
4195 ExprResult CurInit,
4196 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004197 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004198 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004199 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004200 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004201 Class = cast<CXXRecordDecl>(Record->getDecl());
4202 if (!Class)
4203 return move(CurInit);
4204
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004205 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004206 // When certain criteria are met, an implementation is allowed to
4207 // omit the copy/move construction of a class object, even if the
4208 // copy/move constructor and/or destructor for the object have
4209 // side effects. [...]
4210 // - when a temporary class object that has not been bound to a
4211 // reference (12.2) would be copied/moved to a class object
4212 // with the same cv-unqualified type, the copy/move operation
4213 // can be omitted by constructing the temporary object
4214 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004215 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004216 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004217 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004218 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004219 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004220 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004221 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004222
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004224 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4225 return move(CurInit);
4226
Douglas Gregorcc15f012011-01-21 19:38:21 +00004227 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004228 // Only consider constructors and constructor templates. Per
4229 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4230 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004231 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004232 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004233
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004234 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4235
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004236 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004237 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004238 case OR_Success:
4239 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004240
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004241 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004242 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4243 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4244 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004245 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004246 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004247 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004248 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004249 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004250 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004251
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004252 case OR_Ambiguous:
4253 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004254 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004255 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004256 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004257 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004259 case OR_Deleted:
4260 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004261 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004262 << CurInitExpr->getSourceRange();
4263 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004264 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004265 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004266 }
4267
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004268 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004269 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004270 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004271
Anders Carlsson9a68a672010-04-21 18:47:17 +00004272 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004273 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004274
4275 if (IsExtraneousCopy) {
4276 // If this is a totally extraneous copy for C++03 reference
4277 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004278 // expression. We don't generate an (elided) copy operation here
4279 // because doing so would require us to pass down a flag to avoid
4280 // infinite recursion, where each step adds another extraneous,
4281 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004282
Douglas Gregor2559a702010-04-18 07:57:34 +00004283 // Instantiate the default arguments of any extra parameters in
4284 // the selected copy constructor, as if we were going to create a
4285 // proper call to the copy constructor.
4286 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4287 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4288 if (S.RequireCompleteType(Loc, Parm->getType(),
4289 S.PDiag(diag::err_call_incomplete_argument)))
4290 break;
4291
4292 // Build the default argument expression; we don't actually care
4293 // if this succeeds or not, because this routine will complain
4294 // if there was a problem.
4295 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4296 }
4297
Douglas Gregor523d46a2010-04-18 07:40:54 +00004298 return S.Owned(CurInitExpr);
4299 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300
Chandler Carruth25ca4212011-02-25 19:41:05 +00004301 S.MarkDeclarationReferenced(Loc, Constructor);
4302
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004303 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004304 // constructor call (we might have derived-to-base conversions, or
4305 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004306 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004307 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004308 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004309
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004310 // Actually perform the constructor call.
4311 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004312 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004313 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004314 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004315 CXXConstructExpr::CK_Complete,
4316 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004317
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004318 // If we're supposed to bind temporaries, do so.
4319 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4320 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4321 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004322}
Douglas Gregor20093b42009-12-09 23:02:17 +00004323
Richard Smith83da2e72011-10-19 16:55:56 +00004324/// \brief Check whether elidable copy construction for binding a reference to
4325/// a temporary would have succeeded if we were building in C++98 mode, for
4326/// -Wc++98-compat.
4327static void CheckCXX98CompatAccessibleCopy(Sema &S,
4328 const InitializedEntity &Entity,
4329 Expr *CurInitExpr) {
4330 assert(S.getLangOptions().CPlusPlus0x);
4331
4332 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4333 if (!Record)
4334 return;
4335
4336 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4337 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4338 == DiagnosticsEngine::Ignored)
4339 return;
4340
4341 // Find constructors which would have been considered.
4342 OverloadCandidateSet CandidateSet(Loc);
4343 LookupCopyAndMoveConstructors(
4344 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4345
4346 // Perform overload resolution.
4347 OverloadCandidateSet::iterator Best;
4348 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4349
4350 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4351 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4352 << CurInitExpr->getSourceRange();
4353
4354 switch (OR) {
4355 case OR_Success:
4356 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4357 Best->FoundDecl.getAccess(), Diag);
4358 // FIXME: Check default arguments as far as that's possible.
4359 break;
4360
4361 case OR_No_Viable_Function:
4362 S.Diag(Loc, Diag);
4363 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4364 break;
4365
4366 case OR_Ambiguous:
4367 S.Diag(Loc, Diag);
4368 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4369 break;
4370
4371 case OR_Deleted:
4372 S.Diag(Loc, Diag);
4373 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4374 << 1 << Best->Function->isDeleted();
4375 break;
4376 }
4377}
4378
Douglas Gregora41a8c52010-04-22 00:20:18 +00004379void InitializationSequence::PrintInitLocationNote(Sema &S,
4380 const InitializedEntity &Entity) {
4381 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4382 if (Entity.getDecl()->getLocation().isInvalid())
4383 return;
4384
4385 if (Entity.getDecl()->getDeclName())
4386 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4387 << Entity.getDecl()->getDeclName();
4388 else
4389 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4390 }
4391}
4392
Sebastian Redl3b802322011-07-14 19:07:55 +00004393static bool isReferenceBinding(const InitializationSequence::Step &s) {
4394 return s.Kind == InitializationSequence::SK_BindReference ||
4395 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4396}
4397
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004398ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004399InitializationSequence::Perform(Sema &S,
4400 const InitializedEntity &Entity,
4401 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004402 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004403 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004404 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004405 unsigned NumArgs = Args.size();
4406 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004407 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004409
Sebastian Redl7491c492011-06-05 13:59:11 +00004410 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004411 // If the declaration is a non-dependent, incomplete array type
4412 // that has an initializer, then its type will be completed once
4413 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004414 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004415 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004416 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004417 if (const IncompleteArrayType *ArrayT
4418 = S.Context.getAsIncompleteArrayType(DeclType)) {
4419 // FIXME: We don't currently have the ability to accurately
4420 // compute the length of an initializer list without
4421 // performing full type-checking of the initializer list
4422 // (since we have to determine where braces are implicitly
4423 // introduced and such). So, we fall back to making the array
4424 // type a dependently-sized array type with no specified
4425 // bound.
4426 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4427 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004428
Douglas Gregord87b61f2009-12-10 17:56:55 +00004429 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004430 if (DeclaratorDecl *DD = Entity.getDecl()) {
4431 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4432 TypeLoc TL = TInfo->getTypeLoc();
4433 if (IncompleteArrayTypeLoc *ArrayLoc
4434 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4435 Brackets = ArrayLoc->getBracketsRange();
4436 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004437 }
4438
4439 *ResultType
4440 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4441 /*NumElts=*/0,
4442 ArrayT->getSizeModifier(),
4443 ArrayT->getIndexTypeCVRQualifiers(),
4444 Brackets);
4445 }
4446
4447 }
4448 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004449 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4450 Kind.isExplicitCast());
4451 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004452 }
4453
Sebastian Redl7491c492011-06-05 13:59:11 +00004454 // No steps means no initialization.
4455 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004456 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457
Douglas Gregord6542d82009-12-22 15:35:07 +00004458 QualType DestType = Entity.getType().getNonReferenceType();
4459 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004460 // the same as Entity.getDecl()->getType() in cases involving type merging,
4461 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004462 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004463 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004464 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004465
John McCall60d7b3a2010-08-24 06:29:42 +00004466 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004468 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004469 // grab the only argument out the Args and place it into the "current"
4470 // initializer.
4471 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004472 case SK_ResolveAddressOfOverloadedFunction:
4473 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004474 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004475 case SK_CastDerivedToBaseLValue:
4476 case SK_BindReference:
4477 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004478 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004479 case SK_UserConversion:
4480 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004481 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004482 case SK_QualificationConversionRValue:
4483 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004484 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004485 case SK_ListInitialization:
4486 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004487 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004488 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004489 case SK_ArrayInit:
4490 case SK_PassByIndirectCopyRestore:
4491 case SK_PassByIndirectRestore:
4492 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004493 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004494 CurInit = Args.get()[0];
4495 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004496
4497 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004498 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4499 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4500 if (CurInit.isInvalid())
4501 return ExprError();
4502 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004503 break;
John McCallf6a16482010-12-04 03:47:34 +00004504 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004505
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004506 case SK_ConstructorInitialization:
4507 case SK_ZeroInitialization:
4508 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004509 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510
4511 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004512 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004513 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004514 for (step_iterator Step = step_begin(), StepEnd = step_end();
4515 Step != StepEnd; ++Step) {
4516 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004517 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004518
John Wiegley429bb272011-04-08 18:41:53 +00004519 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004520
Douglas Gregor20093b42009-12-09 23:02:17 +00004521 switch (Step->Kind) {
4522 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004523 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004524 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004525 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004526 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004527 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004528 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004529 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004530 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004531
Douglas Gregor20093b42009-12-09 23:02:17 +00004532 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004533 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004534 case SK_CastDerivedToBaseLValue: {
4535 // We have a derived-to-base cast that produces either an rvalue or an
4536 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004537
John McCallf871d0c2010-08-07 06:22:56 +00004538 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004539
Douglas Gregor20093b42009-12-09 23:02:17 +00004540 // Casts to inaccessible base classes are allowed with C-style casts.
4541 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4542 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004543 CurInit.get()->getLocStart(),
4544 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004545 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004546 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004547
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004548 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4549 QualType T = SourceType;
4550 if (const PointerType *Pointer = T->getAs<PointerType>())
4551 T = Pointer->getPointeeType();
4552 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004553 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004554 cast<CXXRecordDecl>(RecordTy->getDecl()));
4555 }
4556
John McCall5baba9d2010-08-25 10:28:54 +00004557 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004558 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004559 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004560 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004561 VK_XValue :
4562 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004563 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4564 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004565 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004566 CurInit.get(),
4567 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004568 break;
4569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004570
Douglas Gregor20093b42009-12-09 23:02:17 +00004571 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004572 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004573 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4574 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004575 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004576 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004577 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004578 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004579 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004580 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004581
John Wiegley429bb272011-04-08 18:41:53 +00004582 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004583 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004584 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4585 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004586 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004587 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004588 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004589 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004590
Douglas Gregor20093b42009-12-09 23:02:17 +00004591 // Reference binding does not have any corresponding ASTs.
4592
4593 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004594 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004595 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004596
Douglas Gregor20093b42009-12-09 23:02:17 +00004597 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004598
Douglas Gregor20093b42009-12-09 23:02:17 +00004599 case SK_BindReferenceToTemporary:
4600 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004601 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004602 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004603
Douglas Gregor03e80032011-06-21 17:03:29 +00004604 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004605 CurInit = new (S.Context) MaterializeTemporaryExpr(
4606 Entity.getType().getNonReferenceType(),
4607 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004608 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004609
4610 // If we're binding to an Objective-C object that has lifetime, we
4611 // need cleanups.
4612 if (S.getLangOptions().ObjCAutoRefCount &&
4613 CurInit.get()->getType()->isObjCLifetimeType())
4614 S.ExprNeedsCleanups = true;
4615
Douglas Gregor20093b42009-12-09 23:02:17 +00004616 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004617
Douglas Gregor523d46a2010-04-18 07:40:54 +00004618 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004619 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004620 /*IsExtraneousCopy=*/true);
4621 break;
4622
Douglas Gregor20093b42009-12-09 23:02:17 +00004623 case SK_UserConversion: {
4624 // We have a user-defined conversion that invokes either a constructor
4625 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004626 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004627 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004628 FunctionDecl *Fn = Step->Function.Function;
4629 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004630 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004631 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00004632 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004633 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004634 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004635 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004636 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004637
Douglas Gregor20093b42009-12-09 23:02:17 +00004638 // Determine the arguments required to actually perform the constructor
4639 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004640 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004641 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004642 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004643 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004644 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004645
Douglas Gregor20093b42009-12-09 23:02:17 +00004646 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004647 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004648 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004649 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004650 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004651 CXXConstructExpr::CK_Complete,
4652 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004653 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004654 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004655
Anders Carlsson9a68a672010-04-21 18:47:17 +00004656 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004657 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004658 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659
John McCall2de56d12010-08-25 11:45:40 +00004660 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004661 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4662 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4663 S.IsDerivedFrom(SourceType, Class))
4664 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004665
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004666 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004667 } else {
4668 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004669 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00004670 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004671 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004672 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004673
4674 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004675 // derived-to-base conversion? I believe the answer is "no", because
4676 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004677 ExprResult CurInitExprRes =
4678 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4679 FoundFn, Conversion);
4680 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004681 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004682 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004683
Douglas Gregor20093b42009-12-09 23:02:17 +00004684 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004685 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4686 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00004687 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004688 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004689
John McCall2de56d12010-08-25 11:45:40 +00004690 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004691
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004692 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004694
Sebastian Redl3b802322011-07-14 19:07:55 +00004695 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004696 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004697 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004698 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004699 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004700 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004701 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004702 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004703 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004704 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004705 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4706 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004707 }
4708 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004709
John McCallf871d0c2010-08-07 06:22:56 +00004710 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004711 CurInit.get()->getType(),
4712 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00004713 CurInit.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004714
Douglas Gregor2f599792010-04-02 18:24:57 +00004715 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004716 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4717 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004718
Douglas Gregor20093b42009-12-09 23:02:17 +00004719 break;
4720 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004721
Douglas Gregor20093b42009-12-09 23:02:17 +00004722 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004723 case SK_QualificationConversionXValue:
4724 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004725 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004726 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004727 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004728 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004729 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004730 VK_XValue :
4731 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004732 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004733 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004734 }
4735
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004736 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004737 Sema::CheckedConversionKind CCK
4738 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4739 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4740 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4741 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004742 ExprResult CurInitExprRes =
4743 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004744 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004745 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004746 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004747 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004748 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004749 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750
Douglas Gregord87b61f2009-12-10 17:56:55 +00004751 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004752 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004753 QualType Ty = Step->Type;
Sebastian Redl14b0c192011-09-24 17:48:00 +00004754 InitListChecker PerformInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00004755 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false,
4756 Kind.getKind() != InitializationKind::IK_Direct ||
4757 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00004758 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00004759 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004760
4761 CurInit.release();
Sebastian Redl14b0c192011-09-24 17:48:00 +00004762 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004763 break;
4764 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004765
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004766 case SK_ListConstructorCall:
4767 assert(false && "List constructor calls not yet supported.");
4768
Douglas Gregor51c56d62009-12-14 20:49:26 +00004769 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004770 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004771 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004772 = cast<CXXConstructorDecl>(Step->Function.Function);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004773 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004774
Douglas Gregor51c56d62009-12-14 20:49:26 +00004775 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004776 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004777 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4778 ? Kind.getEqualLoc()
4779 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004780
4781 if (Kind.getKind() == InitializationKind::IK_Default) {
4782 // Force even a trivial, implicit default constructor to be
4783 // semantically checked. We do this explicitly because we don't build
4784 // the definition for completely trivial constructors.
4785 CXXRecordDecl *ClassDecl = Constructor->getParent();
4786 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004787 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004788 ClassDecl->hasTrivialDefaultConstructor() &&
4789 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004790 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4791 }
4792
Douglas Gregor51c56d62009-12-14 20:49:26 +00004793 // Determine the arguments required to actually perform the constructor
4794 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004795 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004796 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004797 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004798
4799
Douglas Gregor91be6f52010-03-02 17:18:33 +00004800 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004801 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004802 (Kind.getKind() == InitializationKind::IK_Direct ||
4803 Kind.getKind() == InitializationKind::IK_Value)) {
4804 // An explicitly-constructed temporary, e.g., X(1, 2).
4805 unsigned NumExprs = ConstructorArgs.size();
4806 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004807 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004808 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004809
Douglas Gregorab6677e2010-09-08 00:15:04 +00004810 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4811 if (!TSInfo)
4812 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004813
Douglas Gregor91be6f52010-03-02 17:18:33 +00004814 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4815 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004816 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004817 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004818 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004819 Kind.getParenRange(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004820 HadMultipleCandidates,
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004821 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004822 } else {
4823 CXXConstructExpr::ConstructionKind ConstructKind =
4824 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004825
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004826 if (Entity.getKind() == InitializedEntity::EK_Base) {
4827 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004828 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004829 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004830 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004831 ConstructKind = CXXConstructExpr::CK_Delegating;
4832 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004833
Chandler Carruth428edaf2010-10-25 08:47:36 +00004834 // Only get the parenthesis range if it is a direct construction.
4835 SourceRange parenRange =
4836 Kind.getKind() == InitializationKind::IK_Direct ?
4837 Kind.getParenRange() : SourceRange();
4838
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004839 // If the entity allows NRVO, mark the construction as elidable
4840 // unconditionally.
4841 if (Entity.allowsNRVO())
4842 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4843 Constructor, /*Elidable=*/true,
4844 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004845 HadMultipleCandidates,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004846 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004847 ConstructKind,
4848 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004849 else
4850 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004851 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004852 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004853 HadMultipleCandidates,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004854 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004855 ConstructKind,
4856 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004857 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004858 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004859 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004860
4861 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004862 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004863 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004864 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004865
Douglas Gregor2f599792010-04-02 18:24:57 +00004866 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004867 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004868
Douglas Gregor51c56d62009-12-14 20:49:26 +00004869 break;
4870 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004871
Douglas Gregor71d17402009-12-15 00:01:57 +00004872 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004873 step_iterator NextStep = Step;
4874 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004875 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004876 NextStep->Kind == SK_ConstructorInitialization) {
4877 // The need for zero-initialization is recorded directly into
4878 // the call to the object's constructor within the next step.
4879 ConstructorInitRequiresZeroInit = true;
4880 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4881 S.getLangOptions().CPlusPlus &&
4882 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004883 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4884 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004885 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004886 Kind.getRange().getBegin());
4887
4888 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4889 TSInfo->getType().getNonLValueExprType(S.Context),
4890 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004891 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004892 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004893 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004894 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004895 break;
4896 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004897
4898 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004899 QualType SourceType = CurInit.get()->getType();
4900 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004901 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004902 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4903 if (Result.isInvalid())
4904 return ExprError();
4905 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004906
4907 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004908 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004909 if (ConvTy != Sema::Compatible &&
4910 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004911 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004912 == Sema::Compatible)
4913 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004914 if (CurInitExprRes.isInvalid())
4915 return ExprError();
4916 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004917
Douglas Gregora41a8c52010-04-22 00:20:18 +00004918 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004919 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4920 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004921 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004922 getAssignmentAction(Entity),
4923 &Complained)) {
4924 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004925 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004926 } else if (Complained)
4927 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004928 break;
4929 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004930
4931 case SK_StringInit: {
4932 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004933 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004934 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004935 break;
4936 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004937
4938 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004939 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004940 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00004941 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00004942 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004943
4944 case SK_ArrayInit:
4945 // Okay: we checked everything before creating this step. Note that
4946 // this is a GNU extension.
4947 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004948 << Step->Type << CurInit.get()->getType()
4949 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004950
4951 // If the destination type is an incomplete array type, update the
4952 // type accordingly.
4953 if (ResultType) {
4954 if (const IncompleteArrayType *IncompleteDest
4955 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4956 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004957 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004958 *ResultType = S.Context.getConstantArrayType(
4959 IncompleteDest->getElementType(),
4960 ConstantSource->getSize(),
4961 ArrayType::Normal, 0);
4962 }
4963 }
4964 }
John McCallf85e1932011-06-15 23:02:42 +00004965 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004966
John McCallf85e1932011-06-15 23:02:42 +00004967 case SK_PassByIndirectCopyRestore:
4968 case SK_PassByIndirectRestore:
4969 checkIndirectCopyRestoreSource(S, CurInit.get());
4970 CurInit = S.Owned(new (S.Context)
4971 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4972 Step->Kind == SK_PassByIndirectCopyRestore));
4973 break;
4974
4975 case SK_ProduceObjCObject:
4976 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00004977 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00004978 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004979 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004980 }
4981 }
John McCall15d7d122010-11-11 03:21:53 +00004982
4983 // Diagnose non-fatal problems with the completed initialization.
4984 if (Entity.getKind() == InitializedEntity::EK_Member &&
4985 cast<FieldDecl>(Entity.getDecl())->isBitField())
4986 S.CheckBitFieldInitialization(Kind.getLocation(),
4987 cast<FieldDecl>(Entity.getDecl()),
4988 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004989
Douglas Gregor20093b42009-12-09 23:02:17 +00004990 return move(CurInit);
4991}
4992
4993//===----------------------------------------------------------------------===//
4994// Diagnose initialization failures
4995//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004996bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004997 const InitializedEntity &Entity,
4998 const InitializationKind &Kind,
4999 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005000 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005001 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005002
Douglas Gregord6542d82009-12-22 15:35:07 +00005003 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005004 switch (Failure) {
5005 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005006 // FIXME: Customize for the initialized entity?
5007 if (NumArgs == 0)
5008 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5009 << DestType.getNonReferenceType();
5010 else // FIXME: diagnostic below could be better!
5011 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5012 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005013 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005014
Douglas Gregor20093b42009-12-09 23:02:17 +00005015 case FK_ArrayNeedsInitList:
5016 case FK_ArrayNeedsInitListOrStringLiteral:
5017 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5018 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5019 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005020
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005021 case FK_ArrayTypeMismatch:
5022 case FK_NonConstantArrayInit:
5023 S.Diag(Kind.getLocation(),
5024 (Failure == FK_ArrayTypeMismatch
5025 ? diag::err_array_init_different_type
5026 : diag::err_array_init_non_constant_array))
5027 << DestType.getNonReferenceType()
5028 << Args[0]->getType()
5029 << Args[0]->getSourceRange();
5030 break;
5031
John McCall6bb80172010-03-30 21:47:33 +00005032 case FK_AddressOfOverloadFailed: {
5033 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005034 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005035 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005036 true,
5037 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005038 break;
John McCall6bb80172010-03-30 21:47:33 +00005039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005040
Douglas Gregor20093b42009-12-09 23:02:17 +00005041 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005042 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005043 switch (FailedOverloadResult) {
5044 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005045 if (Failure == FK_UserConversionOverloadFailed)
5046 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5047 << Args[0]->getType() << DestType
5048 << Args[0]->getSourceRange();
5049 else
5050 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5051 << DestType << Args[0]->getType()
5052 << Args[0]->getSourceRange();
5053
John McCall120d63c2010-08-24 20:38:10 +00005054 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005055 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005056
Douglas Gregor20093b42009-12-09 23:02:17 +00005057 case OR_No_Viable_Function:
5058 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5059 << Args[0]->getType() << DestType.getNonReferenceType()
5060 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00005061 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005062 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005063
Douglas Gregor20093b42009-12-09 23:02:17 +00005064 case OR_Deleted: {
5065 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5066 << Args[0]->getType() << DestType.getNonReferenceType()
5067 << Args[0]->getSourceRange();
5068 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005069 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005070 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5071 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005072 if (Ovl == OR_Deleted) {
5073 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005074 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00005075 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005076 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005077 }
5078 break;
5079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005080
Douglas Gregor20093b42009-12-09 23:02:17 +00005081 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005082 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005083 break;
5084 }
5085 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005086
Douglas Gregor20093b42009-12-09 23:02:17 +00005087 case FK_NonConstLValueReferenceBindingToTemporary:
5088 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005089 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005090 Failure == FK_NonConstLValueReferenceBindingToTemporary
5091 ? diag::err_lvalue_reference_bind_to_temporary
5092 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005093 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005094 << DestType.getNonReferenceType()
5095 << Args[0]->getType()
5096 << Args[0]->getSourceRange();
5097 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005098
Douglas Gregor20093b42009-12-09 23:02:17 +00005099 case FK_RValueReferenceBindingToLValue:
5100 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005101 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005102 << Args[0]->getSourceRange();
5103 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005104
Douglas Gregor20093b42009-12-09 23:02:17 +00005105 case FK_ReferenceInitDropsQualifiers:
5106 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5107 << DestType.getNonReferenceType()
5108 << Args[0]->getType()
5109 << Args[0]->getSourceRange();
5110 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005111
Douglas Gregor20093b42009-12-09 23:02:17 +00005112 case FK_ReferenceInitFailed:
5113 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5114 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005115 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005116 << Args[0]->getType()
5117 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005118 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5119 Args[0]->getType()->isObjCObjectPointerType())
5120 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005121 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005122
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005123 case FK_ConversionFailed: {
5124 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005125 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
5126 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005127 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005128 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005129 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005130 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005131 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5132 Args[0]->getType()->isObjCObjectPointerType())
5133 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005134 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005135 }
John Wiegley429bb272011-04-08 18:41:53 +00005136
5137 case FK_ConversionFromPropertyFailed:
5138 // No-op. This error has already been reported.
5139 break;
5140
Douglas Gregord87b61f2009-12-10 17:56:55 +00005141 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005142 SourceRange R;
5143
5144 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005145 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005146 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005147 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005148 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005149
Douglas Gregor19311e72010-09-08 21:40:08 +00005150 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5151 if (Kind.isCStyleOrFunctionalCast())
5152 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5153 << R;
5154 else
5155 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5156 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005157 break;
5158 }
5159
5160 case FK_ReferenceBindingToInitList:
5161 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5162 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5163 break;
5164
5165 case FK_InitListBadDestinationType:
5166 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5167 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5168 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005169
Douglas Gregor51c56d62009-12-14 20:49:26 +00005170 case FK_ConstructorOverloadFailed: {
5171 SourceRange ArgsRange;
5172 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005173 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005174 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005175
Douglas Gregor51c56d62009-12-14 20:49:26 +00005176 // FIXME: Using "DestType" for the entity we're printing is probably
5177 // bad.
5178 switch (FailedOverloadResult) {
5179 case OR_Ambiguous:
5180 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5181 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005182 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5183 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005184 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005185
Douglas Gregor51c56d62009-12-14 20:49:26 +00005186 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005187 if (Kind.getKind() == InitializationKind::IK_Default &&
5188 (Entity.getKind() == InitializedEntity::EK_Base ||
5189 Entity.getKind() == InitializedEntity::EK_Member) &&
5190 isa<CXXConstructorDecl>(S.CurContext)) {
5191 // This is implicit default initialization of a member or
5192 // base within a constructor. If no viable function was
5193 // found, notify the user that she needs to explicitly
5194 // initialize this base/member.
5195 CXXConstructorDecl *Constructor
5196 = cast<CXXConstructorDecl>(S.CurContext);
5197 if (Entity.getKind() == InitializedEntity::EK_Base) {
5198 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5199 << Constructor->isImplicit()
5200 << S.Context.getTypeDeclType(Constructor->getParent())
5201 << /*base=*/0
5202 << Entity.getType();
5203
5204 RecordDecl *BaseDecl
5205 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5206 ->getDecl();
5207 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5208 << S.Context.getTagDeclType(BaseDecl);
5209 } else {
5210 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5211 << Constructor->isImplicit()
5212 << S.Context.getTypeDeclType(Constructor->getParent())
5213 << /*member=*/1
5214 << Entity.getName();
5215 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5216
5217 if (const RecordType *Record
5218 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005219 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005220 diag::note_previous_decl)
5221 << S.Context.getTagDeclType(Record->getDecl());
5222 }
5223 break;
5224 }
5225
Douglas Gregor51c56d62009-12-14 20:49:26 +00005226 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5227 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005228 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005229 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005230
Douglas Gregor51c56d62009-12-14 20:49:26 +00005231 case OR_Deleted: {
5232 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5233 << true << DestType << ArgsRange;
5234 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005235 OverloadingResult Ovl
5236 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005237 if (Ovl == OR_Deleted) {
5238 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005239 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005240 } else {
5241 llvm_unreachable("Inconsistent overload resolution?");
5242 }
5243 break;
5244 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005245
Douglas Gregor51c56d62009-12-14 20:49:26 +00005246 case OR_Success:
5247 llvm_unreachable("Conversion did not fail!");
5248 break;
5249 }
5250 break;
5251 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005252
Douglas Gregor99a2e602009-12-16 01:38:02 +00005253 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005254 if (Entity.getKind() == InitializedEntity::EK_Member &&
5255 isa<CXXConstructorDecl>(S.CurContext)) {
5256 // This is implicit default-initialization of a const member in
5257 // a constructor. Complain that it needs to be explicitly
5258 // initialized.
5259 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5260 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5261 << Constructor->isImplicit()
5262 << S.Context.getTypeDeclType(Constructor->getParent())
5263 << /*const=*/1
5264 << Entity.getName();
5265 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5266 << Entity.getName();
5267 } else {
5268 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5269 << DestType << (bool)DestType->getAs<RecordType>();
5270 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005271 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005272
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005273 case FK_Incomplete:
5274 S.RequireCompleteType(Kind.getLocation(), DestType,
5275 diag::err_init_incomplete_type);
5276 break;
5277
Sebastian Redl14b0c192011-09-24 17:48:00 +00005278 case FK_ListInitializationFailed: {
5279 // Run the init list checker again to emit diagnostics.
5280 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5281 QualType DestType = Entity.getType();
5282 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00005283 DestType, /*VerifyOnly=*/false,
5284 Kind.getKind() != InitializationKind::IK_Direct ||
5285 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005286 assert(DiagnoseInitList.HadError() &&
5287 "Inconsistent init list check result.");
5288 break;
5289 }
John McCall5acb0c92011-10-17 18:40:02 +00005290
5291 case FK_PlaceholderType: {
5292 // FIXME: Already diagnosed!
5293 break;
5294 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005295 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005296
Douglas Gregora41a8c52010-04-22 00:20:18 +00005297 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005298 return true;
5299}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005300
Chris Lattner5f9e2722011-07-23 10:55:15 +00005301void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005302 switch (SequenceKind) {
5303 case FailedSequence: {
5304 OS << "Failed sequence: ";
5305 switch (Failure) {
5306 case FK_TooManyInitsForReference:
5307 OS << "too many initializers for reference";
5308 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005309
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005310 case FK_ArrayNeedsInitList:
5311 OS << "array requires initializer list";
5312 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005313
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005314 case FK_ArrayNeedsInitListOrStringLiteral:
5315 OS << "array requires initializer list or string literal";
5316 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005317
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005318 case FK_ArrayTypeMismatch:
5319 OS << "array type mismatch";
5320 break;
5321
5322 case FK_NonConstantArrayInit:
5323 OS << "non-constant array initializer";
5324 break;
5325
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005326 case FK_AddressOfOverloadFailed:
5327 OS << "address of overloaded function failed";
5328 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005329
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005330 case FK_ReferenceInitOverloadFailed:
5331 OS << "overload resolution for reference initialization failed";
5332 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005333
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005334 case FK_NonConstLValueReferenceBindingToTemporary:
5335 OS << "non-const lvalue reference bound to temporary";
5336 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005337
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005338 case FK_NonConstLValueReferenceBindingToUnrelated:
5339 OS << "non-const lvalue reference bound to unrelated type";
5340 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005341
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005342 case FK_RValueReferenceBindingToLValue:
5343 OS << "rvalue reference bound to an lvalue";
5344 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005345
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005346 case FK_ReferenceInitDropsQualifiers:
5347 OS << "reference initialization drops qualifiers";
5348 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005349
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005350 case FK_ReferenceInitFailed:
5351 OS << "reference initialization failed";
5352 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005353
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005354 case FK_ConversionFailed:
5355 OS << "conversion failed";
5356 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005357
John Wiegley429bb272011-04-08 18:41:53 +00005358 case FK_ConversionFromPropertyFailed:
5359 OS << "conversion from property failed";
5360 break;
5361
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005362 case FK_TooManyInitsForScalar:
5363 OS << "too many initializers for scalar";
5364 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005365
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005366 case FK_ReferenceBindingToInitList:
5367 OS << "referencing binding to initializer list";
5368 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005369
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005370 case FK_InitListBadDestinationType:
5371 OS << "initializer list for non-aggregate, non-scalar type";
5372 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005373
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005374 case FK_UserConversionOverloadFailed:
5375 OS << "overloading failed for user-defined conversion";
5376 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005377
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005378 case FK_ConstructorOverloadFailed:
5379 OS << "constructor overloading failed";
5380 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005381
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005382 case FK_DefaultInitOfConst:
5383 OS << "default initialization of a const variable";
5384 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005385
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005386 case FK_Incomplete:
5387 OS << "initialization of incomplete type";
5388 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005389
5390 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005391 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00005392 break;
5393
5394 case FK_PlaceholderType:
5395 OS << "initializer expression isn't contextually valid";
5396 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005397 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005398 OS << '\n';
5399 return;
5400 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005401
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005402 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005403 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005404 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005405
Sebastian Redl7491c492011-06-05 13:59:11 +00005406 case NormalSequence:
5407 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005408 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005409 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005410
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005411 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5412 if (S != step_begin()) {
5413 OS << " -> ";
5414 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005415
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005416 switch (S->Kind) {
5417 case SK_ResolveAddressOfOverloadedFunction:
5418 OS << "resolve address of overloaded function";
5419 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005420
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005421 case SK_CastDerivedToBaseRValue:
5422 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5423 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424
Sebastian Redl906082e2010-07-20 04:20:21 +00005425 case SK_CastDerivedToBaseXValue:
5426 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5427 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005428
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005429 case SK_CastDerivedToBaseLValue:
5430 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5431 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005432
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005433 case SK_BindReference:
5434 OS << "bind reference to lvalue";
5435 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005436
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005437 case SK_BindReferenceToTemporary:
5438 OS << "bind reference to a temporary";
5439 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005440
Douglas Gregor523d46a2010-04-18 07:40:54 +00005441 case SK_ExtraneousCopyToTemporary:
5442 OS << "extraneous C++03 copy to temporary";
5443 break;
5444
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005445 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005446 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005447 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005448
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005449 case SK_QualificationConversionRValue:
5450 OS << "qualification conversion (rvalue)";
5451
Sebastian Redl906082e2010-07-20 04:20:21 +00005452 case SK_QualificationConversionXValue:
5453 OS << "qualification conversion (xvalue)";
5454
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005455 case SK_QualificationConversionLValue:
5456 OS << "qualification conversion (lvalue)";
5457 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005458
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005459 case SK_ConversionSequence:
5460 OS << "implicit conversion sequence (";
5461 S->ICS->DebugPrint(); // FIXME: use OS
5462 OS << ")";
5463 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005464
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005465 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005466 OS << "list aggregate initialization";
5467 break;
5468
5469 case SK_ListConstructorCall:
5470 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005471 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005472
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005473 case SK_ConstructorInitialization:
5474 OS << "constructor initialization";
5475 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005476
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005477 case SK_ZeroInitialization:
5478 OS << "zero initialization";
5479 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005480
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005481 case SK_CAssignment:
5482 OS << "C assignment";
5483 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005484
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005485 case SK_StringInit:
5486 OS << "string initialization";
5487 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005488
5489 case SK_ObjCObjectConversion:
5490 OS << "Objective-C object conversion";
5491 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005492
5493 case SK_ArrayInit:
5494 OS << "array initialization";
5495 break;
John McCallf85e1932011-06-15 23:02:42 +00005496
5497 case SK_PassByIndirectCopyRestore:
5498 OS << "pass by indirect copy and restore";
5499 break;
5500
5501 case SK_PassByIndirectRestore:
5502 OS << "pass by indirect restore";
5503 break;
5504
5505 case SK_ProduceObjCObject:
5506 OS << "Objective-C object retension";
5507 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005508 }
5509 }
5510}
5511
5512void InitializationSequence::dump() const {
5513 dump(llvm::errs());
5514}
5515
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005516static void DiagnoseNarrowingInInitList(
5517 Sema& S, QualType EntityType, const Expr *InitE,
5518 bool Constant, const APValue &ConstantValue) {
5519 if (Constant) {
5520 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005521 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005522 ? diag::err_init_list_constant_narrowing
5523 : diag::warn_init_list_constant_narrowing)
5524 << InitE->getSourceRange()
5525 << ConstantValue
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005526 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005527 } else
5528 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005529 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005530 ? diag::err_init_list_variable_narrowing
5531 : diag::warn_init_list_variable_narrowing)
5532 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005533 << InitE->getType().getLocalUnqualifiedType()
5534 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005535
5536 llvm::SmallString<128> StaticCast;
5537 llvm::raw_svector_ostream OS(StaticCast);
5538 OS << "static_cast<";
5539 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5540 // It's important to use the typedef's name if there is one so that the
5541 // fixit doesn't break code using types like int64_t.
5542 //
5543 // FIXME: This will break if the typedef requires qualification. But
5544 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005545 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005546 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5547 OS << BT->getName(S.getLangOptions());
5548 else {
5549 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5550 // with a broken cast.
5551 return;
5552 }
5553 OS << ">(";
5554 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5555 << InitE->getSourceRange()
5556 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5557 << FixItHint::CreateInsertion(
5558 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5559}
5560
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005561//===----------------------------------------------------------------------===//
5562// Initialization helper functions
5563//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005564bool
5565Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5566 ExprResult Init) {
5567 if (Init.isInvalid())
5568 return false;
5569
5570 Expr *InitE = Init.get();
5571 assert(InitE && "No initialization expression");
5572
5573 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5574 SourceLocation());
5575 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005576 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005577}
5578
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005579ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005580Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5581 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005582 ExprResult Init,
5583 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005584 if (Init.isInvalid())
5585 return ExprError();
5586
John McCall15d7d122010-11-11 03:21:53 +00005587 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005588 assert(InitE && "No initialization expression?");
5589
5590 if (EqualLoc.isInvalid())
5591 EqualLoc = InitE->getLocStart();
5592
5593 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5594 EqualLoc);
5595 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5596 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005597
5598 bool Constant = false;
5599 APValue Result;
5600 if (TopLevelOfInitList &&
5601 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5602 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5603 Constant, Result);
5604 }
John McCallf312b1e2010-08-26 23:41:50 +00005605 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005606}