blob: de93adb6be1c8a85ffebc2ae130c01075f3cf6fd [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
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redl2b916b82012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
Richard Smith30ae1ed2013-05-05 16:40:13 +000085/// Update the type of a string literal, including any surrounding parentheses,
86/// to match the type of the object which it is initializing.
87static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smith27f9cf32013-05-06 00:35:47 +000088 while (true) {
Richard Smith30ae1ed2013-05-05 16:40:13 +000089 E->setType(Ty);
Richard Smith27f9cf32013-05-06 00:35:47 +000090 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
91 break;
92 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
93 E = PE->getSubExpr();
94 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
95 E = UO->getSubExpr();
96 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
97 E = GSE->getResultExpr();
98 else
99 llvm_unreachable("unexpected expr in string literal init");
Richard Smith30ae1ed2013-05-05 16:40:13 +0000100 }
Richard Smith30ae1ed2013-05-05 16:40:13 +0000101}
102
John McCallfef8b342011-02-21 07:57:55 +0000103static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
104 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000105 // Get the length of the string as parsed.
106 uint64_t StrLength =
107 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
108
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000110 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000111 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000112 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +0000113 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000114 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000115 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
116 ConstVal,
117 ArrayType::Normal, 0);
Richard Smith30ae1ed2013-05-05 16:40:13 +0000118 updateStringLiteralType(Str, DeclT);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000119 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000120 }
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Eli Friedman8718a6a2009-05-29 18:22:49 +0000122 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000124 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000125 // the size may be smaller or larger than the string we are initializing.
126 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000127 if (S.getLangOpts().CPlusPlus) {
Richard Smith30ae1ed2013-05-05 16:40:13 +0000128 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000129 // For Pascal strings it's OK to strip off the terminating null character,
130 // so the example below is valid:
131 //
132 // unsigned char a[2] = "\pa";
133 if (SL->isPascal())
134 StrLength--;
135 }
136
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000137 // [dcl.init.string]p2
138 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000139 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000140 diag::err_initializer_string_for_char_array_too_long)
141 << Str->getSourceRange();
142 } else {
143 // C99 6.7.8p14.
144 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000145 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000146 diag::warn_initializer_string_for_char_array_too_long)
147 << Str->getSourceRange();
148 }
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Eli Friedman8718a6a2009-05-29 18:22:49 +0000150 // Set the type to the actual size that we are initializing. If we have
151 // something like:
152 // char x[1] = "foo";
153 // then this will set the string literal's type to char[1].
Richard Smith30ae1ed2013-05-05 16:40:13 +0000154 updateStringLiteralType(Str, DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000155}
156
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000157//===----------------------------------------------------------------------===//
158// Semantic checking for initializer lists.
159//===----------------------------------------------------------------------===//
160
Douglas Gregor9e80f722009-01-29 01:05:33 +0000161/// @brief Semantic checking for initializer lists.
162///
163/// The InitListChecker class contains a set of routines that each
164/// handle the initialization of a certain kind of entity, e.g.,
165/// arrays, vectors, struct/union types, scalars, etc. The
166/// InitListChecker itself performs a recursive walk of the subobject
167/// structure of the type to be initialized, while stepping through
168/// the initializer list one element at a time. The IList and Index
169/// parameters to each of the Check* routines contain the active
170/// (syntactic) initializer list and the index into that initializer
171/// list that represents the current initializer. Each routine is
172/// responsible for moving that Index forward as it consumes elements.
173///
174/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000175/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000176/// initializer list and the index into that initializer list where we
177/// are copying initializers as we map them over to the semantic
178/// list. Once we have completed our recursive walk of the subobject
179/// structure, we will have constructed a full semantic initializer
180/// list.
181///
182/// C99 designators cause changes in the initializer list traversal,
183/// because they make the initialization "jump" into a specific
184/// subobject and then continue the initialization from that
185/// point. CheckDesignatedInitializer() recursively steps into the
186/// designated subobject and manages backing out the recursion to
187/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000188namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000189class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000190 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000191 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000192 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000193 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000194 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000195 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000197 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000198 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000199 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000200 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000201 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000202 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000203 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000204 unsigned &StructuredIndex,
205 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000206 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000207 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000208 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000209 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000210 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000211 unsigned &StructuredIndex,
212 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000213 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000214 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000215 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000218 void CheckComplexType(const InitializedEntity &Entity,
219 InitListExpr *IList, QualType DeclType,
220 unsigned &Index,
221 InitListExpr *StructuredList,
222 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000223 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000224 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000225 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000226 InitListExpr *StructuredList,
227 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000228 void CheckReferenceType(const InitializedEntity &Entity,
229 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000230 unsigned &Index,
231 InitListExpr *StructuredList,
232 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000233 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000234 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000235 InitListExpr *StructuredList,
236 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000237 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000238 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000239 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000241 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000242 unsigned &StructuredIndex,
243 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000244 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000245 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000246 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000247 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 InitListExpr *StructuredList,
249 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000250 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000251 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000252 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000253 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000254 RecordDecl::field_iterator *NextField,
255 llvm::APSInt *NextElementIndex,
256 unsigned &Index,
257 InitListExpr *StructuredList,
258 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000259 bool FinishSubobjectInit,
260 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000261 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
262 QualType CurrentObjectType,
263 InitListExpr *StructuredList,
264 unsigned StructuredIndex,
265 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000266 void UpdateStructuredListElement(InitListExpr *StructuredList,
267 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000268 Expr *expr);
269 int numArrayElements(QualType DeclType);
270 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000271
Douglas Gregord6d37de2009-12-22 00:05:34 +0000272 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
273 const InitializedEntity &ParentEntity,
274 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000275 void FillInValueInitializations(const InitializedEntity &Entity,
276 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000277 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
278 Expr *InitExpr, FieldDecl *Field,
279 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000280 void CheckValueInitializable(const InitializedEntity &Entity);
281
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000282public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000283 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000284 InitListExpr *IL, QualType &T, bool VerifyOnly,
285 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000286 bool HadError() { return hadError; }
287
288 // @brief Retrieves the fully-structured initializer list used for
289 // semantic analysis and code generation.
290 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
291};
Chris Lattner8b419b92009-02-24 22:48:58 +0000292} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000293
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000294void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
295 assert(VerifyOnly &&
296 "CheckValueInitializable is only inteded for verification mode.");
297
298 SourceLocation Loc;
299 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
300 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000301 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000302 if (InitSeq.Failed())
303 hadError = true;
304}
305
Douglas Gregord6d37de2009-12-22 00:05:34 +0000306void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
307 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000308 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000309 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000310 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000311 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000312 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000313 = InitializedEntity::InitializeMember(Field, &ParentEntity);
314 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000315 // If there's no explicit initializer but we have a default initializer, use
316 // that. This only happens in C++1y, since classes with default
317 // initializers are not aggregates in C++11.
318 if (Field->hasInClassInitializer()) {
319 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
320 ILE->getRBraceLoc(), Field);
321 if (Init < NumInits)
322 ILE->setInit(Init, DIE);
323 else {
324 ILE->updateInit(SemaRef.Context, Init, DIE);
325 RequiresSecondPass = true;
326 }
327 return;
328 }
329
Douglas Gregord6d37de2009-12-22 00:05:34 +0000330 // FIXME: We probably don't need to handle references
331 // specially here, since value-initialization of references is
332 // handled in InitializationSequence.
333 if (Field->getType()->isReferenceType()) {
334 // C++ [dcl.init.aggr]p9:
335 // If an incomplete or empty initializer-list leaves a
336 // member of reference type uninitialized, the program is
337 // ill-formed.
338 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
339 << Field->getType()
340 << ILE->getSyntacticForm()->getSourceRange();
341 SemaRef.Diag(Field->getLocation(),
342 diag::note_uninit_reference_member);
343 hadError = true;
344 return;
345 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000346
Douglas Gregord6d37de2009-12-22 00:05:34 +0000347 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
348 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000349 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000350 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000351 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000352 hadError = true;
353 return;
354 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355
John McCall60d7b3a2010-08-24 06:29:42 +0000356 ExprResult MemberInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000357 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000358 if (MemberInit.isInvalid()) {
359 hadError = true;
360 return;
361 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362
Douglas Gregord6d37de2009-12-22 00:05:34 +0000363 if (hadError) {
364 // Do nothing
365 } else if (Init < NumInits) {
366 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000367 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000368 // Value-initialization requires a constructor call, so
369 // extend the initializer list to include the constructor
370 // call and make a note that we'll need to take another pass
371 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000372 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000373 RequiresSecondPass = true;
374 }
375 } else if (InitListExpr *InnerILE
376 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000377 FillInValueInitializations(MemberEntity, InnerILE,
378 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000379}
380
Douglas Gregor4c678342009-01-28 21:54:33 +0000381/// Recursively replaces NULL values within the given initializer list
382/// with expressions that perform value-initialization of the
383/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000385InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
386 InitListExpr *ILE,
387 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000388 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000389 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000390 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000391 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000392 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Ted Kremenek6217b802009-07-29 21:53:49 +0000394 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000395 const RecordDecl *RDecl = RType->getDecl();
396 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000397 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
398 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000399 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
400 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
401 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
402 FieldEnd = RDecl->field_end();
403 Field != FieldEnd; ++Field) {
404 if (Field->hasInClassInitializer()) {
405 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
406 break;
407 }
408 }
409 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000410 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000411 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
412 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000413 Field != FieldEnd; ++Field) {
414 if (Field->isUnnamedBitfield())
415 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000416
Douglas Gregord6d37de2009-12-22 00:05:34 +0000417 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000418 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000419
David Blaikie581deb32012-06-06 20:45:41 +0000420 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000421 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000422 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000423
Douglas Gregord6d37de2009-12-22 00:05:34 +0000424 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000425
Douglas Gregord6d37de2009-12-22 00:05:34 +0000426 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000427 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000428 break;
429 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000430 }
431
432 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000433 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000434
435 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000437 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000438 unsigned NumInits = ILE->getNumInits();
439 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000440 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000441 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000442 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
443 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000444 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000445 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000446 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000447 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000448 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000449 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000450 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000451 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000452 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000453
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000454
Douglas Gregor87fd7032009-02-02 17:43:21 +0000455 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000456 if (hadError)
457 return;
458
Anders Carlssond3d824d2010-01-23 04:34:47 +0000459 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
460 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000461 ElementEntity.setElementIndex(Init);
462
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000463 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
464 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000465 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
466 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000467 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000468 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000469 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000470 hadError = true;
471 return;
472 }
473
John McCall60d7b3a2010-08-24 06:29:42 +0000474 ExprResult ElementInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000475 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000476 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000477 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000478 return;
479 }
480
481 if (hadError) {
482 // Do nothing
483 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000484 // For arrays, just set the expression used for value-initialization
485 // of the "holes" in the array.
486 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
487 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
488 else
489 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000490 } else {
491 // For arrays, just set the expression used for value-initialization
492 // of the rest of elements and exit.
493 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
494 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
495 return;
496 }
497
Sebastian Redl7491c492011-06-05 13:59:11 +0000498 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000499 // Value-initialization requires a constructor call, so
500 // extend the initializer list to include the constructor
501 // call and make a note that we'll need to take another pass
502 // through the initializer list.
503 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
504 RequiresSecondPass = true;
505 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000506 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000507 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000508 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000509 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000510 }
511}
512
Chris Lattner68355a52009-01-29 05:10:57 +0000513
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000514InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000515 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000516 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000517 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000518 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000519
Eli Friedmanb85f7072008-05-19 19:16:24 +0000520 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000522 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000523 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000525 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000526 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000527
Sebastian Redl14b0c192011-09-24 17:48:00 +0000528 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000529 bool RequiresSecondPass = false;
530 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000531 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000532 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000533 RequiresSecondPass);
534 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000535}
536
537int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000538 // FIXME: use a proper constant
539 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000540 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000541 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000542 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
543 }
544 return maxElements;
545}
546
547int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000548 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000549 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000550 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000551 Field = structDecl->field_begin(),
552 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000553 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000554 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000555 ++InitializableMembers;
556 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000557 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000558 return std::min(InitializableMembers, 1);
559 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000560}
561
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000562void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000563 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000564 QualType T, unsigned &Index,
565 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000566 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000567 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Steve Naroff0cca7492008-05-01 22:18:59 +0000569 if (T->isArrayType())
570 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000571 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000572 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000573 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000574 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000575 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000576 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000577
Eli Friedman402256f2008-05-25 13:49:22 +0000578 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000579 if (!VerifyOnly)
580 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
581 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000582 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000583 hadError = true;
584 return;
585 }
586
Douglas Gregor4c678342009-01-28 21:54:33 +0000587 // Build a structured initializer list corresponding to this subobject.
588 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000589 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
590 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000591 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000592 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000593 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000594
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000596 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000598 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000599 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000600 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000601
602 if (VerifyOnly) {
603 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
604 hadError = true;
605 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000606 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000607
Sebastian Redlc2235182011-10-16 18:19:28 +0000608 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000609 // Update the structured sub-object initializer so that it's ending
610 // range corresponds with the end of the last initializer it used.
611 if (EndIndex < ParentIList->getNumInits()) {
612 SourceLocation EndLoc
613 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
614 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
615 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000616
Sebastian Redlc2235182011-10-16 18:19:28 +0000617 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000618 if (T->isArrayType() || T->isRecordType()) {
619 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000620 AllowBraceElision ? diag::warn_missing_braces :
621 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000622 << StructuredSubobjectInitList->getSourceRange()
623 << FixItHint::CreateInsertion(
624 StructuredSubobjectInitList->getLocStart(), "{")
625 << FixItHint::CreateInsertion(
626 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000627 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000628 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000629 if (!AllowBraceElision)
630 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000631 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000632 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000633}
634
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000635void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000636 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000637 unsigned &Index,
638 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 unsigned &StructuredIndex,
640 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000641 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000642 if (!VerifyOnly) {
643 SyntacticToSemantic[IList] = StructuredList;
644 StructuredList->setSyntacticForm(IList);
645 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000646 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000647 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000648 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000649 QualType ExprTy = T;
650 if (!ExprTy->isArrayType())
651 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000652 IList->setType(ExprTy);
653 StructuredList->setType(ExprTy);
654 }
Eli Friedman638e1442008-05-25 13:22:35 +0000655 if (hadError)
656 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000657
Eli Friedman638e1442008-05-25 13:22:35 +0000658 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000659 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000660 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000661 if (SemaRef.getLangOpts().CPlusPlus ||
662 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000663 IList->getType()->isVectorType())) {
664 hadError = true;
665 }
666 return;
667 }
668
Eli Friedmane5408582009-05-29 20:20:05 +0000669 if (StructuredIndex == 1 &&
670 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000671 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000672 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000673 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000674 hadError = true;
675 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000676 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000677 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000678 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000679 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000680 // Don't complain for incomplete types, since we'll get an error
681 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000682 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000683 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000684 CurrentObjectType->isArrayType()? 0 :
685 CurrentObjectType->isVectorType()? 1 :
686 CurrentObjectType->isScalarType()? 2 :
687 CurrentObjectType->isUnionType()? 3 :
688 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000689
690 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000691 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000692 DK = diag::err_excess_initializers;
693 hadError = true;
694 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000695 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000696 DK = diag::err_excess_initializers;
697 hadError = true;
698 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000699
Chris Lattner08202542009-02-24 22:50:46 +0000700 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000701 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000702 }
703 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000704
Sebastian Redl14b0c192011-09-24 17:48:00 +0000705 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
706 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000707 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000708 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000709 << FixItHint::CreateRemoval(IList->getLocStart())
710 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000711}
712
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000713void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000714 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000715 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000716 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000717 unsigned &Index,
718 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000719 unsigned &StructuredIndex,
720 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000721 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
722 // Explicitly braced initializer for complex type can be real+imaginary
723 // parts.
724 CheckComplexType(Entity, IList, DeclType, Index,
725 StructuredList, StructuredIndex);
726 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000727 CheckScalarType(Entity, IList, DeclType, Index,
728 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000729 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000730 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000731 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000732 } else if (DeclType->isRecordType()) {
733 assert(DeclType->isAggregateType() &&
734 "non-aggregate records should be handed in CheckSubElementType");
735 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
736 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
737 SubobjectIsDesignatorContext, Index,
738 StructuredList, StructuredIndex,
739 TopLevelObject);
740 } else if (DeclType->isArrayType()) {
741 llvm::APSInt Zero(
742 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
743 false);
744 CheckArrayType(Entity, IList, DeclType, Zero,
745 SubobjectIsDesignatorContext, Index,
746 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000747 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
748 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000749 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000750 if (!VerifyOnly)
751 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
752 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000753 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000754 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000755 CheckReferenceType(Entity, IList, DeclType, Index,
756 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000757 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000758 if (!VerifyOnly)
759 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
760 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000761 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000762 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000763 if (!VerifyOnly)
764 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
765 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000766 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000767 }
768}
769
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000770void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000771 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000772 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000773 unsigned &Index,
774 InitListExpr *StructuredList,
775 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000776 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000777 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000778 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
779 unsigned newIndex = 0;
780 unsigned newStructuredIndex = 0;
781 InitListExpr *newStructuredList
782 = getStructuredSubobjectInit(IList, Index, ElemType,
783 StructuredList, StructuredIndex,
784 SubInitList->getSourceRange());
785 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
786 newStructuredList, newStructuredIndex);
787 ++StructuredIndex;
788 ++Index;
789 return;
790 }
791 assert(SemaRef.getLangOpts().CPlusPlus &&
792 "non-aggregate records are only possible in C++");
793 // C++ initialization is handled later.
794 }
795
796 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000797 return CheckScalarType(Entity, IList, ElemType, Index,
798 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000799 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000800 return CheckReferenceType(Entity, IList, ElemType, Index,
801 StructuredList, StructuredIndex);
802 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000803
John McCallfef8b342011-02-21 07:57:55 +0000804 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
805 // arrayType can be incomplete if we're initializing a flexible
806 // array member. There's nothing we can do with the completed
807 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000808
John McCallfef8b342011-02-21 07:57:55 +0000809 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000810 if (!VerifyOnly) {
811 CheckStringInit(Str, ElemType, arrayType, SemaRef);
812 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
813 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000814 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000815 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000816 }
John McCallfef8b342011-02-21 07:57:55 +0000817
818 // Fall through for subaggregate initialization.
819
David Blaikie4e4d0842012-03-11 07:00:24 +0000820 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000821 // C++ [dcl.init.aggr]p12:
822 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000823 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000824 // an initializer-list. If the initializer can initialize a
825 // member, the member is initialized. [...]
826
827 // FIXME: Better EqualLoc?
828 InitializationKind Kind =
829 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000830 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000831
832 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000833 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000834 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000835 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000836 if (Result.isInvalid())
837 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000838
Sebastian Redl14b0c192011-09-24 17:48:00 +0000839 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000840 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000841 }
John McCallfef8b342011-02-21 07:57:55 +0000842 ++Index;
843 return;
844 }
845
846 // Fall through for subaggregate initialization
847 } else {
848 // C99 6.7.8p13:
849 //
850 // The initializer for a structure or union object that has
851 // automatic storage duration shall be either an initializer
852 // list as described below, or a single expression that has
853 // compatible structure or union type. In the latter case, the
854 // initial value of the object, including unnamed members, is
855 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000856 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000857 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000858 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
859 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000860 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000861 if (ExprRes.isInvalid())
862 hadError = true;
863 else {
864 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000865 if (ExprRes.isInvalid())
866 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000867 }
868 UpdateStructuredListElement(StructuredList, StructuredIndex,
869 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000870 ++Index;
871 return;
872 }
John Wiegley429bb272011-04-08 18:41:53 +0000873 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000874 // Fall through for subaggregate initialization
875 }
876
877 // C++ [dcl.init.aggr]p12:
878 //
879 // [...] Otherwise, if the member is itself a non-empty
880 // subaggregate, brace elision is assumed and the initializer is
881 // considered for the initialization of the first member of
882 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000883 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000884 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000885 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
886 StructuredIndex);
887 ++StructuredIndex;
888 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000889 if (!VerifyOnly) {
890 // We cannot initialize this element, so let
891 // PerformCopyInitialization produce the appropriate diagnostic.
892 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
893 SemaRef.Owned(expr),
894 /*TopLevelOfInitList=*/true);
895 }
John McCallfef8b342011-02-21 07:57:55 +0000896 hadError = true;
897 ++Index;
898 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000899 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000900}
901
Eli Friedman0c706c22011-09-19 23:17:44 +0000902void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
903 InitListExpr *IList, QualType DeclType,
904 unsigned &Index,
905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
907 assert(Index == 0 && "Index in explicit init list must be zero");
908
909 // As an extension, clang supports complex initializers, which initialize
910 // a complex number component-wise. When an explicit initializer list for
911 // a complex number contains two two initializers, this extension kicks in:
912 // it exepcts the initializer list to contain two elements convertible to
913 // the element type of the complex type. The first element initializes
914 // the real part, and the second element intitializes the imaginary part.
915
916 if (IList->getNumInits() != 2)
917 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
918 StructuredIndex);
919
920 // This is an extension in C. (The builtin _Complex type does not exist
921 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000922 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000923 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
924 << IList->getSourceRange();
925
926 // Initialize the complex number.
927 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
928 InitializedEntity ElementEntity =
929 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
930
931 for (unsigned i = 0; i < 2; ++i) {
932 ElementEntity.setElementIndex(Index);
933 CheckSubElementType(ElementEntity, IList, elementType, Index,
934 StructuredList, StructuredIndex);
935 }
936}
937
938
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000939void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000940 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000941 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000942 InitListExpr *StructuredList,
943 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000944 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000945 if (!VerifyOnly)
946 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000947 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000948 diag::warn_cxx98_compat_empty_scalar_initializer :
949 diag::err_empty_scalar_initializer)
950 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000951 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000952 ++Index;
953 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000954 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000955 }
John McCallb934c2d2010-11-11 00:46:36 +0000956
957 Expr *expr = IList->getInit(Index);
958 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000959 if (!VerifyOnly)
960 SemaRef.Diag(SubIList->getLocStart(),
961 diag::warn_many_braces_around_scalar_init)
962 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000963
964 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
965 StructuredIndex);
966 return;
967 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000968 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000969 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000970 diag::err_designator_for_scalar_init)
971 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000972 hadError = true;
973 ++Index;
974 ++StructuredIndex;
975 return;
976 }
977
Sebastian Redl14b0c192011-09-24 17:48:00 +0000978 if (VerifyOnly) {
979 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
980 hadError = true;
981 ++Index;
982 return;
983 }
984
John McCallb934c2d2010-11-11 00:46:36 +0000985 ExprResult Result =
986 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000987 SemaRef.Owned(expr),
988 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000989
990 Expr *ResultExpr = 0;
991
992 if (Result.isInvalid())
993 hadError = true; // types weren't compatible.
994 else {
995 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996
John McCallb934c2d2010-11-11 00:46:36 +0000997 if (ResultExpr != expr) {
998 // The type was promoted, update initializer list.
999 IList->setInit(Index, ResultExpr);
1000 }
1001 }
1002 if (hadError)
1003 ++StructuredIndex;
1004 else
1005 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1006 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001007}
1008
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001009void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1010 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001011 unsigned &Index,
1012 InitListExpr *StructuredList,
1013 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001014 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001015 // FIXME: It would be wonderful if we could point at the actual member. In
1016 // general, it would be useful to pass location information down the stack,
1017 // so that we know the location (or decl) of the "current object" being
1018 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001019 if (!VerifyOnly)
1020 SemaRef.Diag(IList->getLocStart(),
1021 diag::err_init_reference_member_uninitialized)
1022 << DeclType
1023 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001024 hadError = true;
1025 ++Index;
1026 ++StructuredIndex;
1027 return;
1028 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001029
1030 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001031 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001032 if (!VerifyOnly)
1033 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1034 << DeclType << IList->getSourceRange();
1035 hadError = true;
1036 ++Index;
1037 ++StructuredIndex;
1038 return;
1039 }
1040
1041 if (VerifyOnly) {
1042 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1043 hadError = true;
1044 ++Index;
1045 return;
1046 }
1047
1048 ExprResult Result =
1049 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1050 SemaRef.Owned(expr),
1051 /*TopLevelOfInitList=*/true);
1052
1053 if (Result.isInvalid())
1054 hadError = true;
1055
1056 expr = Result.takeAs<Expr>();
1057 IList->setInit(Index, expr);
1058
1059 if (hadError)
1060 ++StructuredIndex;
1061 else
1062 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1063 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001064}
1065
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001066void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001067 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001068 unsigned &Index,
1069 InitListExpr *StructuredList,
1070 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001071 const VectorType *VT = DeclType->getAs<VectorType>();
1072 unsigned maxElements = VT->getNumElements();
1073 unsigned numEltsInit = 0;
1074 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001075
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001076 if (Index >= IList->getNumInits()) {
1077 // Make sure the element type can be value-initialized.
1078 if (VerifyOnly)
1079 CheckValueInitializable(
1080 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1081 return;
1082 }
1083
David Blaikie4e4d0842012-03-11 07:00:24 +00001084 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001085 // If the initializing element is a vector, try to copy-initialize
1086 // instead of breaking it apart (which is doomed to failure anyway).
1087 Expr *Init = IList->getInit(Index);
1088 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001089 if (VerifyOnly) {
1090 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1091 hadError = true;
1092 ++Index;
1093 return;
1094 }
1095
John McCall20e047a2010-10-30 00:11:39 +00001096 ExprResult Result =
1097 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001098 SemaRef.Owned(Init),
1099 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001100
1101 Expr *ResultExpr = 0;
1102 if (Result.isInvalid())
1103 hadError = true; // types weren't compatible.
1104 else {
1105 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001106
John McCall20e047a2010-10-30 00:11:39 +00001107 if (ResultExpr != Init) {
1108 // The type was promoted, update initializer list.
1109 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001110 }
1111 }
John McCall20e047a2010-10-30 00:11:39 +00001112 if (hadError)
1113 ++StructuredIndex;
1114 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001115 UpdateStructuredListElement(StructuredList, StructuredIndex,
1116 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001117 ++Index;
1118 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001119 }
Mike Stump1eb44332009-09-09 15:08:12 +00001120
John McCall20e047a2010-10-30 00:11:39 +00001121 InitializedEntity ElementEntity =
1122 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001123
John McCall20e047a2010-10-30 00:11:39 +00001124 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1125 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001126 if (Index >= IList->getNumInits()) {
1127 if (VerifyOnly)
1128 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001129 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001131
John McCall20e047a2010-10-30 00:11:39 +00001132 ElementEntity.setElementIndex(Index);
1133 CheckSubElementType(ElementEntity, IList, elementType, Index,
1134 StructuredList, StructuredIndex);
1135 }
1136 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001137 }
John McCall20e047a2010-10-30 00:11:39 +00001138
1139 InitializedEntity ElementEntity =
1140 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001141
John McCall20e047a2010-10-30 00:11:39 +00001142 // OpenCL initializers allows vectors to be constructed from vectors.
1143 for (unsigned i = 0; i < maxElements; ++i) {
1144 // Don't attempt to go past the end of the init list
1145 if (Index >= IList->getNumInits())
1146 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001147
John McCall20e047a2010-10-30 00:11:39 +00001148 ElementEntity.setElementIndex(Index);
1149
1150 QualType IType = IList->getInit(Index)->getType();
1151 if (!IType->isVectorType()) {
1152 CheckSubElementType(ElementEntity, IList, elementType, Index,
1153 StructuredList, StructuredIndex);
1154 ++numEltsInit;
1155 } else {
1156 QualType VecType;
1157 const VectorType *IVT = IType->getAs<VectorType>();
1158 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001159
John McCall20e047a2010-10-30 00:11:39 +00001160 if (IType->isExtVectorType())
1161 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1162 else
1163 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001164 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001165 CheckSubElementType(ElementEntity, IList, VecType, Index,
1166 StructuredList, StructuredIndex);
1167 numEltsInit += numIElts;
1168 }
1169 }
1170
1171 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001172 if (numEltsInit != maxElements) {
1173 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001174 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001175 diag::err_vector_incorrect_num_initializers)
1176 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1177 hadError = true;
1178 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001179}
1180
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001181void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001182 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001183 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001184 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001185 unsigned &Index,
1186 InitListExpr *StructuredList,
1187 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001188 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1189
Steve Naroff0cca7492008-05-01 22:18:59 +00001190 // Check for the special-case of initializing an array with a string.
1191 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001192 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001193 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001194 // We place the string literal directly into the resulting
1195 // initializer list. This is the only place where the structure
1196 // of the structured initializer list doesn't match exactly,
1197 // because doing so would involve allocating one character
1198 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001199 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001200 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001201 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1202 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1203 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001204 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001205 return;
1206 }
1207 }
John McCallce6c9b72011-02-21 07:22:22 +00001208 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001209 // Check for VLAs; in standard C it would be possible to check this
1210 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1211 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001212 if (!VerifyOnly)
1213 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1214 diag::err_variable_object_no_init)
1215 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001216 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001217 ++Index;
1218 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001219 return;
1220 }
1221
Douglas Gregor05c13a32009-01-22 00:58:24 +00001222 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001223 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1224 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001225 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001226 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001227 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001228 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001229 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001230 maxElementsKnown = true;
1231 }
1232
John McCallce6c9b72011-02-21 07:22:22 +00001233 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001234 while (Index < IList->getNumInits()) {
1235 Expr *Init = IList->getInit(Index);
1236 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001237 // If we're not the subobject that matches up with the '{' for
1238 // the designator, we shouldn't be handling the
1239 // designator. Return immediately.
1240 if (!SubobjectIsDesignatorContext)
1241 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001242
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001243 // Handle this designated initializer. elementIndex will be
1244 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001245 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001246 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001247 StructuredList, StructuredIndex, true,
1248 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001249 hadError = true;
1250 continue;
1251 }
1252
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001253 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001254 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001255 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001256 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001257 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001258
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001259 // If the array is of incomplete type, keep track of the number of
1260 // elements in the initializer.
1261 if (!maxElementsKnown && elementIndex > maxElements)
1262 maxElements = elementIndex;
1263
Douglas Gregor05c13a32009-01-22 00:58:24 +00001264 continue;
1265 }
1266
1267 // If we know the maximum number of elements, and we've already
1268 // hit it, stop consuming elements in the initializer list.
1269 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001270 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001272 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001273 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001274 Entity);
1275 // Check this element.
1276 CheckSubElementType(ElementEntity, IList, elementType, Index,
1277 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001278 ++elementIndex;
1279
1280 // If the array is of incomplete type, keep track of the number of
1281 // elements in the initializer.
1282 if (!maxElementsKnown && elementIndex > maxElements)
1283 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001284 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001285 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001286 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001287 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001288 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001289 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001290 // Sizing an array implicitly to zero is not allowed by ISO C,
1291 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001292 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001293 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001294 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001295
Mike Stump1eb44332009-09-09 15:08:12 +00001296 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001297 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001298 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001299 if (!hadError && VerifyOnly) {
1300 // Check if there are any members of the array that get value-initialized.
1301 // If so, check if doing that is possible.
1302 // FIXME: This needs to detect holes left by designated initializers too.
1303 if (maxElementsKnown && elementIndex < maxElements)
1304 CheckValueInitializable(InitializedEntity::InitializeElement(
1305 SemaRef.Context, 0, Entity));
1306 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001307}
1308
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001309bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1310 Expr *InitExpr,
1311 FieldDecl *Field,
1312 bool TopLevelObject) {
1313 // Handle GNU flexible array initializers.
1314 unsigned FlexArrayDiag;
1315 if (isa<InitListExpr>(InitExpr) &&
1316 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1317 // Empty flexible array init always allowed as an extension
1318 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001319 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001320 // Disallow flexible array init in C++; it is not required for gcc
1321 // compatibility, and it needs work to IRGen correctly in general.
1322 FlexArrayDiag = diag::err_flexible_array_init;
1323 } else if (!TopLevelObject) {
1324 // Disallow flexible array init on non-top-level object
1325 FlexArrayDiag = diag::err_flexible_array_init;
1326 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1327 // Disallow flexible array init on anything which is not a variable.
1328 FlexArrayDiag = diag::err_flexible_array_init;
1329 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1330 // Disallow flexible array init on local variables.
1331 FlexArrayDiag = diag::err_flexible_array_init;
1332 } else {
1333 // Allow other cases.
1334 FlexArrayDiag = diag::ext_flexible_array_init;
1335 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001336
1337 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001338 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001339 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001340 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001341 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1342 << Field;
1343 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001344
1345 return FlexArrayDiag != diag::ext_flexible_array_init;
1346}
1347
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001348void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001349 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001350 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001351 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001352 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001353 unsigned &Index,
1354 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001355 unsigned &StructuredIndex,
1356 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001357 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Eli Friedmanb85f7072008-05-19 19:16:24 +00001359 // If the record is invalid, some of it's members are invalid. To avoid
1360 // confusion, we forgo checking the intializer for the entire record.
1361 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001362 // Assume it was supposed to consume a single initializer.
1363 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001364 hadError = true;
1365 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001366 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001367
1368 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001369 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001370
1371 // If there's a default initializer, use it.
1372 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1373 if (VerifyOnly)
1374 return;
1375 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1376 Field != FieldEnd; ++Field) {
1377 if (Field->hasInClassInitializer()) {
1378 StructuredList->setInitializedFieldInUnion(*Field);
1379 // FIXME: Actually build a CXXDefaultInitExpr?
1380 return;
1381 }
1382 }
1383 }
1384
1385 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001386 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1387 Field != FieldEnd; ++Field) {
1388 if (Field->getDeclName()) {
1389 if (VerifyOnly)
1390 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001391 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001392 else
David Blaikie581deb32012-06-06 20:45:41 +00001393 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001394 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001395 }
1396 }
1397 return;
1398 }
1399
Douglas Gregor05c13a32009-01-22 00:58:24 +00001400 // If structDecl is a forward declaration, this loop won't do
1401 // anything except look at designated initializers; That's okay,
1402 // because an error should get printed out elsewhere. It might be
1403 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001404 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001405 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001406 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001407 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001408 while (Index < IList->getNumInits()) {
1409 Expr *Init = IList->getInit(Index);
1410
1411 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001412 // If we're not the subobject that matches up with the '{' for
1413 // the designator, we shouldn't be handling the
1414 // designator. Return immediately.
1415 if (!SubobjectIsDesignatorContext)
1416 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001417
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001418 // Handle this designated initializer. Field will be updated to
1419 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001420 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001421 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001422 StructuredList, StructuredIndex,
1423 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001424 hadError = true;
1425
Douglas Gregordfb5e592009-02-12 19:00:39 +00001426 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001427
1428 // Disable check for missing fields when designators are used.
1429 // This matches gcc behaviour.
1430 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001431 continue;
1432 }
1433
1434 if (Field == FieldEnd) {
1435 // We've run out of fields. We're done.
1436 break;
1437 }
1438
Douglas Gregordfb5e592009-02-12 19:00:39 +00001439 // We've already initialized a member of a union. We're done.
1440 if (InitializedSomething && DeclType->isUnionType())
1441 break;
1442
Douglas Gregor44b43212008-12-11 16:49:14 +00001443 // If we've hit the flexible array member at the end, we're done.
1444 if (Field->getType()->isIncompleteArrayType())
1445 break;
1446
Douglas Gregor0bb76892009-01-29 16:53:55 +00001447 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001448 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001449 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001450 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001451 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001452
Douglas Gregor54001c12011-06-29 21:51:31 +00001453 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001454 bool InvalidUse;
1455 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001456 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001457 else
David Blaikie581deb32012-06-06 20:45:41 +00001458 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001459 IList->getInit(Index)->getLocStart());
1460 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001461 ++Index;
1462 ++Field;
1463 hadError = true;
1464 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001465 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001466
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001467 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001468 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001469 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1470 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001471 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001472
Sebastian Redl14b0c192011-09-24 17:48:00 +00001473 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001474 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001475 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001476 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001477
1478 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001479 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001480
John McCall80639de2010-03-11 19:32:38 +00001481 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001482 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1483 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1484 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001485 // It is possible we have one or more unnamed bitfields remaining.
1486 // Find first (if any) named field and emit warning.
1487 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1488 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001489 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001490 SemaRef.Diag(IList->getSourceRange().getEnd(),
1491 diag::warn_missing_field_initializers) << it->getName();
1492 break;
1493 }
1494 }
1495 }
1496
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001497 // Check that any remaining fields can be value-initialized.
1498 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1499 !Field->getType()->isIncompleteArrayType()) {
1500 // FIXME: Should check for holes left by designated initializers too.
1501 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001502 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001503 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001504 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001505 }
1506 }
1507
Mike Stump1eb44332009-09-09 15:08:12 +00001508 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001509 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001510 return;
1511
David Blaikie581deb32012-06-06 20:45:41 +00001512 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001513 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001514 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001515 ++Index;
1516 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001517 }
1518
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001519 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001520 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001521
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001522 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001523 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001524 StructuredList, StructuredIndex);
1525 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001526 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001527 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001528}
Steve Naroff0cca7492008-05-01 22:18:59 +00001529
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001530/// \brief Expand a field designator that refers to a member of an
1531/// anonymous struct or union into a series of field designators that
1532/// refers to the field within the appropriate subobject.
1533///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001534static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001535 DesignatedInitExpr *DIE,
1536 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001537 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001538 typedef DesignatedInitExpr::Designator Designator;
1539
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001540 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001541 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001542 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1543 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1544 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001545 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001546 DIE->getDesignator(DesigIdx)->getDotLoc(),
1547 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1548 else
1549 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1550 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001551 assert(isa<FieldDecl>(*PI));
1552 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001553 }
1554
1555 // Expand the current designator into the set of replacement
1556 // designators, so we have a full subobject path down to where the
1557 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001558 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001559 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001560}
Mike Stump1eb44332009-09-09 15:08:12 +00001561
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001562/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001563/// corresponds to FieldName.
1564static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1565 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001566 if (!FieldName)
1567 return 0;
1568
Francois Picheta0e27f02010-12-22 03:46:10 +00001569 assert(AnonField->isAnonymousStructOrUnion());
1570 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001571 while (IndirectFieldDecl *IF =
1572 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001573 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001574 return IF;
1575 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001576 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001577 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001578}
1579
Sebastian Redl14b0c192011-09-24 17:48:00 +00001580static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1581 DesignatedInitExpr *DIE) {
1582 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1583 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1584 for (unsigned I = 0; I < NumIndexExprs; ++I)
1585 IndexExprs[I] = DIE->getSubExpr(I + 1);
1586 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001587 DIE->size(), IndexExprs,
1588 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001589 DIE->usesGNUSyntax(), DIE->getInit());
1590}
1591
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001592namespace {
1593
1594// Callback to only accept typo corrections that are for field members of
1595// the given struct or union.
1596class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1597 public:
1598 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1599 : Record(RD) {}
1600
1601 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1602 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1603 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1604 }
1605
1606 private:
1607 RecordDecl *Record;
1608};
1609
1610}
1611
Douglas Gregor05c13a32009-01-22 00:58:24 +00001612/// @brief Check the well-formedness of a C99 designated initializer.
1613///
1614/// Determines whether the designated initializer @p DIE, which
1615/// resides at the given @p Index within the initializer list @p
1616/// IList, is well-formed for a current object of type @p DeclType
1617/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001618/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001619/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001620///
1621/// @param IList The initializer list in which this designated
1622/// initializer occurs.
1623///
Douglas Gregor71199712009-04-15 04:56:10 +00001624/// @param DIE The designated initializer expression.
1625///
1626/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001627///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001628/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001629/// into which the designation in @p DIE should refer.
1630///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001631/// @param NextField If non-NULL and the first designator in @p DIE is
1632/// a field, this will be set to the field declaration corresponding
1633/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001634///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001635/// @param NextElementIndex If non-NULL and the first designator in @p
1636/// DIE is an array designator or GNU array-range designator, this
1637/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001638///
1639/// @param Index Index into @p IList where the designated initializer
1640/// @p DIE occurs.
1641///
Douglas Gregor4c678342009-01-28 21:54:33 +00001642/// @param StructuredList The initializer list expression that
1643/// describes all of the subobject initializers in the order they'll
1644/// actually be initialized.
1645///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001646/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001647bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001648InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001649 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001650 DesignatedInitExpr *DIE,
1651 unsigned DesigIdx,
1652 QualType &CurrentObjectType,
1653 RecordDecl::field_iterator *NextField,
1654 llvm::APSInt *NextElementIndex,
1655 unsigned &Index,
1656 InitListExpr *StructuredList,
1657 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001658 bool FinishSubobjectInit,
1659 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001660 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001661 // Check the actual initialization for the designated object type.
1662 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001663
1664 // Temporarily remove the designator expression from the
1665 // initializer list that the child calls see, so that we don't try
1666 // to re-process the designator.
1667 unsigned OldIndex = Index;
1668 IList->setInit(OldIndex, DIE->getInit());
1669
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001670 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001671 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001672
1673 // Restore the designated initializer expression in the syntactic
1674 // form of the initializer list.
1675 if (IList->getInit(OldIndex) != DIE->getInit())
1676 DIE->setInit(IList->getInit(OldIndex));
1677 IList->setInit(OldIndex, DIE);
1678
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001679 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001680 }
1681
Douglas Gregor71199712009-04-15 04:56:10 +00001682 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001683 bool IsFirstDesignator = (DesigIdx == 0);
1684 if (!VerifyOnly) {
1685 assert((IsFirstDesignator || StructuredList) &&
1686 "Need a non-designated initializer list to start from");
1687
1688 // Determine the structural initializer list that corresponds to the
1689 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001690 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001691 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1692 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001693 SourceRange(D->getLocStart(),
1694 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001695 assert(StructuredList && "Expected a structured initializer list");
1696 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001697
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001698 if (D->isFieldDesignator()) {
1699 // C99 6.7.8p7:
1700 //
1701 // If a designator has the form
1702 //
1703 // . identifier
1704 //
1705 // then the current object (defined below) shall have
1706 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001707 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001708 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001709 if (!RT) {
1710 SourceLocation Loc = D->getDotLoc();
1711 if (Loc.isInvalid())
1712 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001713 if (!VerifyOnly)
1714 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001715 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001716 ++Index;
1717 return true;
1718 }
1719
Douglas Gregor4c678342009-01-28 21:54:33 +00001720 // Note: we perform a linear search of the fields here, despite
1721 // the fact that we have a faster lookup method, because we always
1722 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001723 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001724 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001725 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001726 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001727 Field = RT->getDecl()->field_begin(),
1728 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001729 for (; Field != FieldEnd; ++Field) {
1730 if (Field->isUnnamedBitfield())
1731 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001732
Francois Picheta0e27f02010-12-22 03:46:10 +00001733 // If we find a field representing an anonymous field, look in the
1734 // IndirectFieldDecl that follow for the designated initializer.
1735 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1736 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001737 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001738 // In verify mode, don't modify the original.
1739 if (VerifyOnly)
1740 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001741 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1742 D = DIE->getDesignator(DesigIdx);
1743 break;
1744 }
1745 }
David Blaikie581deb32012-06-06 20:45:41 +00001746 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001747 break;
1748 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001749 break;
1750
1751 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001752 }
1753
Douglas Gregor4c678342009-01-28 21:54:33 +00001754 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001755 if (VerifyOnly) {
1756 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001757 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001758 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001759
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001760 // There was no normal field in the struct with the designated
1761 // name. Perform another lookup for this name, which may find
1762 // something that we can't designate (e.g., a member function),
1763 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001764 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001765 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001766 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001767 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001768 // Name lookup didn't find anything. Determine whether this
1769 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001770 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001771 TypoCorrection Corrected = SemaRef.CorrectTypo(
1772 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001773 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001774 RT->getDecl());
1775 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001776 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001777 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001778 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001779 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001780 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001782 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001783 << FieldName << CurrentObjectType << CorrectedQuotedStr
1784 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001786 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001787 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001788 } else {
1789 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1790 << FieldName << CurrentObjectType;
1791 ++Index;
1792 return true;
1793 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001794 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001796 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001798 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001799 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001800 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001801 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001802 ++Index;
1803 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001804 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001805
Francois Picheta0e27f02010-12-22 03:46:10 +00001806 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001807 // The replacement field comes from typo correction; find it
1808 // in the list of fields.
1809 FieldIndex = 0;
1810 Field = RT->getDecl()->field_begin();
1811 for (; Field != FieldEnd; ++Field) {
1812 if (Field->isUnnamedBitfield())
1813 continue;
1814
David Blaikie581deb32012-06-06 20:45:41 +00001815 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001816 Field->getIdentifier() == ReplacementField->getIdentifier())
1817 break;
1818
1819 ++FieldIndex;
1820 }
1821 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001822 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001823
1824 // All of the fields of a union are located at the same place in
1825 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001826 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001827 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001828 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001829 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001830 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001831
Douglas Gregor54001c12011-06-29 21:51:31 +00001832 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001833 bool InvalidUse;
1834 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001835 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001836 else
David Blaikie581deb32012-06-06 20:45:41 +00001837 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001838 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001839 ++Index;
1840 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001841 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001842
Sebastian Redl14b0c192011-09-24 17:48:00 +00001843 if (!VerifyOnly) {
1844 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001845 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Sebastian Redl14b0c192011-09-24 17:48:00 +00001847 // Make sure that our non-designated initializer list has space
1848 // for a subobject corresponding to this field.
1849 if (FieldIndex >= StructuredList->getNumInits())
1850 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1851 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001852
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001853 // This designator names a flexible array member.
1854 if (Field->getType()->isIncompleteArrayType()) {
1855 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001856 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001857 // We can't designate an object within the flexible array
1858 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001859 if (!VerifyOnly) {
1860 DesignatedInitExpr::Designator *NextD
1861 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001862 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001863 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001864 << SourceRange(NextD->getLocStart(),
1865 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001866 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001867 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001868 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001869 Invalid = true;
1870 }
1871
Chris Lattner9046c222010-10-10 17:49:49 +00001872 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1873 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001874 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001875 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001876 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001877 diag::err_flexible_array_init_needs_braces)
1878 << DIE->getInit()->getSourceRange();
1879 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001880 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001881 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001882 Invalid = true;
1883 }
1884
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001885 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001886 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001887 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001888 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001889
1890 if (Invalid) {
1891 ++Index;
1892 return true;
1893 }
1894
1895 // Initialize the array.
1896 bool prevHadError = hadError;
1897 unsigned newStructuredIndex = FieldIndex;
1898 unsigned OldIndex = Index;
1899 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001900
1901 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001902 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001903 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001904 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001905
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001906 IList->setInit(OldIndex, DIE);
1907 if (hadError && !prevHadError) {
1908 ++Field;
1909 ++FieldIndex;
1910 if (NextField)
1911 *NextField = Field;
1912 StructuredIndex = FieldIndex;
1913 return true;
1914 }
1915 } else {
1916 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001917 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001918 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001919
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001920 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001921 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001922 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1923 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001924 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001925 true, false))
1926 return true;
1927 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001928
1929 // Find the position of the next field to be initialized in this
1930 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001931 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001932 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001933
1934 // If this the first designator, our caller will continue checking
1935 // the rest of this struct/class/union subobject.
1936 if (IsFirstDesignator) {
1937 if (NextField)
1938 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001939 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001940 return false;
1941 }
1942
Douglas Gregor34e79462009-01-28 23:36:17 +00001943 if (!FinishSubobjectInit)
1944 return false;
1945
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001946 // We've already initialized something in the union; we're done.
1947 if (RT->getDecl()->isUnion())
1948 return hadError;
1949
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001950 // Check the remaining fields within this class/struct/union subobject.
1951 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001952
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001953 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001954 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001955 return hadError && !prevHadError;
1956 }
1957
1958 // C99 6.7.8p6:
1959 //
1960 // If a designator has the form
1961 //
1962 // [ constant-expression ]
1963 //
1964 // then the current object (defined below) shall have array
1965 // type and the expression shall be an integer constant
1966 // expression. If the array is of unknown size, any
1967 // nonnegative value is valid.
1968 //
1969 // Additionally, cope with the GNU extension that permits
1970 // designators of the form
1971 //
1972 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001973 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001974 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001975 if (!VerifyOnly)
1976 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1977 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001978 ++Index;
1979 return true;
1980 }
1981
1982 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001983 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1984 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001985 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001986 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001987 DesignatedEndIndex = DesignatedStartIndex;
1988 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001989 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001990
Mike Stump1eb44332009-09-09 15:08:12 +00001991 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001992 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001993 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001994 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001995 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001996
Chris Lattnere0fd8322011-02-19 22:28:58 +00001997 // Codegen can't handle evaluating array range designators that have side
1998 // effects, because we replicate the AST value for each initialized element.
1999 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2000 // elements with something that has a side effect, so codegen can emit an
2001 // "error unsupported" error instead of miscompiling the app.
2002 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002003 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002004 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002005 }
2006
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002007 if (isa<ConstantArrayType>(AT)) {
2008 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002009 DesignatedStartIndex
2010 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002011 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002012 DesignatedEndIndex
2013 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002014 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2015 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002016 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002017 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002018 diag::err_array_designator_too_large)
2019 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2020 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002021 ++Index;
2022 return true;
2023 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002024 } else {
2025 // Make sure the bit-widths and signedness match.
2026 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002027 DesignatedEndIndex
2028 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002029 else if (DesignatedStartIndex.getBitWidth() <
2030 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002031 DesignatedStartIndex
2032 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002033 DesignatedStartIndex.setIsUnsigned(true);
2034 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002035 }
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Douglas Gregor4c678342009-01-28 21:54:33 +00002037 // Make sure that our non-designated initializer list has space
2038 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002039 if (!VerifyOnly &&
2040 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002041 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002042 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002043
Douglas Gregor34e79462009-01-28 23:36:17 +00002044 // Repeatedly perform subobject initializations in the range
2045 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002046
Douglas Gregor34e79462009-01-28 23:36:17 +00002047 // Move to the next designator
2048 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2049 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002050
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002051 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002052 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002053
Douglas Gregor34e79462009-01-28 23:36:17 +00002054 while (DesignatedStartIndex <= DesignatedEndIndex) {
2055 // Recurse to check later designated subobjects.
2056 QualType ElementType = AT->getElementType();
2057 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002058
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002059 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002060 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2061 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002062 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002063 (DesignatedStartIndex == DesignatedEndIndex),
2064 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002065 return true;
2066
2067 // Move to the next index in the array that we'll be initializing.
2068 ++DesignatedStartIndex;
2069 ElementIndex = DesignatedStartIndex.getZExtValue();
2070 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002071
2072 // If this the first designator, our caller will continue checking
2073 // the rest of this array subobject.
2074 if (IsFirstDesignator) {
2075 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002076 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002077 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002078 return false;
2079 }
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Douglas Gregor34e79462009-01-28 23:36:17 +00002081 if (!FinishSubobjectInit)
2082 return false;
2083
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002084 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002085 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002086 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002087 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002088 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002089 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002090}
2091
Douglas Gregor4c678342009-01-28 21:54:33 +00002092// Get the structured initializer list for a subobject of type
2093// @p CurrentObjectType.
2094InitListExpr *
2095InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2096 QualType CurrentObjectType,
2097 InitListExpr *StructuredList,
2098 unsigned StructuredIndex,
2099 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002100 if (VerifyOnly)
2101 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002102 Expr *ExistingInit = 0;
2103 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002104 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002105 else if (StructuredIndex < StructuredList->getNumInits())
2106 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Douglas Gregor4c678342009-01-28 21:54:33 +00002108 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2109 return Result;
2110
2111 if (ExistingInit) {
2112 // We are creating an initializer list that initializes the
2113 // subobjects of the current object, but there was already an
2114 // initialization that completely initialized the current
2115 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002116 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002117 // struct X { int a, b; };
2118 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002119 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002120 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2121 // designated initializer re-initializes the whole
2122 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002123 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002124 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002125 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002126 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002127 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002128 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002129 << ExistingInit->getSourceRange();
2130 }
2131
Mike Stump1eb44332009-09-09 15:08:12 +00002132 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002133 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002134 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002135 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002136
Eli Friedman5c89c392012-02-23 02:25:10 +00002137 QualType ResultType = CurrentObjectType;
2138 if (!ResultType->isArrayType())
2139 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2140 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002141
Douglas Gregorfa219202009-03-20 23:58:33 +00002142 // Pre-allocate storage for the structured initializer list.
2143 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002144 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002145 bool GotNumInits = false;
2146 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002147 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002148 GotNumInits = true;
2149 } else if (Index < IList->getNumInits()) {
2150 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002151 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002152 GotNumInits = true;
2153 }
Douglas Gregor08457732009-03-21 18:13:52 +00002154 }
2155
Mike Stump1eb44332009-09-09 15:08:12 +00002156 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002157 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2158 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2159 NumElements = CAType->getSize().getZExtValue();
2160 // Simple heuristic so that we don't allocate a very large
2161 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002162 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002163 NumElements = 0;
2164 }
John McCall183700f2009-09-21 23:43:11 +00002165 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002166 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002167 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002168 RecordDecl *RDecl = RType->getDecl();
2169 if (RDecl->isUnion())
2170 NumElements = 1;
2171 else
Mike Stump1eb44332009-09-09 15:08:12 +00002172 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002173 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002174 }
2175
Ted Kremenek709210f2010-04-13 23:39:13 +00002176 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002177
Douglas Gregor4c678342009-01-28 21:54:33 +00002178 // Link this new initializer list into the structured initializer
2179 // lists.
2180 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002181 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002182 else {
2183 Result->setSyntacticForm(IList);
2184 SyntacticToSemantic[IList] = Result;
2185 }
2186
2187 return Result;
2188}
2189
2190/// Update the initializer at index @p StructuredIndex within the
2191/// structured initializer list to the value @p expr.
2192void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2193 unsigned &StructuredIndex,
2194 Expr *expr) {
2195 // No structured initializer list to update
2196 if (!StructuredList)
2197 return;
2198
Ted Kremenek709210f2010-04-13 23:39:13 +00002199 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2200 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002201 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002202 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002203 diag::warn_initializer_overrides)
2204 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002205 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002206 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002207 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002208 << PrevInit->getSourceRange();
2209 }
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Douglas Gregor4c678342009-01-28 21:54:33 +00002211 ++StructuredIndex;
2212}
2213
Douglas Gregor05c13a32009-01-22 00:58:24 +00002214/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002215/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002216/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002217/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002218/// failure. Returns the index expression, possibly with an implicit cast
2219/// added, on success. If everything went okay, Value will receive the
2220/// value of the constant expression.
2221static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002222CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002223 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002224
2225 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002226 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2227 if (Result.isInvalid())
2228 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002229
Chris Lattner3bf68932009-04-25 21:59:05 +00002230 if (Value.isSigned() && Value.isNegative())
2231 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002232 << Value.toString(10) << Index->getSourceRange();
2233
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002234 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002235 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002236}
2237
John McCall60d7b3a2010-08-24 06:29:42 +00002238ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002239 SourceLocation Loc,
2240 bool GNUSyntax,
2241 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002242 typedef DesignatedInitExpr::Designator ASTDesignator;
2243
2244 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002245 SmallVector<ASTDesignator, 32> Designators;
2246 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002247
2248 // Build designators and check array designator expressions.
2249 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2250 const Designator &D = Desig.getDesignator(Idx);
2251 switch (D.getKind()) {
2252 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002253 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002254 D.getFieldLoc()));
2255 break;
2256
2257 case Designator::ArrayDesignator: {
2258 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2259 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002260 if (!Index->isTypeDependent() && !Index->isValueDependent())
2261 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2262 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002263 Invalid = true;
2264 else {
2265 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002266 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002267 D.getRBracketLoc()));
2268 InitExpressions.push_back(Index);
2269 }
2270 break;
2271 }
2272
2273 case Designator::ArrayRangeDesignator: {
2274 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2275 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2276 llvm::APSInt StartValue;
2277 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002278 bool StartDependent = StartIndex->isTypeDependent() ||
2279 StartIndex->isValueDependent();
2280 bool EndDependent = EndIndex->isTypeDependent() ||
2281 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002282 if (!StartDependent)
2283 StartIndex =
2284 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2285 if (!EndDependent)
2286 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2287
2288 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002289 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002290 else {
2291 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002292 if (StartDependent || EndDependent) {
2293 // Nothing to compute.
2294 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002295 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002296 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002297 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002298
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002299 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002300 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002301 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002302 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2303 Invalid = true;
2304 } else {
2305 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002306 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002307 D.getEllipsisLoc(),
2308 D.getRBracketLoc()));
2309 InitExpressions.push_back(StartIndex);
2310 InitExpressions.push_back(EndIndex);
2311 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002312 }
2313 break;
2314 }
2315 }
2316 }
2317
2318 if (Invalid || Init.isInvalid())
2319 return ExprError();
2320
2321 // Clear out the expressions within the designation.
2322 Desig.ClearExprs(*this);
2323
2324 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002325 = DesignatedInitExpr::Create(Context,
2326 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002327 InitExpressions, Loc, GNUSyntax,
2328 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002329
David Blaikie4e4d0842012-03-11 07:00:24 +00002330 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002331 Diag(DIE->getLocStart(), diag::ext_designated_init)
2332 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002333
Douglas Gregor05c13a32009-01-22 00:58:24 +00002334 return Owned(DIE);
2335}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002336
Douglas Gregor20093b42009-12-09 23:02:17 +00002337//===----------------------------------------------------------------------===//
2338// Initialization entity
2339//===----------------------------------------------------------------------===//
2340
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002341InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002342 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002343 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002344{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002345 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2346 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002347 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002348 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002349 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002350 Type = VT->getElementType();
2351 } else {
2352 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2353 assert(CT && "Unexpected type");
2354 Kind = EK_ComplexElement;
2355 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002356 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002357}
2358
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002359InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002360 CXXBaseSpecifier *Base,
2361 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002362{
2363 InitializedEntity Result;
2364 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002365 Result.Base = reinterpret_cast<uintptr_t>(Base);
2366 if (IsInheritedVirtualBase)
2367 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002368
Douglas Gregord6542d82009-12-22 15:35:07 +00002369 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002370 return Result;
2371}
2372
Douglas Gregor99a2e602009-12-16 01:38:02 +00002373DeclarationName InitializedEntity::getName() const {
2374 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002375 case EK_Parameter: {
2376 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2377 return (D ? D->getDeclName() : DeclarationName());
2378 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002379
2380 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002381 case EK_Member:
2382 return VariableOrMember->getDeclName();
2383
Douglas Gregor47736542012-02-15 16:57:26 +00002384 case EK_LambdaCapture:
2385 return Capture.Var->getDeclName();
2386
Douglas Gregor99a2e602009-12-16 01:38:02 +00002387 case EK_Result:
2388 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002389 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002390 case EK_Temporary:
2391 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002392 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002393 case EK_ArrayElement:
2394 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002395 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002396 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002397 case EK_CompoundLiteralInit:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002398 return DeclarationName();
2399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002400
David Blaikie7530c032012-01-17 06:56:22 +00002401 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002402}
2403
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002404DeclaratorDecl *InitializedEntity::getDecl() const {
2405 switch (getKind()) {
2406 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002407 case EK_Member:
2408 return VariableOrMember;
2409
John McCallf85e1932011-06-15 23:02:42 +00002410 case EK_Parameter:
2411 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2412
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002413 case EK_Result:
2414 case EK_Exception:
2415 case EK_New:
2416 case EK_Temporary:
2417 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002418 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002419 case EK_ArrayElement:
2420 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002421 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002422 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002423 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002424 case EK_CompoundLiteralInit:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002425 return 0;
2426 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002427
David Blaikie7530c032012-01-17 06:56:22 +00002428 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002429}
2430
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002431bool InitializedEntity::allowsNRVO() const {
2432 switch (getKind()) {
2433 case EK_Result:
2434 case EK_Exception:
2435 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002436
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002437 case EK_Variable:
2438 case EK_Parameter:
2439 case EK_Member:
2440 case EK_New:
2441 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002442 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002443 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002444 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002445 case EK_ArrayElement:
2446 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002447 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002448 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002449 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002450 break;
2451 }
2452
2453 return false;
2454}
2455
Douglas Gregor20093b42009-12-09 23:02:17 +00002456//===----------------------------------------------------------------------===//
2457// Initialization sequence
2458//===----------------------------------------------------------------------===//
2459
2460void InitializationSequence::Step::Destroy() {
2461 switch (Kind) {
2462 case SK_ResolveAddressOfOverloadedFunction:
2463 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002464 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002465 case SK_CastDerivedToBaseLValue:
2466 case SK_BindReference:
2467 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002468 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002469 case SK_UserConversion:
2470 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002471 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002473 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002474 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002475 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002476 case SK_UnwrapInitList:
2477 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002478 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002479 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002480 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002481 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002482 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002483 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002484 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002485 case SK_PassByIndirectCopyRestore:
2486 case SK_PassByIndirectRestore:
2487 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002488 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002489 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002490 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002491 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002492
Douglas Gregor20093b42009-12-09 23:02:17 +00002493 case SK_ConversionSequence:
2494 delete ICS;
2495 }
2496}
2497
Douglas Gregorb70cf442010-03-26 20:14:36 +00002498bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002499 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002500}
2501
2502bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002503 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002504 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002505
Douglas Gregorb70cf442010-03-26 20:14:36 +00002506 switch (getFailureKind()) {
2507 case FK_TooManyInitsForReference:
2508 case FK_ArrayNeedsInitList:
2509 case FK_ArrayNeedsInitListOrStringLiteral:
2510 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2511 case FK_NonConstLValueReferenceBindingToTemporary:
2512 case FK_NonConstLValueReferenceBindingToUnrelated:
2513 case FK_RValueReferenceBindingToLValue:
2514 case FK_ReferenceInitDropsQualifiers:
2515 case FK_ReferenceInitFailed:
2516 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002517 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002518 case FK_TooManyInitsForScalar:
2519 case FK_ReferenceBindingToInitList:
2520 case FK_InitListBadDestinationType:
2521 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002522 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002523 case FK_ArrayTypeMismatch:
2524 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002525 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002526 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002527 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002528 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002529 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002530 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002531
Douglas Gregorb70cf442010-03-26 20:14:36 +00002532 case FK_ReferenceInitOverloadFailed:
2533 case FK_UserConversionOverloadFailed:
2534 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002535 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002536 return FailedOverloadResult == OR_Ambiguous;
2537 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002538
David Blaikie7530c032012-01-17 06:56:22 +00002539 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002540}
2541
Douglas Gregord6e44a32010-04-16 22:09:46 +00002542bool InitializationSequence::isConstructorInitialization() const {
2543 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2544}
2545
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002546void
2547InitializationSequence
2548::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2549 DeclAccessPair Found,
2550 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002551 Step S;
2552 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2553 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002554 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002555 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002556 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002557 Steps.push_back(S);
2558}
2559
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002560void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002561 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002562 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002563 switch (VK) {
2564 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2565 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2566 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002567 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002568 S.Type = BaseType;
2569 Steps.push_back(S);
2570}
2571
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002572void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002573 bool BindingTemporary) {
2574 Step S;
2575 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2576 S.Type = T;
2577 Steps.push_back(S);
2578}
2579
Douglas Gregor523d46a2010-04-18 07:40:54 +00002580void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2581 Step S;
2582 S.Kind = SK_ExtraneousCopyToTemporary;
2583 S.Type = T;
2584 Steps.push_back(S);
2585}
2586
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002587void
2588InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2589 DeclAccessPair FoundDecl,
2590 QualType T,
2591 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002592 Step S;
2593 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002594 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002595 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002596 S.Function.Function = Function;
2597 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002598 Steps.push_back(S);
2599}
2600
2601void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002602 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002603 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002604 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002605 switch (VK) {
2606 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002607 S.Kind = SK_QualificationConversionRValue;
2608 break;
John McCall5baba9d2010-08-25 10:28:54 +00002609 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002610 S.Kind = SK_QualificationConversionXValue;
2611 break;
John McCall5baba9d2010-08-25 10:28:54 +00002612 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002613 S.Kind = SK_QualificationConversionLValue;
2614 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002615 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002616 S.Type = Ty;
2617 Steps.push_back(S);
2618}
2619
Jordan Rose1fd1e282013-04-11 00:58:58 +00002620void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2621 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2622
2623 Step S;
2624 S.Kind = SK_LValueToRValue;
2625 S.Type = Ty;
2626 Steps.push_back(S);
2627}
2628
Douglas Gregor20093b42009-12-09 23:02:17 +00002629void InitializationSequence::AddConversionSequenceStep(
2630 const ImplicitConversionSequence &ICS,
2631 QualType T) {
2632 Step S;
2633 S.Kind = SK_ConversionSequence;
2634 S.Type = T;
2635 S.ICS = new ImplicitConversionSequence(ICS);
2636 Steps.push_back(S);
2637}
2638
Douglas Gregord87b61f2009-12-10 17:56:55 +00002639void InitializationSequence::AddListInitializationStep(QualType T) {
2640 Step S;
2641 S.Kind = SK_ListInitialization;
2642 S.Type = T;
2643 Steps.push_back(S);
2644}
2645
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002646void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002647InitializationSequence
2648::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2649 AccessSpecifier Access,
2650 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002651 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002652 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002653 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002654 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2655 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002656 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002657 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002658 S.Function.Function = Constructor;
2659 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002660 Steps.push_back(S);
2661}
2662
Douglas Gregor71d17402009-12-15 00:01:57 +00002663void InitializationSequence::AddZeroInitializationStep(QualType T) {
2664 Step S;
2665 S.Kind = SK_ZeroInitialization;
2666 S.Type = T;
2667 Steps.push_back(S);
2668}
2669
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002670void InitializationSequence::AddCAssignmentStep(QualType T) {
2671 Step S;
2672 S.Kind = SK_CAssignment;
2673 S.Type = T;
2674 Steps.push_back(S);
2675}
2676
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002677void InitializationSequence::AddStringInitStep(QualType T) {
2678 Step S;
2679 S.Kind = SK_StringInit;
2680 S.Type = T;
2681 Steps.push_back(S);
2682}
2683
Douglas Gregor569c3162010-08-07 11:51:51 +00002684void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2685 Step S;
2686 S.Kind = SK_ObjCObjectConversion;
2687 S.Type = T;
2688 Steps.push_back(S);
2689}
2690
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002691void InitializationSequence::AddArrayInitStep(QualType T) {
2692 Step S;
2693 S.Kind = SK_ArrayInit;
2694 S.Type = T;
2695 Steps.push_back(S);
2696}
2697
Richard Smith0f163e92012-02-15 22:38:09 +00002698void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2699 Step S;
2700 S.Kind = SK_ParenthesizedArrayInit;
2701 S.Type = T;
2702 Steps.push_back(S);
2703}
2704
John McCallf85e1932011-06-15 23:02:42 +00002705void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2706 bool shouldCopy) {
2707 Step s;
2708 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2709 : SK_PassByIndirectRestore);
2710 s.Type = type;
2711 Steps.push_back(s);
2712}
2713
2714void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2715 Step S;
2716 S.Kind = SK_ProduceObjCObject;
2717 S.Type = T;
2718 Steps.push_back(S);
2719}
2720
Sebastian Redl2b916b82012-01-17 22:49:42 +00002721void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2722 Step S;
2723 S.Kind = SK_StdInitializerList;
2724 S.Type = T;
2725 Steps.push_back(S);
2726}
2727
Guy Benyei21f18c42013-02-07 10:55:47 +00002728void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2729 Step S;
2730 S.Kind = SK_OCLSamplerInit;
2731 S.Type = T;
2732 Steps.push_back(S);
2733}
2734
Guy Benyeie6b9d802013-01-20 12:31:11 +00002735void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2736 Step S;
2737 S.Kind = SK_OCLZeroEvent;
2738 S.Type = T;
2739 Steps.push_back(S);
2740}
2741
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002742void InitializationSequence::RewrapReferenceInitList(QualType T,
2743 InitListExpr *Syntactic) {
2744 assert(Syntactic->getNumInits() == 1 &&
2745 "Can only rewrap trivial init lists.");
2746 Step S;
2747 S.Kind = SK_UnwrapInitList;
2748 S.Type = Syntactic->getInit(0)->getType();
2749 Steps.insert(Steps.begin(), S);
2750
2751 S.Kind = SK_RewrapInitList;
2752 S.Type = T;
2753 S.WrappingSyntacticList = Syntactic;
2754 Steps.push_back(S);
2755}
2756
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002757void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002758 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002759 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002760 this->Failure = Failure;
2761 this->FailedOverloadResult = Result;
2762}
2763
2764//===----------------------------------------------------------------------===//
2765// Attempt initialization
2766//===----------------------------------------------------------------------===//
2767
John McCallf85e1932011-06-15 23:02:42 +00002768static void MaybeProduceObjCObject(Sema &S,
2769 InitializationSequence &Sequence,
2770 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002771 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002772
2773 /// When initializing a parameter, produce the value if it's marked
2774 /// __attribute__((ns_consumed)).
2775 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2776 if (!Entity.isParameterConsumed())
2777 return;
2778
2779 assert(Entity.getType()->isObjCRetainableType() &&
2780 "consuming an object of unretainable type?");
2781 Sequence.AddProduceObjCObjectStep(Entity.getType());
2782
2783 /// When initializing a return value, if the return type is a
2784 /// retainable type, then returns need to immediately retain the
2785 /// object. If an autorelease is required, it will be done at the
2786 /// last instant.
2787 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2788 if (!Entity.getType()->isObjCRetainableType())
2789 return;
2790
2791 Sequence.AddProduceObjCObjectStep(Entity.getType());
2792 }
2793}
2794
Richard Smithf4bb8d02012-07-05 08:39:21 +00002795/// \brief When initializing from init list via constructor, handle
2796/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002797///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002798/// \return true if we have handled initialization of an object of type
2799/// std::initializer_list<T>, false otherwise.
2800static bool TryInitializerListConstruction(Sema &S,
2801 InitListExpr *List,
2802 QualType DestType,
2803 InitializationSequence &Sequence) {
2804 QualType E;
2805 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002806 return false;
2807
Richard Smithf4bb8d02012-07-05 08:39:21 +00002808 // Check that each individual element can be copy-constructed. But since we
2809 // have no place to store further information, we'll recalculate everything
2810 // later.
2811 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2812 S.Context.getConstantArrayType(E,
2813 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2814 List->getNumInits()),
2815 ArrayType::Normal, 0));
2816 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2817 0, HiddenArray);
2818 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2819 Element.setElementIndex(i);
2820 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2821 Sequence.SetFailed(
2822 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002823 return true;
2824 }
2825 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002826 Sequence.AddStdInitializerListConstructionStep(DestType);
2827 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002828}
2829
Sebastian Redl96715b22012-02-04 21:27:39 +00002830static OverloadingResult
2831ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002832 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002833 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002834 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002835 OverloadCandidateSet::iterator &Best,
2836 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002837 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002838 CandidateSet.clear();
2839
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002840 for (ArrayRef<NamedDecl *>::iterator
2841 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002842 NamedDecl *D = *Con;
2843 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2844 bool SuppressUserConversions = false;
2845
2846 // Find the constructor (which may be a template).
2847 CXXConstructorDecl *Constructor = 0;
2848 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2849 if (ConstructorTmpl)
2850 Constructor = cast<CXXConstructorDecl>(
2851 ConstructorTmpl->getTemplatedDecl());
2852 else {
2853 Constructor = cast<CXXConstructorDecl>(D);
2854
2855 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002856 // suppress user-defined conversions on the arguments. We do the same for
2857 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002858 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002859 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002860 SuppressUserConversions = true;
2861 }
2862
2863 if (!Constructor->isInvalidDecl() &&
2864 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002865 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002866 if (ConstructorTmpl)
2867 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002868 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002869 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002870 else {
2871 // C++ [over.match.copy]p1:
2872 // - When initializing a temporary to be bound to the first parameter
2873 // of a constructor that takes a reference to possibly cv-qualified
2874 // T as its first argument, called with a single argument in the
2875 // context of direct-initialization, explicit conversion functions
2876 // are also considered.
2877 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002878 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00002879 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002880 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002881 SuppressUserConversions,
2882 /*PartialOverloading=*/false,
2883 /*AllowExplicit=*/AllowExplicitConv);
2884 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002885 }
2886 }
2887
2888 // Perform overload resolution and return the result.
2889 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2890}
2891
Sebastian Redl10f04a62011-12-22 14:44:04 +00002892/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2893/// enumerates the constructors of the initialized entity and performs overload
2894/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002895/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002896/// class type.
2897static void TryConstructorInitialization(Sema &S,
2898 const InitializedEntity &Entity,
2899 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002900 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002901 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002902 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002903 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00002904 "InitListSyntax must come with a single initializer list argument.");
2905
Sebastian Redl10f04a62011-12-22 14:44:04 +00002906 // The type we're constructing needs to be complete.
2907 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002908 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002909 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002910 }
2911
2912 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2913 assert(DestRecordType && "Constructor initialization requires record type");
2914 CXXRecordDecl *DestRecordDecl
2915 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2916
Sebastian Redl96715b22012-02-04 21:27:39 +00002917 // Build the candidate set directly in the initialization sequence
2918 // structure, so that it will persist if we fail.
2919 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2920
2921 // Determine whether we are allowed to call explicit constructors or
2922 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002923 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002924 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002925
Sebastian Redl10f04a62011-12-22 14:44:04 +00002926 // - Otherwise, if T is a class type, constructors are considered. The
2927 // applicable constructors are enumerated, and the best one is chosen
2928 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00002929 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002930 // The container holding the constructors can under certain conditions
2931 // be changed while iterating (e.g. because of deserialization).
2932 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00002933 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00002934
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002935 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002936 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002937 bool AsInitializerList = false;
2938
2939 // C++11 [over.match.list]p1:
2940 // When objects of non-aggregate type T are list-initialized, overload
2941 // resolution selects the constructor in two phases:
2942 // - Initially, the candidate functions are the initializer-list
2943 // constructors of the class T and the argument list consists of the
2944 // initializer list as a single argument.
2945 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002946 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002947 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00002948
2949 // If the initializer list has no elements and T has a default constructor,
2950 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00002951 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002952 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002953 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00002954 CopyInitialization, AllowExplicit,
2955 /*OnlyListConstructor=*/true,
2956 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002957
2958 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002959 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002960 }
2961
2962 // C++11 [over.match.list]p1:
2963 // - If no viable initializer-list constructor is found, overload resolution
2964 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00002965 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002966 // elements of the initializer list.
2967 if (Result == OR_No_Viable_Function) {
2968 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002969 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002970 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002971 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002972 /*OnlyListConstructors=*/false,
2973 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002974 }
2975 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002976 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002977 InitializationSequence::FK_ListConstructorOverloadFailed :
2978 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002979 Result);
2980 return;
2981 }
2982
Richard Smithf4bb8d02012-07-05 08:39:21 +00002983 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002984 // If a program calls for the default initialization of an object
2985 // of a const-qualified type T, T shall be a class type with a
2986 // user-provided default constructor.
2987 if (Kind.getKind() == InitializationKind::IK_Default &&
2988 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00002989 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002990 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2991 return;
2992 }
2993
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002994 // C++11 [over.match.list]p1:
2995 // In copy-list-initialization, if an explicit constructor is chosen, the
2996 // initializer is ill-formed.
2997 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2998 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2999 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3000 return;
3001 }
3002
Sebastian Redl10f04a62011-12-22 14:44:04 +00003003 // Add the constructor initialization step. Any cv-qualification conversion is
3004 // subsumed by the initialization.
3005 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003006 Sequence.AddConstructorInitializationStep(CtorDecl,
3007 Best->FoundDecl.getAccess(),
3008 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003009 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003010}
3011
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003012static bool
3013ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3014 Expr *Initializer,
3015 QualType &SourceType,
3016 QualType &UnqualifiedSourceType,
3017 QualType UnqualifiedTargetType,
3018 InitializationSequence &Sequence) {
3019 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3020 S.Context.OverloadTy) {
3021 DeclAccessPair Found;
3022 bool HadMultipleCandidates = false;
3023 if (FunctionDecl *Fn
3024 = S.ResolveAddressOfOverloadedFunction(Initializer,
3025 UnqualifiedTargetType,
3026 false, Found,
3027 &HadMultipleCandidates)) {
3028 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3029 HadMultipleCandidates);
3030 SourceType = Fn->getType();
3031 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3032 } else if (!UnqualifiedTargetType->isRecordType()) {
3033 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3034 return true;
3035 }
3036 }
3037 return false;
3038}
3039
3040static void TryReferenceInitializationCore(Sema &S,
3041 const InitializedEntity &Entity,
3042 const InitializationKind &Kind,
3043 Expr *Initializer,
3044 QualType cv1T1, QualType T1,
3045 Qualifiers T1Quals,
3046 QualType cv2T2, QualType T2,
3047 Qualifiers T2Quals,
3048 InitializationSequence &Sequence);
3049
Richard Smithf4bb8d02012-07-05 08:39:21 +00003050static void TryValueInitialization(Sema &S,
3051 const InitializedEntity &Entity,
3052 const InitializationKind &Kind,
3053 InitializationSequence &Sequence,
3054 InitListExpr *InitList = 0);
3055
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003056static void TryListInitialization(Sema &S,
3057 const InitializedEntity &Entity,
3058 const InitializationKind &Kind,
3059 InitListExpr *InitList,
3060 InitializationSequence &Sequence);
3061
3062/// \brief Attempt list initialization of a reference.
3063static void TryReferenceListInitialization(Sema &S,
3064 const InitializedEntity &Entity,
3065 const InitializationKind &Kind,
3066 InitListExpr *InitList,
3067 InitializationSequence &Sequence)
3068{
3069 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003070 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003071 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3072 return;
3073 }
3074
3075 QualType DestType = Entity.getType();
3076 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3077 Qualifiers T1Quals;
3078 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3079
3080 // Reference initialization via an initializer list works thus:
3081 // If the initializer list consists of a single element that is
3082 // reference-related to the referenced type, bind directly to that element
3083 // (possibly creating temporaries).
3084 // Otherwise, initialize a temporary with the initializer list and
3085 // bind to that.
3086 if (InitList->getNumInits() == 1) {
3087 Expr *Initializer = InitList->getInit(0);
3088 QualType cv2T2 = Initializer->getType();
3089 Qualifiers T2Quals;
3090 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3091
3092 // If this fails, creating a temporary wouldn't work either.
3093 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3094 T1, Sequence))
3095 return;
3096
3097 SourceLocation DeclLoc = Initializer->getLocStart();
3098 bool dummy1, dummy2, dummy3;
3099 Sema::ReferenceCompareResult RefRelationship
3100 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3101 dummy2, dummy3);
3102 if (RefRelationship >= Sema::Ref_Related) {
3103 // Try to bind the reference here.
3104 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3105 T1Quals, cv2T2, T2, T2Quals, Sequence);
3106 if (Sequence)
3107 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3108 return;
3109 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003110
3111 // Update the initializer if we've resolved an overloaded function.
3112 if (Sequence.step_begin() != Sequence.step_end())
3113 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003114 }
3115
3116 // Not reference-related. Create a temporary and bind to that.
3117 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3118
3119 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3120 if (Sequence) {
3121 if (DestType->isRValueReferenceType() ||
3122 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3123 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3124 else
3125 Sequence.SetFailed(
3126 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3127 }
3128}
3129
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003130/// \brief Attempt list initialization (C++0x [dcl.init.list])
3131static void TryListInitialization(Sema &S,
3132 const InitializedEntity &Entity,
3133 const InitializationKind &Kind,
3134 InitListExpr *InitList,
3135 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003136 QualType DestType = Entity.getType();
3137
Sebastian Redl14b0c192011-09-24 17:48:00 +00003138 // C++ doesn't allow scalar initialization with more than one argument.
3139 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003140 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003141 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3142 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3143 return;
3144 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003145 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003146 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003147 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003148 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003149 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003150 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003151 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003152 return;
3153 }
3154
Richard Smithf4bb8d02012-07-05 08:39:21 +00003155 // C++11 [dcl.init.list]p3:
3156 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003157 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003158 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003159 // - Otherwise, if the initializer list has no elements and T is a
3160 // class type with a default constructor, the object is
3161 // value-initialized.
3162 if (InitList->getNumInits() == 0) {
3163 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003164 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003165 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3166 return;
3167 }
3168 }
3169
3170 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3171 // an initializer_list object constructed [...]
3172 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3173 return;
3174
3175 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003176 Expr *InitListAsExpr = InitList;
3177 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003178 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003179 } else
3180 Sequence.SetFailed(
3181 InitializationSequence::FK_InitListBadDestinationType);
3182 return;
3183 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003184 }
3185
Sebastian Redl14b0c192011-09-24 17:48:00 +00003186 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003187 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003188 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00003189 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003190 if (CheckInitList.HadError()) {
3191 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3192 return;
3193 }
3194
3195 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003196 Sequence.AddListInitializationStep(DestType);
3197}
Douglas Gregor20093b42009-12-09 23:02:17 +00003198
3199/// \brief Try a reference initialization that involves calling a conversion
3200/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003201static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3202 const InitializedEntity &Entity,
3203 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003204 Expr *Initializer,
3205 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003206 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003207 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003208 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3209 QualType T1 = cv1T1.getUnqualifiedType();
3210 QualType cv2T2 = Initializer->getType();
3211 QualType T2 = cv2T2.getUnqualifiedType();
3212
3213 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003214 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003215 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003216 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003217 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003218 ObjCConversion,
3219 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003220 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003221 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003222 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003223 (void)ObjCLifetimeConversion;
3224
Douglas Gregor20093b42009-12-09 23:02:17 +00003225 // Build the candidate set directly in the initialization sequence
3226 // structure, so that it will persist if we fail.
3227 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3228 CandidateSet.clear();
3229
3230 // Determine whether we are allowed to call explicit constructors or
3231 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003232 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003233 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3234
Douglas Gregor20093b42009-12-09 23:02:17 +00003235 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003236 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3237 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003238 // The type we're converting to is a class type. Enumerate its constructors
3239 // to see if there is a suitable conversion.
3240 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003241
David Blaikie3bc93e32012-12-19 00:45:41 +00003242 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003243 // The container holding the constructors can under certain conditions
3244 // be changed while iterating (e.g. because of deserialization).
3245 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003246 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003247 for (SmallVector<NamedDecl*, 16>::iterator
3248 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3249 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003250 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3251
Douglas Gregor20093b42009-12-09 23:02:17 +00003252 // Find the constructor (which may be a template).
3253 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003254 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003255 if (ConstructorTmpl)
3256 Constructor = cast<CXXConstructorDecl>(
3257 ConstructorTmpl->getTemplatedDecl());
3258 else
John McCall9aa472c2010-03-19 07:35:19 +00003259 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260
Douglas Gregor20093b42009-12-09 23:02:17 +00003261 if (!Constructor->isInvalidDecl() &&
3262 Constructor->isConvertingConstructor(AllowExplicit)) {
3263 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003264 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003265 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003266 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003267 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003268 else
John McCall9aa472c2010-03-19 07:35:19 +00003269 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003270 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003271 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003272 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003273 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003274 }
John McCall572fc622010-08-17 07:23:57 +00003275 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3276 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003277
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003278 const RecordType *T2RecordType = 0;
3279 if ((T2RecordType = T2->getAs<RecordType>()) &&
3280 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003281 // The type we're converting from is a class type, enumerate its conversion
3282 // functions.
3283 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3284
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003285 std::pair<CXXRecordDecl::conversion_iterator,
3286 CXXRecordDecl::conversion_iterator>
3287 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3288 for (CXXRecordDecl::conversion_iterator
3289 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003290 NamedDecl *D = *I;
3291 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3292 if (isa<UsingShadowDecl>(D))
3293 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294
Douglas Gregor20093b42009-12-09 23:02:17 +00003295 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3296 CXXConversionDecl *Conv;
3297 if (ConvTemplate)
3298 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3299 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003300 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003301
Douglas Gregor20093b42009-12-09 23:02:17 +00003302 // If the conversion function doesn't return a reference type,
3303 // it can't be considered for this conversion unless we're allowed to
3304 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003305 // FIXME: Do we need to make sure that we only consider conversion
3306 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003307 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003308 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003309 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3310 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003311 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003312 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003313 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003314 else
John McCall9aa472c2010-03-19 07:35:19 +00003315 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003316 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003317 }
3318 }
3319 }
John McCall572fc622010-08-17 07:23:57 +00003320 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3321 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003322
Douglas Gregor20093b42009-12-09 23:02:17 +00003323 SourceLocation DeclLoc = Initializer->getLocStart();
3324
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003325 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003326 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003328 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003329 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003330
Douglas Gregor20093b42009-12-09 23:02:17 +00003331 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003332 // This is the overload that will be used for this initialization step if we
3333 // use this initialization. Mark it as referenced.
3334 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003335
Eli Friedman03981012009-12-11 02:42:07 +00003336 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003337 if (isa<CXXConversionDecl>(Function))
3338 T2 = Function->getResultType();
3339 else
3340 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003341
3342 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003343 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003344 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003345 T2.getNonLValueExprType(S.Context),
3346 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003347
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003348 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003349 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003350 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003351 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003352 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003353 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003354 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003355
Douglas Gregor20093b42009-12-09 23:02:17 +00003356 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003357 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003358 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003359 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003361 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003362 NewDerivedToBase, NewObjCConversion,
3363 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003364 if (NewRefRelationship == Sema::Ref_Incompatible) {
3365 // If the type we've converted to is not reference-related to the
3366 // type we're looking for, then there is another conversion step
3367 // we need to perform to produce a temporary of the right type
3368 // that we'll be binding to.
3369 ImplicitConversionSequence ICS;
3370 ICS.setStandard();
3371 ICS.Standard = Best->FinalConversion;
3372 T2 = ICS.Standard.getToType(2);
3373 Sequence.AddConversionSequenceStep(ICS, T2);
3374 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003375 Sequence.AddDerivedToBaseCastStep(
3376 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003378 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003379 else if (NewObjCConversion)
3380 Sequence.AddObjCObjectConversionStep(
3381 S.Context.getQualifiedType(T1,
3382 T2.getNonReferenceType().getQualifiers()));
3383
Douglas Gregor20093b42009-12-09 23:02:17 +00003384 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003385 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003386
Douglas Gregor20093b42009-12-09 23:02:17 +00003387 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3388 return OR_Success;
3389}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390
Richard Smith83da2e72011-10-19 16:55:56 +00003391static void CheckCXX98CompatAccessibleCopy(Sema &S,
3392 const InitializedEntity &Entity,
3393 Expr *CurInitExpr);
3394
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003395/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3396static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003397 const InitializedEntity &Entity,
3398 const InitializationKind &Kind,
3399 Expr *Initializer,
3400 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003401 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003402 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003403 Qualifiers T1Quals;
3404 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003405 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003406 Qualifiers T2Quals;
3407 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003408
Douglas Gregor20093b42009-12-09 23:02:17 +00003409 // If the initializer is the address of an overloaded function, try
3410 // to resolve the overloaded function. If all goes well, T2 is the
3411 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003412 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3413 T1, Sequence))
3414 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003415
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003416 // Delegate everything else to a subfunction.
3417 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3418 T1Quals, cv2T2, T2, T2Quals, Sequence);
3419}
3420
Jordan Rose1fd1e282013-04-11 00:58:58 +00003421/// Converts the target of reference initialization so that it has the
3422/// appropriate qualifiers and value kind.
3423///
3424/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3425/// \code
3426/// int x;
3427/// const int &r = x;
3428/// \endcode
3429///
3430/// In this case the reference is binding to a bitfield lvalue, which isn't
3431/// valid. Perform a load to create a lifetime-extended temporary instead.
3432/// \code
3433/// const int &r = someStruct.bitfield;
3434/// \endcode
3435static ExprValueKind
3436convertQualifiersAndValueKindIfNecessary(Sema &S,
3437 InitializationSequence &Sequence,
3438 Expr *Initializer,
3439 QualType cv1T1,
3440 Qualifiers T1Quals,
3441 Qualifiers T2Quals,
3442 bool IsLValueRef) {
3443 bool IsNonAddressableType = Initializer->getBitField() ||
3444 Initializer->refersToVectorElement();
3445
3446 if (IsNonAddressableType) {
3447 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3448 // lvalue reference to a non-volatile const type, or the reference shall be
3449 // an rvalue reference.
3450 //
3451 // If not, we can't make a temporary and bind to that. Give up and allow the
3452 // error to be diagnosed later.
3453 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3454 assert(Initializer->isGLValue());
3455 return Initializer->getValueKind();
3456 }
3457
3458 // Force a load so we can materialize a temporary.
3459 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3460 return VK_RValue;
3461 }
3462
3463 if (T1Quals != T2Quals) {
3464 Sequence.AddQualificationConversionStep(cv1T1,
3465 Initializer->getValueKind());
3466 }
3467
3468 return Initializer->getValueKind();
3469}
3470
3471
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003472/// \brief Reference initialization without resolving overloaded functions.
3473static void TryReferenceInitializationCore(Sema &S,
3474 const InitializedEntity &Entity,
3475 const InitializationKind &Kind,
3476 Expr *Initializer,
3477 QualType cv1T1, QualType T1,
3478 Qualifiers T1Quals,
3479 QualType cv2T2, QualType T2,
3480 Qualifiers T2Quals,
3481 InitializationSequence &Sequence) {
3482 QualType DestType = Entity.getType();
3483 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003484 // Compute some basic properties of the types and the initializer.
3485 bool isLValueRef = DestType->isLValueReferenceType();
3486 bool isRValueRef = !isLValueRef;
3487 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003488 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003489 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003490 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003491 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003492 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003493 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003494
Douglas Gregor20093b42009-12-09 23:02:17 +00003495 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003497 // "cv2 T2" as follows:
3498 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003499 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003500 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003501 // Note the analogous bullet points for rvlaue refs to functions. Because
3502 // there are no function rvalues in C++, rvalue refs to functions are treated
3503 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003504 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003505 bool T1Function = T1->isFunctionType();
3506 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003507 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003508 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003509 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003510 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003511 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003512 // reference-compatible with "cv2 T2," or
3513 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003514 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003515 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003516 // can occur. However, we do pay attention to whether it is a bit-field
3517 // to decide whether we're actually binding to a temporary created from
3518 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003519 if (DerivedToBase)
3520 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003521 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003522 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003523 else if (ObjCConversion)
3524 Sequence.AddObjCObjectConversionStep(
3525 S.Context.getQualifiedType(T1, T2Quals));
3526
Jordan Rose1fd1e282013-04-11 00:58:58 +00003527 ExprValueKind ValueKind =
3528 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3529 cv1T1, T1Quals, T2Quals,
3530 isLValueRef);
3531 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003532 return;
3533 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534
3535 // - has a class type (i.e., T2 is a class type), where T1 is not
3536 // reference-related to T2, and can be implicitly converted to an
3537 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3538 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 // applicable conversion functions (13.3.1.6) and choosing the best
3540 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003541 // If we have an rvalue ref to function type here, the rhs must be
3542 // an rvalue.
3543 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3544 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003545 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003546 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003547 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003548 Sequence);
3549 if (ConvOvlResult == OR_Success)
3550 return;
John McCall1d318332010-01-12 00:44:57 +00003551 if (ConvOvlResult != OR_No_Viable_Function) {
3552 Sequence.SetOverloadFailure(
3553 InitializationSequence::FK_ReferenceInitOverloadFailed,
3554 ConvOvlResult);
3555 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003556 }
3557 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003558
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003560 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003561 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003562 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003563 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3564 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3565 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003566 Sequence.SetOverloadFailure(
3567 InitializationSequence::FK_ReferenceInitOverloadFailed,
3568 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003569 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003570 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003571 ? (RefRelationship == Sema::Ref_Related
3572 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3573 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3574 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003575
Douglas Gregor20093b42009-12-09 23:02:17 +00003576 return;
3577 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003578
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003579 // - If the initializer expression
3580 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3581 // "cv1 T1" is reference-compatible with "cv2 T2"
3582 // Note: functions are handled below.
3583 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003584 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003585 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003586 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003587 (InitCategory.isXValue() ||
3588 (InitCategory.isPRValue() && T2->isRecordType()) ||
3589 (InitCategory.isPRValue() && T2->isArrayType()))) {
3590 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3591 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003592 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3593 // compiler the freedom to perform a copy here or bind to the
3594 // object, while C++0x requires that we bind directly to the
3595 // object. Hence, we always bind to the object without making an
3596 // extra copy. However, in C++03 requires that we check for the
3597 // presence of a suitable copy constructor:
3598 //
3599 // The constructor that would be used to make the copy shall
3600 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003601 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003602 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003603 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003604 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003605 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003606
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003607 if (DerivedToBase)
3608 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3609 ValueKind);
3610 else if (ObjCConversion)
3611 Sequence.AddObjCObjectConversionStep(
3612 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003613
Jordan Rose1fd1e282013-04-11 00:58:58 +00003614 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3615 Initializer, cv1T1,
3616 T1Quals, T2Quals,
3617 isLValueRef);
3618
3619 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003620 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003621 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003622
3623 // - has a class type (i.e., T2 is a class type), where T1 is not
3624 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003625 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3626 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003627 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003628 if (RefRelationship == Sema::Ref_Incompatible) {
3629 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3630 Kind, Initializer,
3631 /*AllowRValues=*/true,
3632 Sequence);
3633 if (ConvOvlResult)
3634 Sequence.SetOverloadFailure(
3635 InitializationSequence::FK_ReferenceInitOverloadFailed,
3636 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637
Douglas Gregor20093b42009-12-09 23:02:17 +00003638 return;
3639 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003640
Douglas Gregordefa32e2013-03-26 23:59:23 +00003641 if ((RefRelationship == Sema::Ref_Compatible ||
3642 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3643 isRValueRef && InitCategory.isLValue()) {
3644 Sequence.SetFailed(
3645 InitializationSequence::FK_RValueReferenceBindingToLValue);
3646 return;
3647 }
3648
Douglas Gregor20093b42009-12-09 23:02:17 +00003649 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3650 return;
3651 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003652
3653 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003654 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003656 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003657
Douglas Gregor20093b42009-12-09 23:02:17 +00003658 // Determine whether we are allowed to call explicit constructors or
3659 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003660 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003661
3662 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3663
John McCallf85e1932011-06-15 23:02:42 +00003664 ImplicitConversionSequence ICS
3665 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003666 /*SuppressUserConversions*/ false,
3667 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003668 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003669 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3670 /*AllowObjCWritebackConversion=*/false);
3671
3672 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003673 // FIXME: Use the conversion function set stored in ICS to turn
3674 // this into an overloading ambiguity diagnostic. However, we need
3675 // to keep that set as an OverloadCandidateSet rather than as some
3676 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003677 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3678 Sequence.SetOverloadFailure(
3679 InitializationSequence::FK_ReferenceInitOverloadFailed,
3680 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003681 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3682 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003683 else
3684 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003685 return;
John McCallf85e1932011-06-15 23:02:42 +00003686 } else {
3687 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003688 }
3689
3690 // [...] If T1 is reference-related to T2, cv1 must be the
3691 // same cv-qualification as, or greater cv-qualification
3692 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003693 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3694 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003695 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003696 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003697 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3698 return;
3699 }
3700
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003701 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003702 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003703 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003704 InitCategory.isLValue()) {
3705 Sequence.SetFailed(
3706 InitializationSequence::FK_RValueReferenceBindingToLValue);
3707 return;
3708 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3711 return;
3712}
3713
3714/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003715/// (C++ [dcl.init.string], C99 6.7.8).
3716static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003717 const InitializedEntity &Entity,
3718 const InitializationKind &Kind,
3719 Expr *Initializer,
3720 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003721 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003722}
3723
Douglas Gregor71d17402009-12-15 00:01:57 +00003724/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003725static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003726 const InitializedEntity &Entity,
3727 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003728 InitializationSequence &Sequence,
3729 InitListExpr *InitList) {
3730 assert((!InitList || InitList->getNumInits() == 0) &&
3731 "Shouldn't use value-init for non-empty init lists");
3732
Richard Smith1d0c9a82012-02-14 21:14:13 +00003733 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003734 //
3735 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003736 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003737
Douglas Gregor71d17402009-12-15 00:01:57 +00003738 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003739 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003740
Douglas Gregor71d17402009-12-15 00:01:57 +00003741 if (const RecordType *RT = T->getAs<RecordType>()) {
3742 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003743 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003744 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003745 // C++98:
3746 // -- if T is a class type (clause 9) with a user-declared constructor
3747 // (12.1), then the default constructor for T is called (and the
3748 // initialization is ill-formed if T has no accessible default
3749 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003750 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003751 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003752 } else {
3753 // C++11:
3754 // -- if T is a class type (clause 9) with either no default constructor
3755 // (12.1 [class.ctor]) or a default constructor that is user-provided
3756 // or deleted, then the object is default-initialized;
3757 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3758 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003759 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003760 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003761
Richard Smith1d0c9a82012-02-14 21:14:13 +00003762 // -- if T is a (possibly cv-qualified) non-union class type without a
3763 // user-provided or deleted default constructor, then the object is
3764 // zero-initialized and, if T has a non-trivial default constructor,
3765 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003766 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3767 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003768 if (NeedZeroInitialization)
3769 Sequence.AddZeroInitializationStep(Entity.getType());
3770
Richard Smithd5bc8672012-12-08 02:01:17 +00003771 // C++03:
3772 // -- if T is a non-union class type without a user-declared constructor,
3773 // then every non-static data member and base class component of T is
3774 // value-initialized;
3775 // [...] A program that calls for [...] value-initialization of an
3776 // entity of reference type is ill-formed.
3777 //
3778 // C++11 doesn't need this handling, because value-initialization does not
3779 // occur recursively there, and the implicit default constructor is
3780 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003781 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003782 ClassDecl->hasUninitializedReferenceMember()) {
3783 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3784 return;
3785 }
3786
Richard Smithf4bb8d02012-07-05 08:39:21 +00003787 // If this is list-value-initialization, pass the empty init list on when
3788 // building the constructor call. This affects the semantics of a few
3789 // things (such as whether an explicit default constructor can be called).
3790 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003791 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003792 bool InitListSyntax = InitList;
3793
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003794 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3795 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003796 }
3797 }
3798
Douglas Gregord6542d82009-12-22 15:35:07 +00003799 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003800}
3801
Douglas Gregor99a2e602009-12-16 01:38:02 +00003802/// \brief Attempt default initialization (C++ [dcl.init]p6).
3803static void TryDefaultInitialization(Sema &S,
3804 const InitializedEntity &Entity,
3805 const InitializationKind &Kind,
3806 InitializationSequence &Sequence) {
3807 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003808
Douglas Gregor99a2e602009-12-16 01:38:02 +00003809 // C++ [dcl.init]p6:
3810 // To default-initialize an object of type T means:
3811 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003812 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3813
Douglas Gregor99a2e602009-12-16 01:38:02 +00003814 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3815 // constructor for T is called (and the initialization is ill-formed if
3816 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003817 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003818 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003819 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003820 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003821
Douglas Gregor99a2e602009-12-16 01:38:02 +00003822 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
Douglas Gregor99a2e602009-12-16 01:38:02 +00003824 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003825 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003826 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003827 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003828 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003829 return;
3830 }
3831
3832 // If the destination type has a lifetime property, zero-initialize it.
3833 if (DestType.getQualifiers().hasObjCLifetime()) {
3834 Sequence.AddZeroInitializationStep(Entity.getType());
3835 return;
3836 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003837}
3838
Douglas Gregor20093b42009-12-09 23:02:17 +00003839/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3840/// which enumerates all conversion functions and performs overload resolution
3841/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003843 const InitializedEntity &Entity,
3844 const InitializationKind &Kind,
3845 Expr *Initializer,
3846 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003847 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003848 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3849 QualType SourceType = Initializer->getType();
3850 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3851 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003852
Douglas Gregor4a520a22009-12-14 17:27:33 +00003853 // Build the candidate set directly in the initialization sequence
3854 // structure, so that it will persist if we fail.
3855 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3856 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857
Douglas Gregor4a520a22009-12-14 17:27:33 +00003858 // Determine whether we are allowed to call explicit constructors or
3859 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003860 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003861
Douglas Gregor4a520a22009-12-14 17:27:33 +00003862 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3863 // The type we're converting to is a class type. Enumerate its constructors
3864 // to see if there is a suitable conversion.
3865 CXXRecordDecl *DestRecordDecl
3866 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003867
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003868 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003869 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003870 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003871 // The container holding the constructors can under certain conditions
3872 // be changed while iterating. To be safe we copy the lookup results
3873 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003874 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003875 for (SmallVector<NamedDecl*, 8>::iterator
3876 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003877 Con != ConEnd; ++Con) {
3878 NamedDecl *D = *Con;
3879 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003880
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003881 // Find the constructor (which may be a template).
3882 CXXConstructorDecl *Constructor = 0;
3883 FunctionTemplateDecl *ConstructorTmpl
3884 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003885 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003886 Constructor = cast<CXXConstructorDecl>(
3887 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003888 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003889 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003890
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003891 if (!Constructor->isInvalidDecl() &&
3892 Constructor->isConvertingConstructor(AllowExplicit)) {
3893 if (ConstructorTmpl)
3894 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3895 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003896 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003897 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003898 else
3899 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003900 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003901 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003902 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003903 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003904 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003905 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003906
3907 SourceLocation DeclLoc = Initializer->getLocStart();
3908
Douglas Gregor4a520a22009-12-14 17:27:33 +00003909 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3910 // The type we're converting from is a class type, enumerate its conversion
3911 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003912
Eli Friedman33c2da92009-12-20 22:12:03 +00003913 // We can only enumerate the conversion functions for a complete type; if
3914 // the type isn't complete, simply skip this step.
3915 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3916 CXXRecordDecl *SourceRecordDecl
3917 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003918
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003919 std::pair<CXXRecordDecl::conversion_iterator,
3920 CXXRecordDecl::conversion_iterator>
3921 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3922 for (CXXRecordDecl::conversion_iterator
3923 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003924 NamedDecl *D = *I;
3925 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3926 if (isa<UsingShadowDecl>(D))
3927 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928
Eli Friedman33c2da92009-12-20 22:12:03 +00003929 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3930 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003931 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003932 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003933 else
John McCall32daa422010-03-31 01:36:47 +00003934 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003935
Eli Friedman33c2da92009-12-20 22:12:03 +00003936 if (AllowExplicit || !Conv->isExplicit()) {
3937 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003938 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003939 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003940 CandidateSet);
3941 else
John McCall9aa472c2010-03-19 07:35:19 +00003942 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003943 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003944 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003945 }
3946 }
3947 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003948
3949 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003950 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003951 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003952 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003953 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003954 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003955 Result);
3956 return;
3957 }
John McCall1d318332010-01-12 00:44:57 +00003958
Douglas Gregor4a520a22009-12-14 17:27:33 +00003959 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003960 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003961 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003962
Douglas Gregor4a520a22009-12-14 17:27:33 +00003963 if (isa<CXXConstructorDecl>(Function)) {
3964 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003965 // subsumed by the initialization. Per DR5, the created temporary is of the
3966 // cv-unqualified type of the destination.
3967 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3968 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003969 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003970 return;
3971 }
3972
3973 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003974 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003975 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003976 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003977 // the resulting temporary object (possible to create an object of
3978 // a base class type). That copy is not a separate conversion, so
3979 // we just make a note of the actual destination type (possibly a
3980 // base class of the type returned by the conversion function) and
3981 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003982 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3983 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003984 return;
3985 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003986
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003987 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3988 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003989
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003990 // If the conversion following the call to the conversion function
3991 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003992 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3993 Best->FinalConversion.Third) {
3994 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003995 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003996 ICS.Standard = Best->FinalConversion;
3997 Sequence.AddConversionSequenceStep(ICS, DestType);
3998 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003999}
4000
John McCallf85e1932011-06-15 23:02:42 +00004001/// The non-zero enum values here are indexes into diagnostic alternatives.
4002enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4003
4004/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004005static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004006 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004007 // Skip parens.
4008 e = e->IgnoreParens();
4009
4010 // Skip address-of nodes.
4011 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4012 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004013 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4014 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004015
4016 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004017 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4018 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004019 case CK_Dependent:
4020 case CK_BitCast:
4021 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004022 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004023 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004024
4025 case CK_ArrayToPointerDecay:
4026 return IIK_nonscalar;
4027
4028 case CK_NullToPointer:
4029 return IIK_okay;
4030
4031 default:
4032 break;
4033 }
4034
4035 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004036 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004037 // set isWeakAccess to true, to mean that there will be an implicit
4038 // load which requires a cleanup.
4039 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4040 isWeakAccess = true;
4041
John McCallc03fa492011-06-27 23:59:58 +00004042 if (!isAddressOf) return IIK_nonlocal;
4043
John McCallf4b88a42012-03-10 09:33:50 +00004044 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4045 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004046
4047 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004048
4049 // If we have a conditional operator, check both sides.
4050 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004051 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4052 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004053 return iik;
4054
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004055 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004056
4057 // These are never scalar.
4058 } else if (isa<ArraySubscriptExpr>(e)) {
4059 return IIK_nonscalar;
4060
4061 // Otherwise, it needs to be a null pointer constant.
4062 } else {
4063 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4064 ? IIK_okay : IIK_nonlocal);
4065 }
4066
4067 return IIK_nonlocal;
4068}
4069
4070/// Check whether the given expression is a valid operand for an
4071/// indirect copy/restore.
4072static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4073 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004074 bool isWeakAccess = false;
4075 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4076 // If isWeakAccess to true, there will be an implicit
4077 // load which requires a cleanup.
4078 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4079 S.ExprNeedsCleanups = true;
4080
John McCallf85e1932011-06-15 23:02:42 +00004081 if (iik == IIK_okay) return;
4082
4083 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4084 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4085 << src->getSourceRange();
4086}
4087
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004088/// \brief Determine whether we have compatible array types for the
4089/// purposes of GNU by-copy array initialization.
4090static bool hasCompatibleArrayTypes(ASTContext &Context,
4091 const ArrayType *Dest,
4092 const ArrayType *Source) {
4093 // If the source and destination array types are equivalent, we're
4094 // done.
4095 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4096 return true;
4097
4098 // Make sure that the element types are the same.
4099 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4100 return false;
4101
4102 // The only mismatch we allow is when the destination is an
4103 // incomplete array type and the source is a constant array type.
4104 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4105}
4106
John McCallf85e1932011-06-15 23:02:42 +00004107static bool tryObjCWritebackConversion(Sema &S,
4108 InitializationSequence &Sequence,
4109 const InitializedEntity &Entity,
4110 Expr *Initializer) {
4111 bool ArrayDecay = false;
4112 QualType ArgType = Initializer->getType();
4113 QualType ArgPointee;
4114 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4115 ArrayDecay = true;
4116 ArgPointee = ArgArrayType->getElementType();
4117 ArgType = S.Context.getPointerType(ArgPointee);
4118 }
4119
4120 // Handle write-back conversion.
4121 QualType ConvertedArgType;
4122 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4123 ConvertedArgType))
4124 return false;
4125
4126 // We should copy unless we're passing to an argument explicitly
4127 // marked 'out'.
4128 bool ShouldCopy = true;
4129 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4130 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4131
4132 // Do we need an lvalue conversion?
4133 if (ArrayDecay || Initializer->isGLValue()) {
4134 ImplicitConversionSequence ICS;
4135 ICS.setStandard();
4136 ICS.Standard.setAsIdentityConversion();
4137
4138 QualType ResultType;
4139 if (ArrayDecay) {
4140 ICS.Standard.First = ICK_Array_To_Pointer;
4141 ResultType = S.Context.getPointerType(ArgPointee);
4142 } else {
4143 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4144 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4145 }
4146
4147 Sequence.AddConversionSequenceStep(ICS, ResultType);
4148 }
4149
4150 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4151 return true;
4152}
4153
Guy Benyei21f18c42013-02-07 10:55:47 +00004154static bool TryOCLSamplerInitialization(Sema &S,
4155 InitializationSequence &Sequence,
4156 QualType DestType,
4157 Expr *Initializer) {
4158 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4159 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4160 return false;
4161
4162 Sequence.AddOCLSamplerInitStep(DestType);
4163 return true;
4164}
4165
Guy Benyeie6b9d802013-01-20 12:31:11 +00004166//
4167// OpenCL 1.2 spec, s6.12.10
4168//
4169// The event argument can also be used to associate the
4170// async_work_group_copy with a previous async copy allowing
4171// an event to be shared by multiple async copies; otherwise
4172// event should be zero.
4173//
4174static bool TryOCLZeroEventInitialization(Sema &S,
4175 InitializationSequence &Sequence,
4176 QualType DestType,
4177 Expr *Initializer) {
4178 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4179 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4180 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4181 return false;
4182
4183 Sequence.AddOCLZeroEventStep(DestType);
4184 return true;
4185}
4186
Douglas Gregor20093b42009-12-09 23:02:17 +00004187InitializationSequence::InitializationSequence(Sema &S,
4188 const InitializedEntity &Entity,
4189 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004190 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004191 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004192 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004193
John McCall76da55d2013-04-16 07:28:30 +00004194 // Eliminate non-overload placeholder types in the arguments. We
4195 // need to do this before checking whether types are dependent
4196 // because lowering a pseudo-object expression might well give us
4197 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004198 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004199 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4200 // FIXME: should we be doing this here?
4201 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4202 if (result.isInvalid()) {
4203 SetFailed(FK_PlaceholderType);
4204 return;
4205 }
4206 Args[I] = result.take();
4207 }
4208
Douglas Gregor20093b42009-12-09 23:02:17 +00004209 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004210 // The semantics of initializers are as follows. The destination type is
4211 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004212 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004213 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004214 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004215 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004216
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004217 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004218 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004219 SequenceKind = DependentSequence;
4220 return;
4221 }
4222
Sebastian Redl7491c492011-06-05 13:59:11 +00004223 // Almost everything is a normal sequence.
4224 setSequenceKind(NormalSequence);
4225
Douglas Gregor20093b42009-12-09 23:02:17 +00004226 QualType SourceType;
4227 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004228 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004229 Initializer = Args[0];
4230 if (!isa<InitListExpr>(Initializer))
4231 SourceType = Initializer->getType();
4232 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004233
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004234 // - If the initializer is a (non-parenthesized) braced-init-list, the
4235 // object is list-initialized (8.5.4).
4236 if (Kind.getKind() != InitializationKind::IK_Direct) {
4237 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4238 TryListInitialization(S, Entity, Kind, InitList, *this);
4239 return;
4240 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004242
Douglas Gregor20093b42009-12-09 23:02:17 +00004243 // - If the destination type is a reference type, see 8.5.3.
4244 if (DestType->isReferenceType()) {
4245 // C++0x [dcl.init.ref]p1:
4246 // A variable declared to be a T& or T&&, that is, "reference to type T"
4247 // (8.3.2), shall be initialized by an object, or function, of type T or
4248 // by an object that can be converted into a T.
4249 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004250 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004251 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004252 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004253 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004254 return;
4255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004256
Douglas Gregor20093b42009-12-09 23:02:17 +00004257 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004258 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004259 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004260 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004261 return;
4262 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263
Douglas Gregor99a2e602009-12-16 01:38:02 +00004264 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004265 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004266 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004267 return;
4268 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004269
John McCallce6c9b72011-02-21 07:22:22 +00004270 // - If the destination type is an array of characters, an array of
4271 // char16_t, an array of char32_t, or an array of wchar_t, and the
4272 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004273 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004274 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004275 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004276 if (Initializer && isa<VariableArrayType>(DestAT)) {
4277 SetFailed(FK_VariableLengthArrayHasInitializer);
4278 return;
4279 }
4280
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004281 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004282 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004283 return;
4284 }
4285
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004286 // Note: as an GNU C extension, we allow initialization of an
4287 // array from a compound literal that creates an array of the same
4288 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004289 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004290 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4291 Initializer->getType()->isArrayType()) {
4292 const ArrayType *SourceAT
4293 = Context.getAsArrayType(Initializer->getType());
4294 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004295 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004296 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004297 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004298 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004299 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004300 }
Richard Smith0f163e92012-02-15 22:38:09 +00004301 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004302 // Note: as a GNU C++ extension, we allow list-initialization of a
4303 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004304 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004305 Entity.getKind() == InitializedEntity::EK_Member &&
4306 Initializer && isa<InitListExpr>(Initializer)) {
4307 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4308 *this);
4309 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004310 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004311 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004312 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004313 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314
Douglas Gregor20093b42009-12-09 23:02:17 +00004315 return;
4316 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004317
John McCallf85e1932011-06-15 23:02:42 +00004318 // Determine whether we should consider writeback conversions for
4319 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004320 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004321 Entity.getKind() == InitializedEntity::EK_Parameter;
4322
4323 // We're at the end of the line for C: it's either a write-back conversion
4324 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004325 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004326 // If allowed, check whether this is an Objective-C writeback conversion.
4327 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004328 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004329 return;
4330 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004331
4332 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4333 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004334
4335 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4336 return;
4337
John McCallf85e1932011-06-15 23:02:42 +00004338 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004339 AddCAssignmentStep(DestType);
4340 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004341 return;
4342 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004343
David Blaikie4e4d0842012-03-11 07:00:24 +00004344 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004345
Douglas Gregor20093b42009-12-09 23:02:17 +00004346 // - If the destination type is a (possibly cv-qualified) class type:
4347 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004348 // - If the initialization is direct-initialization, or if it is
4349 // copy-initialization where the cv-unqualified version of the
4350 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004351 // class of the destination, constructors are considered. [...]
4352 if (Kind.getKind() == InitializationKind::IK_Direct ||
4353 (Kind.getKind() == InitializationKind::IK_Copy &&
4354 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4355 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004356 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004357 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004358 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004359 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004360 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004361 // used) to a derived class thereof are enumerated as described in
4362 // 13.3.1.4, and the best one is chosen through overload resolution
4363 // (13.3).
4364 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004365 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004366 return;
4367 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004368
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004369 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004370 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004371 return;
4372 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004373 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004374
4375 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004376 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004377 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004378 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4379 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004380 return;
4381 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004382
Douglas Gregor20093b42009-12-09 23:02:17 +00004383 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004384 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004385 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004386 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004387 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004388
4389 ImplicitConversionSequence ICS
4390 = S.TryImplicitConversion(Initializer, Entity.getType(),
4391 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004392 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004393 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004394 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4395 allowObjCWritebackConversion);
4396
4397 if (ICS.isStandard() &&
4398 ICS.Standard.Second == ICK_Writeback_Conversion) {
4399 // Objective-C ARC writeback conversion.
4400
4401 // We should copy unless we're passing to an argument explicitly
4402 // marked 'out'.
4403 bool ShouldCopy = true;
4404 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4405 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4406
4407 // If there was an lvalue adjustment, add it as a separate conversion.
4408 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4409 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4410 ImplicitConversionSequence LvalueICS;
4411 LvalueICS.setStandard();
4412 LvalueICS.Standard.setAsIdentityConversion();
4413 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4414 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004415 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004416 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004417
4418 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004419 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004420 DeclAccessPair dap;
4421 if (Initializer->getType() == Context.OverloadTy &&
4422 !S.ResolveAddressOfOverloadedFunction(Initializer
4423 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004424 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004425 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004426 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004427 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004428 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004429
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004430 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004431 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004432}
4433
4434InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004435 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004436 StepEnd = Steps.end();
4437 Step != StepEnd; ++Step)
4438 Step->Destroy();
4439}
4440
4441//===----------------------------------------------------------------------===//
4442// Perform initialization
4443//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004444static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004445getAssignmentAction(const InitializedEntity &Entity) {
4446 switch(Entity.getKind()) {
4447 case InitializedEntity::EK_Variable:
4448 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004449 case InitializedEntity::EK_Exception:
4450 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004451 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004452 return Sema::AA_Initializing;
4453
4454 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004455 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004456 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4457 return Sema::AA_Sending;
4458
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004459 return Sema::AA_Passing;
4460
4461 case InitializedEntity::EK_Result:
4462 return Sema::AA_Returning;
4463
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004464 case InitializedEntity::EK_Temporary:
4465 // FIXME: Can we tell apart casting vs. converting?
4466 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004468 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004469 case InitializedEntity::EK_ArrayElement:
4470 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004471 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004472 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004473 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004474 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004475 return Sema::AA_Initializing;
4476 }
4477
David Blaikie7530c032012-01-17 06:56:22 +00004478 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004479}
4480
Richard Smith774d8b42013-01-08 00:08:23 +00004481/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004482/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004483static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004484 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004485 case InitializedEntity::EK_ArrayElement:
4486 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004487 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004488 case InitializedEntity::EK_New:
4489 case InitializedEntity::EK_Variable:
4490 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004491 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004492 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004493 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004494 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004495 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004496 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004497 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004498 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004500 case InitializedEntity::EK_Parameter:
4501 case InitializedEntity::EK_Temporary:
4502 return true;
4503 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004504
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004505 llvm_unreachable("missed an InitializedEntity kind?");
4506}
4507
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004508/// \brief Whether the given entity, when initialized with an object
4509/// created for that initialization, requires destruction.
4510static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4511 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004512 case InitializedEntity::EK_Result:
4513 case InitializedEntity::EK_New:
4514 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004515 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004516 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004517 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004518 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004519 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004520 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004521
Richard Smith774d8b42013-01-08 00:08:23 +00004522 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004523 case InitializedEntity::EK_Variable:
4524 case InitializedEntity::EK_Parameter:
4525 case InitializedEntity::EK_Temporary:
4526 case InitializedEntity::EK_ArrayElement:
4527 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004528 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004529 return true;
4530 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004531
4532 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004533}
4534
Richard Smith83da2e72011-10-19 16:55:56 +00004535/// \brief Look for copy and move constructors and constructor templates, for
4536/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4537static void LookupCopyAndMoveConstructors(Sema &S,
4538 OverloadCandidateSet &CandidateSet,
4539 CXXRecordDecl *Class,
4540 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004541 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004542 // The container holding the constructors can under certain conditions
4543 // be changed while iterating (e.g. because of deserialization).
4544 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004545 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004546 for (SmallVector<NamedDecl*, 16>::iterator
4547 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4548 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004549 CXXConstructorDecl *Constructor = 0;
4550
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004551 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004552 // Handle copy/moveconstructors, only.
4553 if (!Constructor || Constructor->isInvalidDecl() ||
4554 !Constructor->isCopyOrMoveConstructor() ||
4555 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4556 continue;
4557
4558 DeclAccessPair FoundDecl
4559 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4560 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004561 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004562 continue;
4563 }
4564
4565 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004566 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004567 if (ConstructorTmpl->isInvalidDecl())
4568 continue;
4569
4570 Constructor = cast<CXXConstructorDecl>(
4571 ConstructorTmpl->getTemplatedDecl());
4572 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4573 continue;
4574
4575 // FIXME: Do we need to limit this to copy-constructor-like
4576 // candidates?
4577 DeclAccessPair FoundDecl
4578 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4579 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004580 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004581 }
4582}
4583
4584/// \brief Get the location at which initialization diagnostics should appear.
4585static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4586 Expr *Initializer) {
4587 switch (Entity.getKind()) {
4588 case InitializedEntity::EK_Result:
4589 return Entity.getReturnLoc();
4590
4591 case InitializedEntity::EK_Exception:
4592 return Entity.getThrowLoc();
4593
4594 case InitializedEntity::EK_Variable:
4595 return Entity.getDecl()->getLocation();
4596
Douglas Gregor47736542012-02-15 16:57:26 +00004597 case InitializedEntity::EK_LambdaCapture:
4598 return Entity.getCaptureLoc();
4599
Richard Smith83da2e72011-10-19 16:55:56 +00004600 case InitializedEntity::EK_ArrayElement:
4601 case InitializedEntity::EK_Member:
4602 case InitializedEntity::EK_Parameter:
4603 case InitializedEntity::EK_Temporary:
4604 case InitializedEntity::EK_New:
4605 case InitializedEntity::EK_Base:
4606 case InitializedEntity::EK_Delegating:
4607 case InitializedEntity::EK_VectorElement:
4608 case InitializedEntity::EK_ComplexElement:
4609 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004610 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith83da2e72011-10-19 16:55:56 +00004611 return Initializer->getLocStart();
4612 }
4613 llvm_unreachable("missed an InitializedEntity kind?");
4614}
4615
Douglas Gregor523d46a2010-04-18 07:40:54 +00004616/// \brief Make a (potentially elidable) temporary copy of the object
4617/// provided by the given initializer by calling the appropriate copy
4618/// constructor.
4619///
4620/// \param S The Sema object used for type-checking.
4621///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004622/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004623/// the type of the initializer expression or a superclass thereof.
4624///
James Dennett1dfbd922012-06-14 21:40:34 +00004625/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004626///
4627/// \param CurInit The initializer expression.
4628///
4629/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4630/// is permitted in C++03 (but not C++0x) when binding a reference to
4631/// an rvalue.
4632///
4633/// \returns An expression that copies the initializer expression into
4634/// a temporary object, or an error expression if a copy could not be
4635/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004636static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004637 QualType T,
4638 const InitializedEntity &Entity,
4639 ExprResult CurInit,
4640 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004641 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004642 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004643 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004644 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004645 Class = cast<CXXRecordDecl>(Record->getDecl());
4646 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004647 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004648
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004649 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004650 // When certain criteria are met, an implementation is allowed to
4651 // omit the copy/move construction of a class object, even if the
4652 // copy/move constructor and/or destructor for the object have
4653 // side effects. [...]
4654 // - when a temporary class object that has not been bound to a
4655 // reference (12.2) would be copied/moved to a class object
4656 // with the same cv-unqualified type, the copy/move operation
4657 // can be omitted by constructing the temporary object
4658 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004660 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004661 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004663 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004664 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004665 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004666
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004667 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004668 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004669 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004670
Douglas Gregorcc15f012011-01-21 19:38:21 +00004671 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004672 // Only consider constructors and constructor templates. Per
4673 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4674 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004675 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004676 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004678 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4679
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004680 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004681 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004682 case OR_Success:
4683 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004684
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004685 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004686 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4687 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4688 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004689 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004690 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004691 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004692 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004693 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004694 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004695
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004696 case OR_Ambiguous:
4697 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004698 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004699 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004700 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004701 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004702
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004703 case OR_Deleted:
4704 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004705 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004706 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004707 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004708 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004709 }
4710
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004711 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004712 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004713 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004714
Anders Carlsson9a68a672010-04-21 18:47:17 +00004715 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004716 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004717
4718 if (IsExtraneousCopy) {
4719 // If this is a totally extraneous copy for C++03 reference
4720 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004721 // expression. We don't generate an (elided) copy operation here
4722 // because doing so would require us to pass down a flag to avoid
4723 // infinite recursion, where each step adds another extraneous,
4724 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004725
Douglas Gregor2559a702010-04-18 07:57:34 +00004726 // Instantiate the default arguments of any extra parameters in
4727 // the selected copy constructor, as if we were going to create a
4728 // proper call to the copy constructor.
4729 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4730 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4731 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004732 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004733 break;
4734
4735 // Build the default argument expression; we don't actually care
4736 // if this succeeds or not, because this routine will complain
4737 // if there was a problem.
4738 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4739 }
4740
Douglas Gregor523d46a2010-04-18 07:40:54 +00004741 return S.Owned(CurInitExpr);
4742 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004743
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004744 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004745 // constructor call (we might have derived-to-base conversions, or
4746 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004747 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004748 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004749
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004750 // Actually perform the constructor call.
4751 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004752 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004753 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004754 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004755 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004756 CXXConstructExpr::CK_Complete,
4757 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004758
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004759 // If we're supposed to bind temporaries, do so.
4760 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4761 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004762 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004763}
Douglas Gregor20093b42009-12-09 23:02:17 +00004764
Richard Smith83da2e72011-10-19 16:55:56 +00004765/// \brief Check whether elidable copy construction for binding a reference to
4766/// a temporary would have succeeded if we were building in C++98 mode, for
4767/// -Wc++98-compat.
4768static void CheckCXX98CompatAccessibleCopy(Sema &S,
4769 const InitializedEntity &Entity,
4770 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004771 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004772
4773 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4774 if (!Record)
4775 return;
4776
4777 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4778 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4779 == DiagnosticsEngine::Ignored)
4780 return;
4781
4782 // Find constructors which would have been considered.
4783 OverloadCandidateSet CandidateSet(Loc);
4784 LookupCopyAndMoveConstructors(
4785 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4786
4787 // Perform overload resolution.
4788 OverloadCandidateSet::iterator Best;
4789 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4790
4791 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4792 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4793 << CurInitExpr->getSourceRange();
4794
4795 switch (OR) {
4796 case OR_Success:
4797 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004798 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004799 // FIXME: Check default arguments as far as that's possible.
4800 break;
4801
4802 case OR_No_Viable_Function:
4803 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004804 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004805 break;
4806
4807 case OR_Ambiguous:
4808 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004809 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004810 break;
4811
4812 case OR_Deleted:
4813 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004814 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004815 break;
4816 }
4817}
4818
Douglas Gregora41a8c52010-04-22 00:20:18 +00004819void InitializationSequence::PrintInitLocationNote(Sema &S,
4820 const InitializedEntity &Entity) {
4821 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4822 if (Entity.getDecl()->getLocation().isInvalid())
4823 return;
4824
4825 if (Entity.getDecl()->getDeclName())
4826 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4827 << Entity.getDecl()->getDeclName();
4828 else
4829 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4830 }
4831}
4832
Sebastian Redl3b802322011-07-14 19:07:55 +00004833static bool isReferenceBinding(const InitializationSequence::Step &s) {
4834 return s.Kind == InitializationSequence::SK_BindReference ||
4835 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4836}
4837
Jordan Rose2624b812013-05-06 16:48:12 +00004838/// Returns true if the parameters describe a constructor initialization of
4839/// an explicit temporary object, e.g. "Point(x, y)".
4840static bool isExplicitTemporary(const InitializedEntity &Entity,
4841 const InitializationKind &Kind,
4842 unsigned NumArgs) {
4843 switch (Entity.getKind()) {
4844 case InitializedEntity::EK_Temporary:
4845 case InitializedEntity::EK_CompoundLiteralInit:
4846 break;
4847 default:
4848 return false;
4849 }
4850
4851 switch (Kind.getKind()) {
4852 case InitializationKind::IK_DirectList:
4853 return true;
4854 // FIXME: Hack to work around cast weirdness.
4855 case InitializationKind::IK_Direct:
4856 case InitializationKind::IK_Value:
4857 return NumArgs != 1;
4858 default:
4859 return false;
4860 }
4861}
4862
Sebastian Redl10f04a62011-12-22 14:44:04 +00004863static ExprResult
4864PerformConstructorInitialization(Sema &S,
4865 const InitializedEntity &Entity,
4866 const InitializationKind &Kind,
4867 MultiExprArg Args,
4868 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004869 bool &ConstructorInitRequiresZeroInit,
4870 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004871 unsigned NumArgs = Args.size();
4872 CXXConstructorDecl *Constructor
4873 = cast<CXXConstructorDecl>(Step.Function.Function);
4874 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4875
4876 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004877 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004878 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4879 ? Kind.getEqualLoc()
4880 : Kind.getLocation();
4881
4882 if (Kind.getKind() == InitializationKind::IK_Default) {
4883 // Force even a trivial, implicit default constructor to be
4884 // semantically checked. We do this explicitly because we don't build
4885 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004886 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004887 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004888 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004889 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4890 }
4891
4892 ExprResult CurInit = S.Owned((Expr *)0);
4893
Douglas Gregored878af2012-02-24 23:56:31 +00004894 // C++ [over.match.copy]p1:
4895 // - When initializing a temporary to be bound to the first parameter
4896 // of a constructor that takes a reference to possibly cv-qualified
4897 // T as its first argument, called with a single argument in the
4898 // context of direct-initialization, explicit conversion functions
4899 // are also considered.
4900 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4901 Args.size() == 1 &&
4902 Constructor->isCopyOrMoveConstructor();
4903
Sebastian Redl10f04a62011-12-22 14:44:04 +00004904 // Determine the arguments required to actually perform the constructor
4905 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004906 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004907 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004908 AllowExplicitConv,
4909 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004910 return ExprError();
4911
4912
Jordan Rose2624b812013-05-06 16:48:12 +00004913 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004914 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004915 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00004916 if (S.DiagnoseUseOfDecl(Constructor, Loc))
4917 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004918
4919 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4920 if (!TSInfo)
4921 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004922 SourceRange ParenRange;
4923 if (Kind.getKind() != InitializationKind::IK_DirectList)
4924 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004925
Richard Smithc83c2302012-12-19 01:39:02 +00004926 CurInit = S.Owned(
4927 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4928 TSInfo, ConstructorArgs,
4929 ParenRange, IsListInitialization,
4930 HadMultipleCandidates,
4931 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00004932 } else {
4933 CXXConstructExpr::ConstructionKind ConstructKind =
4934 CXXConstructExpr::CK_Complete;
4935
4936 if (Entity.getKind() == InitializedEntity::EK_Base) {
4937 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4938 CXXConstructExpr::CK_VirtualBase :
4939 CXXConstructExpr::CK_NonVirtualBase;
4940 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4941 ConstructKind = CXXConstructExpr::CK_Delegating;
4942 }
4943
4944 // Only get the parenthesis range if it is a direct construction.
4945 SourceRange parenRange =
4946 Kind.getKind() == InitializationKind::IK_Direct ?
4947 Kind.getParenRange() : SourceRange();
4948
4949 // If the entity allows NRVO, mark the construction as elidable
4950 // unconditionally.
4951 if (Entity.allowsNRVO())
4952 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4953 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004954 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004955 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004956 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004957 ConstructorInitRequiresZeroInit,
4958 ConstructKind,
4959 parenRange);
4960 else
4961 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4962 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004963 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004964 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004965 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004966 ConstructorInitRequiresZeroInit,
4967 ConstructKind,
4968 parenRange);
4969 }
4970 if (CurInit.isInvalid())
4971 return ExprError();
4972
4973 // Only check access if all of that succeeded.
4974 S.CheckConstructorAccess(Loc, Constructor, Entity,
4975 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00004976 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
4977 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004978
4979 if (shouldBindAsTemporary(Entity))
4980 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4981
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004982 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004983}
4984
Richard Smith36d02af2012-06-04 22:27:30 +00004985/// Determine whether the specified InitializedEntity definitely has a lifetime
4986/// longer than the current full-expression. Conservatively returns false if
4987/// it's unclear.
4988static bool
4989InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4990 const InitializedEntity *Top = &Entity;
4991 while (Top->getParent())
4992 Top = Top->getParent();
4993
4994 switch (Top->getKind()) {
4995 case InitializedEntity::EK_Variable:
4996 case InitializedEntity::EK_Result:
4997 case InitializedEntity::EK_Exception:
4998 case InitializedEntity::EK_Member:
4999 case InitializedEntity::EK_New:
5000 case InitializedEntity::EK_Base:
5001 case InitializedEntity::EK_Delegating:
5002 return true;
5003
5004 case InitializedEntity::EK_ArrayElement:
5005 case InitializedEntity::EK_VectorElement:
5006 case InitializedEntity::EK_BlockElement:
5007 case InitializedEntity::EK_ComplexElement:
5008 // Could not determine what the full initialization is. Assume it might not
5009 // outlive the full-expression.
5010 return false;
5011
5012 case InitializedEntity::EK_Parameter:
5013 case InitializedEntity::EK_Temporary:
5014 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005015 case InitializedEntity::EK_CompoundLiteralInit:
Richard Smith36d02af2012-06-04 22:27:30 +00005016 // The entity being initialized might not outlive the full-expression.
5017 return false;
5018 }
5019
5020 llvm_unreachable("unknown entity kind");
5021}
5022
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005023ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005024InitializationSequence::Perform(Sema &S,
5025 const InitializedEntity &Entity,
5026 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005027 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005028 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005029 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005030 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005031 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005032 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005033
Sebastian Redl7491c492011-06-05 13:59:11 +00005034 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005035 // If the declaration is a non-dependent, incomplete array type
5036 // that has an initializer, then its type will be completed once
5037 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005038 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005039 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005040 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005041 if (const IncompleteArrayType *ArrayT
5042 = S.Context.getAsIncompleteArrayType(DeclType)) {
5043 // FIXME: We don't currently have the ability to accurately
5044 // compute the length of an initializer list without
5045 // performing full type-checking of the initializer list
5046 // (since we have to determine where braces are implicitly
5047 // introduced and such). So, we fall back to making the array
5048 // type a dependently-sized array type with no specified
5049 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005050 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005051 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005052
Douglas Gregord87b61f2009-12-10 17:56:55 +00005053 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005054 if (DeclaratorDecl *DD = Entity.getDecl()) {
5055 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5056 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005057 if (IncompleteArrayTypeLoc ArrayLoc =
5058 TL.getAs<IncompleteArrayTypeLoc>())
5059 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005060 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005061 }
5062
5063 *ResultType
5064 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5065 /*NumElts=*/0,
5066 ArrayT->getSizeModifier(),
5067 ArrayT->getIndexTypeCVRQualifiers(),
5068 Brackets);
5069 }
5070
5071 }
5072 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005073 if (Kind.getKind() == InitializationKind::IK_Direct &&
5074 !Kind.isExplicitCast()) {
5075 // Rebuild the ParenListExpr.
5076 SourceRange ParenRange = Kind.getParenRange();
5077 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005078 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005079 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005080 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005081 Kind.isExplicitCast() ||
5082 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005083 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005084 }
5085
Sebastian Redl7491c492011-06-05 13:59:11 +00005086 // No steps means no initialization.
5087 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005088 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005089
Richard Smith80ad52f2013-01-02 11:42:31 +00005090 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005091 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005092 Entity.getKind() != InitializedEntity::EK_Parameter) {
5093 // Produce a C++98 compatibility warning if we are initializing a reference
5094 // from an initializer list. For parameters, we produce a better warning
5095 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005096 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005097 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5098 << Init->getSourceRange();
5099 }
5100
Richard Smith36d02af2012-06-04 22:27:30 +00005101 // Diagnose cases where we initialize a pointer to an array temporary, and the
5102 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005103 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005104 Entity.getType()->isPointerType() &&
5105 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005106 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005107 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5108 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5109 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5110 << Init->getSourceRange();
5111 }
5112
Douglas Gregord6542d82009-12-22 15:35:07 +00005113 QualType DestType = Entity.getType().getNonReferenceType();
5114 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005115 // the same as Entity.getDecl()->getType() in cases involving type merging,
5116 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005117 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005118 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005119 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005120
John McCall60d7b3a2010-08-24 06:29:42 +00005121 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005122
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005123 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005124 // grab the only argument out the Args and place it into the "current"
5125 // initializer.
5126 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005127 case SK_ResolveAddressOfOverloadedFunction:
5128 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005129 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005130 case SK_CastDerivedToBaseLValue:
5131 case SK_BindReference:
5132 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005133 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005134 case SK_UserConversion:
5135 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005136 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005137 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005138 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005139 case SK_ConversionSequence:
5140 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005141 case SK_UnwrapInitList:
5142 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005143 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005144 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005145 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005146 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005147 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005148 case SK_PassByIndirectCopyRestore:
5149 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005150 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005151 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005152 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005153 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005154 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005155 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005156 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005157 break;
John McCallf6a16482010-12-04 03:47:34 +00005158 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005159
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005160 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005161 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005162 case SK_ZeroInitialization:
5163 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005164 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005165
5166 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005167 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005168 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005169 for (step_iterator Step = step_begin(), StepEnd = step_end();
5170 Step != StepEnd; ++Step) {
5171 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005172 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005173
John Wiegley429bb272011-04-08 18:41:53 +00005174 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005175
Douglas Gregor20093b42009-12-09 23:02:17 +00005176 switch (Step->Kind) {
5177 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005178 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005179 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005180 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005181 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5182 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005183 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005184 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005185 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005186 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005187
Douglas Gregor20093b42009-12-09 23:02:17 +00005188 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005189 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005190 case SK_CastDerivedToBaseLValue: {
5191 // We have a derived-to-base cast that produces either an rvalue or an
5192 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005193
John McCallf871d0c2010-08-07 06:22:56 +00005194 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005195
Douglas Gregor20093b42009-12-09 23:02:17 +00005196 // Casts to inaccessible base classes are allowed with C-style casts.
5197 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5198 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005199 CurInit.get()->getLocStart(),
5200 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005201 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005202 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005203
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005204 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5205 QualType T = SourceType;
5206 if (const PointerType *Pointer = T->getAs<PointerType>())
5207 T = Pointer->getPointeeType();
5208 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005209 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005210 cast<CXXRecordDecl>(RecordTy->getDecl()));
5211 }
5212
John McCall5baba9d2010-08-25 10:28:54 +00005213 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005214 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005215 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005216 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005217 VK_XValue :
5218 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005219 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5220 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005221 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005222 CurInit.get(),
5223 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005224 break;
5225 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005226
Douglas Gregor20093b42009-12-09 23:02:17 +00005227 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00005228 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005229 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
5230 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005231 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005232 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00005233 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00005234 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00005235 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005236 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005237
John Wiegley429bb272011-04-08 18:41:53 +00005238 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005239 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005240 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5241 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005242 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005243 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005244 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005245 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005246
Douglas Gregor20093b42009-12-09 23:02:17 +00005247 // Reference binding does not have any corresponding ASTs.
5248
5249 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005250 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005251 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005252
Douglas Gregor20093b42009-12-09 23:02:17 +00005253 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005254
Douglas Gregor20093b42009-12-09 23:02:17 +00005255 case SK_BindReferenceToTemporary:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005256 // Make sure the "temporary" is actually an rvalue.
5257 assert(CurInit.get()->isRValue() && "not a temporary");
5258
Douglas Gregor20093b42009-12-09 23:02:17 +00005259 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005260 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005261 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005262
Douglas Gregor03e80032011-06-21 17:03:29 +00005263 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005264 CurInit = new (S.Context) MaterializeTemporaryExpr(
5265 Entity.getType().getNonReferenceType(),
5266 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005267 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005268
5269 // If we're binding to an Objective-C object that has lifetime, we
5270 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005271 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005272 CurInit.get()->getType()->isObjCLifetimeType())
5273 S.ExprNeedsCleanups = true;
5274
Douglas Gregor20093b42009-12-09 23:02:17 +00005275 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005276
Douglas Gregor523d46a2010-04-18 07:40:54 +00005277 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005278 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005279 /*IsExtraneousCopy=*/true);
5280 break;
5281
Douglas Gregor20093b42009-12-09 23:02:17 +00005282 case SK_UserConversion: {
5283 // We have a user-defined conversion that invokes either a constructor
5284 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005285 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005286 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005287 FunctionDecl *Fn = Step->Function.Function;
5288 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005289 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005290 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005291 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005292 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005293 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005294 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005295 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005296
Douglas Gregor20093b42009-12-09 23:02:17 +00005297 // Determine the arguments required to actually perform the constructor
5298 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005299 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005300 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005301 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005302 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005303 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005304
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005305 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005306 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005307 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005308 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005309 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005310 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005311 CXXConstructExpr::CK_Complete,
5312 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005313 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005314 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005315
Anders Carlsson9a68a672010-04-21 18:47:17 +00005316 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005317 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005318 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5319 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005320
John McCall2de56d12010-08-25 11:45:40 +00005321 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005322 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5323 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5324 S.IsDerivedFrom(SourceType, Class))
5325 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005326
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005327 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005328 } else {
5329 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005330 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005331 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005332 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005333 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5334 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005335
5336 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005337 // derived-to-base conversion? I believe the answer is "no", because
5338 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005339 ExprResult CurInitExprRes =
5340 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5341 FoundFn, Conversion);
5342 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005343 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005344 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005345
Douglas Gregor20093b42009-12-09 23:02:17 +00005346 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005347 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5348 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005349 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005350 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005351
John McCall2de56d12010-08-25 11:45:40 +00005352 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005353
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005354 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005355 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005356
Sebastian Redl3b802322011-07-14 19:07:55 +00005357 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005358 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5359
5360 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005361 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005362 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005363 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005364 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005365 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005366 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005367 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005368 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5369 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005370 }
5371 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005372
John McCallf871d0c2010-08-07 06:22:56 +00005373 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005374 CurInit.get()->getType(),
5375 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005376 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005377 if (MaybeBindToTemp)
5378 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005379 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005380 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005381 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005382 break;
5383 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005384
Douglas Gregor20093b42009-12-09 23:02:17 +00005385 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005386 case SK_QualificationConversionXValue:
5387 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005388 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005389 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005390 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005391 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005392 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005393 VK_XValue :
5394 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005395 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005396 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005397 }
5398
Jordan Rose1fd1e282013-04-11 00:58:58 +00005399 case SK_LValueToRValue: {
5400 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5401 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5402 CK_LValueToRValue,
5403 CurInit.take(),
5404 /*BasePath=*/0,
5405 VK_RValue));
5406 break;
5407 }
5408
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005409 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005410 Sema::CheckedConversionKind CCK
5411 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5412 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005413 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005414 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005415 ExprResult CurInitExprRes =
5416 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005417 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005418 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005419 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005420 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005421 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005422 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005423
Douglas Gregord87b61f2009-12-10 17:56:55 +00005424 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005425 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005426 // Hack: We must pass *ResultType if available in order to set the type
5427 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5428 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5429 // temporary, not a reference, so we should pass Ty.
5430 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5431 // Since this step is never used for a reference directly, we explicitly
5432 // unwrap references here and rewrap them afterwards.
5433 // We also need to create a InitializeTemporary entity for this.
5434 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005435 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005436 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005437 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5438 InitListChecker PerformInitList(S, InitEntity,
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005439 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005440 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00005441 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005442 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005443 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005444
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005445 if (ResultType) {
5446 if ((*ResultType)->isRValueReferenceType())
5447 Ty = S.Context.getRValueReferenceType(Ty);
5448 else if ((*ResultType)->isLValueReferenceType())
5449 Ty = S.Context.getLValueReferenceType(Ty,
5450 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5451 *ResultType = Ty;
5452 }
5453
5454 InitListExpr *StructuredInitList =
5455 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005456 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005457 CurInit = shouldBindAsTemporary(InitEntity)
5458 ? S.MaybeBindToTemporary(StructuredInitList)
5459 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005460 break;
5461 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005462
Sebastian Redl10f04a62011-12-22 14:44:04 +00005463 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005464 // When an initializer list is passed for a parameter of type "reference
5465 // to object", we don't get an EK_Temporary entity, but instead an
5466 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005467 // FIXME: This is a hack. What we really should do is create a user
5468 // conversion step for this case, but this makes it considerably more
5469 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005470 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5471 Entity.getType().getNonReferenceType());
5472 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005473 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005474 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005475 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5476 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005477 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005478 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5479 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005480 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005481 ConstructorInitRequiresZeroInit,
5482 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005483 break;
5484 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005485
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005486 case SK_UnwrapInitList:
5487 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5488 break;
5489
5490 case SK_RewrapInitList: {
5491 Expr *E = CurInit.take();
5492 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5493 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005494 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005495 ILE->setSyntacticForm(Syntactic);
5496 ILE->setType(E->getType());
5497 ILE->setValueKind(E->getValueKind());
5498 CurInit = S.Owned(ILE);
5499 break;
5500 }
5501
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005502 case SK_ConstructorInitialization: {
5503 // When an initializer list is passed for a parameter of type "reference
5504 // to object", we don't get an EK_Temporary entity, but instead an
5505 // EK_Parameter entity with reference type.
5506 // FIXME: This is a hack. What we really should do is create a user
5507 // conversion step for this case, but this makes it considerably more
5508 // complicated. For now, this will do.
5509 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5510 Entity.getType().getNonReferenceType());
5511 bool UseTemporary = Entity.getType()->isReferenceType();
5512 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5513 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005514 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005515 ConstructorInitRequiresZeroInit,
5516 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005517 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005518 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005519
Douglas Gregor71d17402009-12-15 00:01:57 +00005520 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005521 step_iterator NextStep = Step;
5522 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005523 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005524 (NextStep->Kind == SK_ConstructorInitialization ||
5525 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005526 // The need for zero-initialization is recorded directly into
5527 // the call to the object's constructor within the next step.
5528 ConstructorInitRequiresZeroInit = true;
5529 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005530 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005531 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005532 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5533 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005534 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005535 Kind.getRange().getBegin());
5536
5537 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5538 TSInfo->getType().getNonLValueExprType(S.Context),
5539 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005540 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005541 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005542 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005543 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005544 break;
5545 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005546
5547 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005548 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005549 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005550 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005551 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5552 if (Result.isInvalid())
5553 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005554 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005555
5556 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005557 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005558 if (ConvTy != Sema::Compatible &&
5559 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005560 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005561 == Sema::Compatible)
5562 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005563 if (CurInitExprRes.isInvalid())
5564 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005565 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005566
Douglas Gregora41a8c52010-04-22 00:20:18 +00005567 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005568 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5569 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005570 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005571 getAssignmentAction(Entity),
5572 &Complained)) {
5573 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005574 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005575 } else if (Complained)
5576 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005577 break;
5578 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005579
5580 case SK_StringInit: {
5581 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005582 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005583 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005584 break;
5585 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005586
5587 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005588 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005589 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005590 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005591 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005592
5593 case SK_ArrayInit:
5594 // Okay: we checked everything before creating this step. Note that
5595 // this is a GNU extension.
5596 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005597 << Step->Type << CurInit.get()->getType()
5598 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005599
5600 // If the destination type is an incomplete array type, update the
5601 // type accordingly.
5602 if (ResultType) {
5603 if (const IncompleteArrayType *IncompleteDest
5604 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5605 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005606 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005607 *ResultType = S.Context.getConstantArrayType(
5608 IncompleteDest->getElementType(),
5609 ConstantSource->getSize(),
5610 ArrayType::Normal, 0);
5611 }
5612 }
5613 }
John McCallf85e1932011-06-15 23:02:42 +00005614 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005615
Richard Smith0f163e92012-02-15 22:38:09 +00005616 case SK_ParenthesizedArrayInit:
5617 // Okay: we checked everything before creating this step. Note that
5618 // this is a GNU extension.
5619 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5620 << CurInit.get()->getSourceRange();
5621 break;
5622
John McCallf85e1932011-06-15 23:02:42 +00005623 case SK_PassByIndirectCopyRestore:
5624 case SK_PassByIndirectRestore:
5625 checkIndirectCopyRestoreSource(S, CurInit.get());
5626 CurInit = S.Owned(new (S.Context)
5627 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5628 Step->Kind == SK_PassByIndirectCopyRestore));
5629 break;
5630
5631 case SK_ProduceObjCObject:
5632 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005633 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005634 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005635 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005636
5637 case SK_StdInitializerList: {
5638 QualType Dest = Step->Type;
5639 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005640 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005641 (void)Success;
5642 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005643
5644 // If the element type has a destructor, check it.
5645 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5646 if (!RD->hasIrrelevantDestructor()) {
5647 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5648 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5649 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5650 S.PDiag(diag::err_access_dtor_temp) << E);
Richard Smith82f145d2013-05-04 06:44:46 +00005651 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5652 return ExprError();
Sebastian Redl28357452012-03-05 19:35:43 +00005653 }
5654 }
5655 }
5656
Sebastian Redl2b916b82012-01-17 22:49:42 +00005657 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005658 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5659 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005660 unsigned NumInits = ILE->getNumInits();
5661 SmallVector<Expr*, 16> Converted(NumInits);
5662 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5663 S.Context.getConstantArrayType(E,
5664 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5665 NumInits),
5666 ArrayType::Normal, 0));
5667 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5668 0, HiddenArray);
5669 for (unsigned i = 0; i < NumInits; ++i) {
5670 Element.setElementIndex(i);
5671 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005672 ExprResult Res = S.PerformCopyInitialization(
5673 Element, Init.get()->getExprLoc(), Init,
5674 /*TopLevelOfInitList=*/ true);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005675 assert(!Res.isInvalid() && "Result changed since try phase.");
5676 Converted[i] = Res.take();
5677 }
5678 InitListExpr *Semantic = new (S.Context)
5679 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005680 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005681 Semantic->setSyntacticForm(ILE);
5682 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005683 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005684 CurInit = S.Owned(Semantic);
5685 break;
5686 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005687 case SK_OCLSamplerInit: {
5688 assert(Step->Type->isSamplerT() &&
5689 "Sampler initialization on non sampler type.");
5690
5691 QualType SourceType = CurInit.get()->getType();
5692 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5693
5694 if (EntityKind == InitializedEntity::EK_Parameter) {
5695 if (!SourceType->isSamplerT())
5696 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5697 << SourceType;
5698 } else if (EntityKind != InitializedEntity::EK_Variable) {
5699 llvm_unreachable("Invalid EntityKind!");
5700 }
5701
5702 break;
5703 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005704 case SK_OCLZeroEvent: {
5705 assert(Step->Type->isEventT() &&
5706 "Event initialization on non event type.");
5707
5708 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5709 CK_ZeroToOCLEvent,
5710 CurInit.get()->getValueKind());
5711 break;
5712 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005713 }
5714 }
John McCall15d7d122010-11-11 03:21:53 +00005715
5716 // Diagnose non-fatal problems with the completed initialization.
5717 if (Entity.getKind() == InitializedEntity::EK_Member &&
5718 cast<FieldDecl>(Entity.getDecl())->isBitField())
5719 S.CheckBitFieldInitialization(Kind.getLocation(),
5720 cast<FieldDecl>(Entity.getDecl()),
5721 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005722
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005723 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005724}
5725
Richard Smithd5bc8672012-12-08 02:01:17 +00005726/// Somewhere within T there is an uninitialized reference subobject.
5727/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005728static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5729 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005730 if (T->isReferenceType()) {
5731 S.Diag(Loc, diag::err_reference_without_init)
5732 << T.getNonReferenceType();
5733 return true;
5734 }
5735
5736 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5737 if (!RD || !RD->hasUninitializedReferenceMember())
5738 return false;
5739
5740 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5741 FE = RD->field_end(); FI != FE; ++FI) {
5742 if (FI->isUnnamedBitfield())
5743 continue;
5744
5745 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5746 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5747 return true;
5748 }
5749 }
5750
5751 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5752 BE = RD->bases_end();
5753 BI != BE; ++BI) {
5754 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5755 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5756 return true;
5757 }
5758 }
5759
5760 return false;
5761}
5762
5763
Douglas Gregor20093b42009-12-09 23:02:17 +00005764//===----------------------------------------------------------------------===//
5765// Diagnose initialization failures
5766//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00005767
5768/// Emit notes associated with an initialization that failed due to a
5769/// "simple" conversion failure.
5770static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5771 Expr *op) {
5772 QualType destType = entity.getType();
5773 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5774 op->getType()->isObjCObjectPointerType()) {
5775
5776 // Emit a possible note about the conversion failing because the
5777 // operand is a message send with a related result type.
5778 S.EmitRelatedResultTypeNote(op);
5779
5780 // Emit a possible note about a return failing because we're
5781 // expecting a related result type.
5782 if (entity.getKind() == InitializedEntity::EK_Result)
5783 S.EmitRelatedResultTypeNoteForReturn(destType);
5784 }
5785}
5786
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005787bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005788 const InitializedEntity &Entity,
5789 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005790 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005791 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005792 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005793
Douglas Gregord6542d82009-12-22 15:35:07 +00005794 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005795 switch (Failure) {
5796 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005797 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005798 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005799 // Dig out the reference subobject which is uninitialized and diagnose it.
5800 // If this is value-initialization, this could be nested some way within
5801 // the target type.
5802 assert(Kind.getKind() == InitializationKind::IK_Value ||
5803 DestType->isReferenceType());
5804 bool Diagnosed =
5805 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5806 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5807 (void)Diagnosed;
5808 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005809 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005810 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005811 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005812
Douglas Gregor20093b42009-12-09 23:02:17 +00005813 case FK_ArrayNeedsInitList:
5814 case FK_ArrayNeedsInitListOrStringLiteral:
5815 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5816 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5817 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005818
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005819 case FK_ArrayTypeMismatch:
5820 case FK_NonConstantArrayInit:
5821 S.Diag(Kind.getLocation(),
5822 (Failure == FK_ArrayTypeMismatch
5823 ? diag::err_array_init_different_type
5824 : diag::err_array_init_non_constant_array))
5825 << DestType.getNonReferenceType()
5826 << Args[0]->getType()
5827 << Args[0]->getSourceRange();
5828 break;
5829
John McCall73076432012-01-05 00:13:19 +00005830 case FK_VariableLengthArrayHasInitializer:
5831 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5832 << Args[0]->getSourceRange();
5833 break;
5834
John McCall6bb80172010-03-30 21:47:33 +00005835 case FK_AddressOfOverloadFailed: {
5836 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005837 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005838 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005839 true,
5840 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005841 break;
John McCall6bb80172010-03-30 21:47:33 +00005842 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005843
Douglas Gregor20093b42009-12-09 23:02:17 +00005844 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005845 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005846 switch (FailedOverloadResult) {
5847 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005848 if (Failure == FK_UserConversionOverloadFailed)
5849 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5850 << Args[0]->getType() << DestType
5851 << Args[0]->getSourceRange();
5852 else
5853 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5854 << DestType << Args[0]->getType()
5855 << Args[0]->getSourceRange();
5856
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005857 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005858 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005859
Douglas Gregor20093b42009-12-09 23:02:17 +00005860 case OR_No_Viable_Function:
5861 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5862 << Args[0]->getType() << DestType.getNonReferenceType()
5863 << Args[0]->getSourceRange();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005864 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005865 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005866
Douglas Gregor20093b42009-12-09 23:02:17 +00005867 case OR_Deleted: {
5868 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5869 << Args[0]->getType() << DestType.getNonReferenceType()
5870 << Args[0]->getSourceRange();
5871 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005872 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005873 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5874 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005875 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005876 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005877 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005878 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005879 }
5880 break;
5881 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005882
Douglas Gregor20093b42009-12-09 23:02:17 +00005883 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005884 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005885 }
5886 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005887
Douglas Gregor20093b42009-12-09 23:02:17 +00005888 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005889 if (isa<InitListExpr>(Args[0])) {
5890 S.Diag(Kind.getLocation(),
5891 diag::err_lvalue_reference_bind_to_initlist)
5892 << DestType.getNonReferenceType().isVolatileQualified()
5893 << DestType.getNonReferenceType()
5894 << Args[0]->getSourceRange();
5895 break;
5896 }
5897 // Intentional fallthrough
5898
Douglas Gregor20093b42009-12-09 23:02:17 +00005899 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005900 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005901 Failure == FK_NonConstLValueReferenceBindingToTemporary
5902 ? diag::err_lvalue_reference_bind_to_temporary
5903 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005904 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005905 << DestType.getNonReferenceType()
5906 << Args[0]->getType()
5907 << Args[0]->getSourceRange();
5908 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005909
Douglas Gregor20093b42009-12-09 23:02:17 +00005910 case FK_RValueReferenceBindingToLValue:
5911 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005912 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005913 << Args[0]->getSourceRange();
5914 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005915
Douglas Gregor20093b42009-12-09 23:02:17 +00005916 case FK_ReferenceInitDropsQualifiers:
5917 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5918 << DestType.getNonReferenceType()
5919 << Args[0]->getType()
5920 << Args[0]->getSourceRange();
5921 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005922
Douglas Gregor20093b42009-12-09 23:02:17 +00005923 case FK_ReferenceInitFailed:
5924 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5925 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005926 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005927 << Args[0]->getType()
5928 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00005929 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005930 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005931
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005932 case FK_ConversionFailed: {
5933 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005934 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005935 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005936 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005937 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005938 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005939 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005940 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5941 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00005942 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005943 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005944 }
John Wiegley429bb272011-04-08 18:41:53 +00005945
5946 case FK_ConversionFromPropertyFailed:
5947 // No-op. This error has already been reported.
5948 break;
5949
Douglas Gregord87b61f2009-12-10 17:56:55 +00005950 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005951 SourceRange R;
5952
5953 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005954 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005955 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005956 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005957 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005958
Douglas Gregor19311e72010-09-08 21:40:08 +00005959 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5960 if (Kind.isCStyleOrFunctionalCast())
5961 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5962 << R;
5963 else
5964 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5965 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005966 break;
5967 }
5968
5969 case FK_ReferenceBindingToInitList:
5970 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5971 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5972 break;
5973
5974 case FK_InitListBadDestinationType:
5975 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5976 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5977 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005978
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005979 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005980 case FK_ConstructorOverloadFailed: {
5981 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005982 if (Args.size())
5983 ArgsRange = SourceRange(Args.front()->getLocStart(),
5984 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005985
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005986 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005987 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005988 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005989 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005990 }
5991
Douglas Gregor51c56d62009-12-14 20:49:26 +00005992 // FIXME: Using "DestType" for the entity we're printing is probably
5993 // bad.
5994 switch (FailedOverloadResult) {
5995 case OR_Ambiguous:
5996 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5997 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005998 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005999 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006000
Douglas Gregor51c56d62009-12-14 20:49:26 +00006001 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006002 if (Kind.getKind() == InitializationKind::IK_Default &&
6003 (Entity.getKind() == InitializedEntity::EK_Base ||
6004 Entity.getKind() == InitializedEntity::EK_Member) &&
6005 isa<CXXConstructorDecl>(S.CurContext)) {
6006 // This is implicit default initialization of a member or
6007 // base within a constructor. If no viable function was
6008 // found, notify the user that she needs to explicitly
6009 // initialize this base/member.
6010 CXXConstructorDecl *Constructor
6011 = cast<CXXConstructorDecl>(S.CurContext);
6012 if (Entity.getKind() == InitializedEntity::EK_Base) {
6013 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006014 << (Constructor->getInheritedConstructor() ? 2 :
6015 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006016 << S.Context.getTypeDeclType(Constructor->getParent())
6017 << /*base=*/0
6018 << Entity.getType();
6019
6020 RecordDecl *BaseDecl
6021 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6022 ->getDecl();
6023 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6024 << S.Context.getTagDeclType(BaseDecl);
6025 } else {
6026 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006027 << (Constructor->getInheritedConstructor() ? 2 :
6028 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006029 << S.Context.getTypeDeclType(Constructor->getParent())
6030 << /*member=*/1
6031 << Entity.getName();
6032 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6033
6034 if (const RecordType *Record
6035 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006036 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006037 diag::note_previous_decl)
6038 << S.Context.getTagDeclType(Record->getDecl());
6039 }
6040 break;
6041 }
6042
Douglas Gregor51c56d62009-12-14 20:49:26 +00006043 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6044 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006045 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006046 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006047
Douglas Gregor51c56d62009-12-14 20:49:26 +00006048 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006049 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006050 OverloadingResult Ovl
6051 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006052 if (Ovl != OR_Deleted) {
6053 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6054 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006055 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006056 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006057 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006058
6059 // If this is a defaulted or implicitly-declared function, then
6060 // it was implicitly deleted. Make it clear that the deletion was
6061 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006062 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006063 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006064 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006065 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006066 else
6067 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6068 << true << DestType << ArgsRange;
6069
6070 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006071 break;
6072 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006073
Douglas Gregor51c56d62009-12-14 20:49:26 +00006074 case OR_Success:
6075 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006076 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006077 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006078 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006079
Douglas Gregor99a2e602009-12-16 01:38:02 +00006080 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006081 if (Entity.getKind() == InitializedEntity::EK_Member &&
6082 isa<CXXConstructorDecl>(S.CurContext)) {
6083 // This is implicit default-initialization of a const member in
6084 // a constructor. Complain that it needs to be explicitly
6085 // initialized.
6086 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6087 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006088 << (Constructor->getInheritedConstructor() ? 2 :
6089 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006090 << S.Context.getTypeDeclType(Constructor->getParent())
6091 << /*const=*/1
6092 << Entity.getName();
6093 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6094 << Entity.getName();
6095 } else {
6096 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6097 << DestType << (bool)DestType->getAs<RecordType>();
6098 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006099 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006100
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006101 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006102 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006103 diag::err_init_incomplete_type);
6104 break;
6105
Sebastian Redl14b0c192011-09-24 17:48:00 +00006106 case FK_ListInitializationFailed: {
6107 // Run the init list checker again to emit diagnostics.
6108 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6109 QualType DestType = Entity.getType();
6110 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00006111 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00006112 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00006113 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006114 assert(DiagnoseInitList.HadError() &&
6115 "Inconsistent init list check result.");
6116 break;
6117 }
John McCall5acb0c92011-10-17 18:40:02 +00006118
6119 case FK_PlaceholderType: {
6120 // FIXME: Already diagnosed!
6121 break;
6122 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006123
6124 case FK_InitListElementCopyFailure: {
6125 // Try to perform all copies again.
6126 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6127 unsigned NumInits = InitList->getNumInits();
6128 QualType DestType = Entity.getType();
6129 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006130 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006131 (void)Success;
6132 assert(Success && "Where did the std::initializer_list go?");
6133 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6134 S.Context.getConstantArrayType(E,
6135 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6136 NumInits),
6137 ArrayType::Normal, 0));
6138 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6139 0, HiddenArray);
6140 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6141 // where the init list type is wrong, e.g.
6142 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6143 // FIXME: Emit a note if we hit the limit?
6144 int ErrorCount = 0;
6145 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6146 Element.setElementIndex(i);
6147 ExprResult Init = S.Owned(InitList->getInit(i));
6148 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6149 .isInvalid())
6150 ++ErrorCount;
6151 }
6152 break;
6153 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006154
6155 case FK_ExplicitConstructor: {
6156 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6157 << Args[0]->getSourceRange();
6158 OverloadCandidateSet::iterator Best;
6159 OverloadingResult Ovl
6160 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006161 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006162 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6163 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6164 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6165 break;
6166 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006167 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006168
Douglas Gregora41a8c52010-04-22 00:20:18 +00006169 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006170 return true;
6171}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006172
Chris Lattner5f9e2722011-07-23 10:55:15 +00006173void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006174 switch (SequenceKind) {
6175 case FailedSequence: {
6176 OS << "Failed sequence: ";
6177 switch (Failure) {
6178 case FK_TooManyInitsForReference:
6179 OS << "too many initializers for reference";
6180 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006181
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006182 case FK_ArrayNeedsInitList:
6183 OS << "array requires initializer list";
6184 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006185
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006186 case FK_ArrayNeedsInitListOrStringLiteral:
6187 OS << "array requires initializer list or string literal";
6188 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006189
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006190 case FK_ArrayTypeMismatch:
6191 OS << "array type mismatch";
6192 break;
6193
6194 case FK_NonConstantArrayInit:
6195 OS << "non-constant array initializer";
6196 break;
6197
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006198 case FK_AddressOfOverloadFailed:
6199 OS << "address of overloaded function failed";
6200 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006201
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006202 case FK_ReferenceInitOverloadFailed:
6203 OS << "overload resolution for reference initialization failed";
6204 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006205
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006206 case FK_NonConstLValueReferenceBindingToTemporary:
6207 OS << "non-const lvalue reference bound to temporary";
6208 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006209
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006210 case FK_NonConstLValueReferenceBindingToUnrelated:
6211 OS << "non-const lvalue reference bound to unrelated type";
6212 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006213
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006214 case FK_RValueReferenceBindingToLValue:
6215 OS << "rvalue reference bound to an lvalue";
6216 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006217
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006218 case FK_ReferenceInitDropsQualifiers:
6219 OS << "reference initialization drops qualifiers";
6220 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006221
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006222 case FK_ReferenceInitFailed:
6223 OS << "reference initialization failed";
6224 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006225
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006226 case FK_ConversionFailed:
6227 OS << "conversion failed";
6228 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006229
John Wiegley429bb272011-04-08 18:41:53 +00006230 case FK_ConversionFromPropertyFailed:
6231 OS << "conversion from property failed";
6232 break;
6233
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006234 case FK_TooManyInitsForScalar:
6235 OS << "too many initializers for scalar";
6236 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006237
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006238 case FK_ReferenceBindingToInitList:
6239 OS << "referencing binding to initializer list";
6240 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006241
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006242 case FK_InitListBadDestinationType:
6243 OS << "initializer list for non-aggregate, non-scalar type";
6244 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006245
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006246 case FK_UserConversionOverloadFailed:
6247 OS << "overloading failed for user-defined conversion";
6248 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006249
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006250 case FK_ConstructorOverloadFailed:
6251 OS << "constructor overloading failed";
6252 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006253
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006254 case FK_DefaultInitOfConst:
6255 OS << "default initialization of a const variable";
6256 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006257
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006258 case FK_Incomplete:
6259 OS << "initialization of incomplete type";
6260 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006261
6262 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006263 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006264 break;
6265
John McCall73076432012-01-05 00:13:19 +00006266 case FK_VariableLengthArrayHasInitializer:
6267 OS << "variable length array has an initializer";
6268 break;
6269
John McCall5acb0c92011-10-17 18:40:02 +00006270 case FK_PlaceholderType:
6271 OS << "initializer expression isn't contextually valid";
6272 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006273
6274 case FK_ListConstructorOverloadFailed:
6275 OS << "list constructor overloading failed";
6276 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006277
6278 case FK_InitListElementCopyFailure:
6279 OS << "copy construction of initializer list element failed";
6280 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006281
6282 case FK_ExplicitConstructor:
6283 OS << "list copy initialization chose explicit constructor";
6284 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006285 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006286 OS << '\n';
6287 return;
6288 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006289
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006290 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006291 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006292 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006293
Sebastian Redl7491c492011-06-05 13:59:11 +00006294 case NormalSequence:
6295 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006296 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006297 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006298
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006299 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6300 if (S != step_begin()) {
6301 OS << " -> ";
6302 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006303
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006304 switch (S->Kind) {
6305 case SK_ResolveAddressOfOverloadedFunction:
6306 OS << "resolve address of overloaded function";
6307 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006308
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006309 case SK_CastDerivedToBaseRValue:
6310 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6311 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006312
Sebastian Redl906082e2010-07-20 04:20:21 +00006313 case SK_CastDerivedToBaseXValue:
6314 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6315 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006316
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006317 case SK_CastDerivedToBaseLValue:
6318 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6319 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006320
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006321 case SK_BindReference:
6322 OS << "bind reference to lvalue";
6323 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006324
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006325 case SK_BindReferenceToTemporary:
6326 OS << "bind reference to a temporary";
6327 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006328
Douglas Gregor523d46a2010-04-18 07:40:54 +00006329 case SK_ExtraneousCopyToTemporary:
6330 OS << "extraneous C++03 copy to temporary";
6331 break;
6332
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006333 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006334 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006335 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006336
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006337 case SK_QualificationConversionRValue:
6338 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006339 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006340
Sebastian Redl906082e2010-07-20 04:20:21 +00006341 case SK_QualificationConversionXValue:
6342 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006343 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006344
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006345 case SK_QualificationConversionLValue:
6346 OS << "qualification conversion (lvalue)";
6347 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006348
Jordan Rose1fd1e282013-04-11 00:58:58 +00006349 case SK_LValueToRValue:
6350 OS << "load (lvalue to rvalue)";
6351 break;
6352
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006353 case SK_ConversionSequence:
6354 OS << "implicit conversion sequence (";
6355 S->ICS->DebugPrint(); // FIXME: use OS
6356 OS << ")";
6357 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006358
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006359 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006360 OS << "list aggregate initialization";
6361 break;
6362
6363 case SK_ListConstructorCall:
6364 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006365 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006366
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006367 case SK_UnwrapInitList:
6368 OS << "unwrap reference initializer list";
6369 break;
6370
6371 case SK_RewrapInitList:
6372 OS << "rewrap reference initializer list";
6373 break;
6374
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006375 case SK_ConstructorInitialization:
6376 OS << "constructor initialization";
6377 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006378
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006379 case SK_ZeroInitialization:
6380 OS << "zero initialization";
6381 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006382
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006383 case SK_CAssignment:
6384 OS << "C assignment";
6385 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006386
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006387 case SK_StringInit:
6388 OS << "string initialization";
6389 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006390
6391 case SK_ObjCObjectConversion:
6392 OS << "Objective-C object conversion";
6393 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006394
6395 case SK_ArrayInit:
6396 OS << "array initialization";
6397 break;
John McCallf85e1932011-06-15 23:02:42 +00006398
Richard Smith0f163e92012-02-15 22:38:09 +00006399 case SK_ParenthesizedArrayInit:
6400 OS << "parenthesized array initialization";
6401 break;
6402
John McCallf85e1932011-06-15 23:02:42 +00006403 case SK_PassByIndirectCopyRestore:
6404 OS << "pass by indirect copy and restore";
6405 break;
6406
6407 case SK_PassByIndirectRestore:
6408 OS << "pass by indirect restore";
6409 break;
6410
6411 case SK_ProduceObjCObject:
6412 OS << "Objective-C object retension";
6413 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006414
6415 case SK_StdInitializerList:
6416 OS << "std::initializer_list from initializer list";
6417 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006418
Guy Benyei21f18c42013-02-07 10:55:47 +00006419 case SK_OCLSamplerInit:
6420 OS << "OpenCL sampler_t from integer constant";
6421 break;
6422
Guy Benyeie6b9d802013-01-20 12:31:11 +00006423 case SK_OCLZeroEvent:
6424 OS << "OpenCL event_t from zero";
6425 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006426 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006427
6428 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006429 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006430
6431 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006432}
6433
6434void InitializationSequence::dump() const {
6435 dump(llvm::errs());
6436}
6437
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006438static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6439 QualType EntityType,
6440 const Expr *PreInit,
6441 const Expr *PostInit) {
6442 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6443 return;
6444
6445 // A narrowing conversion can only appear as the final implicit conversion in
6446 // an initialization sequence.
6447 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6448 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6449 return;
6450
6451 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6452 const StandardConversionSequence *SCS = 0;
6453 switch (ICS.getKind()) {
6454 case ImplicitConversionSequence::StandardConversion:
6455 SCS = &ICS.Standard;
6456 break;
6457 case ImplicitConversionSequence::UserDefinedConversion:
6458 SCS = &ICS.UserDefined.After;
6459 break;
6460 case ImplicitConversionSequence::AmbiguousConversion:
6461 case ImplicitConversionSequence::EllipsisConversion:
6462 case ImplicitConversionSequence::BadConversion:
6463 return;
6464 }
6465
6466 // Determine the type prior to the narrowing conversion. If a conversion
6467 // operator was used, this may be different from both the type of the entity
6468 // and of the pre-initialization expression.
6469 QualType PreNarrowingType = PreInit->getType();
6470 if (Seq.step_begin() + 1 != Seq.step_end())
6471 PreNarrowingType = Seq.step_end()[-2].Type;
6472
6473 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6474 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006475 QualType ConstantType;
6476 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6477 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006478 case NK_Not_Narrowing:
6479 // No narrowing occurred.
6480 return;
6481
6482 case NK_Type_Narrowing:
6483 // This was a floating-to-integer conversion, which is always considered a
6484 // narrowing conversion even if the value is a constant and can be
6485 // represented exactly as an integer.
6486 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006487 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006488 diag::warn_init_list_type_narrowing
6489 : S.isSFINAEContext()?
6490 diag::err_init_list_type_narrowing_sfinae
6491 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006492 << PostInit->getSourceRange()
6493 << PreNarrowingType.getLocalUnqualifiedType()
6494 << EntityType.getLocalUnqualifiedType();
6495 break;
6496
6497 case NK_Constant_Narrowing:
6498 // A constant value was narrowed.
6499 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006500 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006501 diag::warn_init_list_constant_narrowing
6502 : S.isSFINAEContext()?
6503 diag::err_init_list_constant_narrowing_sfinae
6504 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006505 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006506 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006507 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006508 break;
6509
6510 case NK_Variable_Narrowing:
6511 // A variable's value may have been narrowed.
6512 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006513 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006514 diag::warn_init_list_variable_narrowing
6515 : S.isSFINAEContext()?
6516 diag::err_init_list_variable_narrowing_sfinae
6517 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006518 << PostInit->getSourceRange()
6519 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006520 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006521 break;
6522 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006523
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006524 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006525 llvm::raw_svector_ostream OS(StaticCast);
6526 OS << "static_cast<";
6527 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6528 // It's important to use the typedef's name if there is one so that the
6529 // fixit doesn't break code using types like int64_t.
6530 //
6531 // FIXME: This will break if the typedef requires qualification. But
6532 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006533 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006534 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006535 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006536 else {
6537 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6538 // with a broken cast.
6539 return;
6540 }
6541 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006542 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6543 << PostInit->getSourceRange()
6544 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006545 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006546 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006547}
6548
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006549//===----------------------------------------------------------------------===//
6550// Initialization helper functions
6551//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006552bool
6553Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6554 ExprResult Init) {
6555 if (Init.isInvalid())
6556 return false;
6557
6558 Expr *InitE = Init.get();
6559 assert(InitE && "No initialization expression");
6560
Douglas Gregor3c394c52012-07-31 22:15:04 +00006561 InitializationKind Kind
6562 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006563 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006564 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006565}
6566
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006567ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006568Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6569 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006570 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006571 bool TopLevelOfInitList,
6572 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006573 if (Init.isInvalid())
6574 return ExprError();
6575
John McCall15d7d122010-11-11 03:21:53 +00006576 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006577 assert(InitE && "No initialization expression?");
6578
6579 if (EqualLoc.isInvalid())
6580 EqualLoc = InitE->getLocStart();
6581
6582 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006583 EqualLoc,
6584 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006585 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006586 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006587
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006588 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006589
6590 if (!Result.isInvalid() && TopLevelOfInitList)
6591 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6592 InitE, Result.get());
6593
6594 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006595}