blob: 6bbbcdc17a029a8310021818d6fdce171293403f [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
John McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +000095 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000096 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000097 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ConstVal,
99 ArrayType::Normal, 0);
Richard Smithbebf5b12013-04-26 14:36:30 +0000100 Str->setType(DeclT);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000101 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedman8718a6a2009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000109 if (S.getLangOpts().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000121 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000127 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Eli Friedman8718a6a2009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137}
138
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregor9e80f722009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000170namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000176 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000177 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000200 void CheckComplexType(const InitializedEntity &Entity,
201 InitListExpr *IList, QualType DeclType,
202 unsigned &Index,
203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000243 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244 QualType CurrentObjectType,
245 InitListExpr *StructuredList,
246 unsigned StructuredIndex,
247 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000253
Douglas Gregord6d37de2009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000264public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000268 bool HadError() { return hadError; }
269
270 // @brief Retrieves the fully-structured initializer list used for
271 // semantic analysis and code generation.
272 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273};
Chris Lattner8b419b92009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000275
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000276void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277 assert(VerifyOnly &&
278 "CheckValueInitializable is only inteded for verification mode.");
279
280 SourceLocation Loc;
281 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282 true);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000283 InitializationSequence InitSeq(SemaRef, Entity, Kind, MultiExprArg());
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000284 if (InitSeq.Failed())
285 hadError = true;
286}
287
Douglas Gregord6d37de2009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000292 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000297 // If there's no explicit initializer but we have a default initializer, use
298 // that. This only happens in C++1y, since classes with default
299 // initializers are not aggregates in C++11.
300 if (Field->hasInClassInitializer()) {
301 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
302 ILE->getRBraceLoc(), Field);
303 if (Init < NumInits)
304 ILE->setInit(Init, DIE);
305 else {
306 ILE->updateInit(SemaRef.Context, Init, DIE);
307 RequiresSecondPass = true;
308 }
309 return;
310 }
311
Douglas Gregord6d37de2009-12-22 00:05:34 +0000312 // FIXME: We probably don't need to handle references
313 // specially here, since value-initialization of references is
314 // handled in InitializationSequence.
315 if (Field->getType()->isReferenceType()) {
316 // C++ [dcl.init.aggr]p9:
317 // If an incomplete or empty initializer-list leaves a
318 // member of reference type uninitialized, the program is
319 // ill-formed.
320 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
321 << Field->getType()
322 << ILE->getSyntacticForm()->getSourceRange();
323 SemaRef.Diag(Field->getLocation(),
324 diag::note_uninit_reference_member);
325 hadError = true;
326 return;
327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
330 true);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000331 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000332 if (!InitSeq) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000333 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, ArrayRef<Expr *>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000334 hadError = true;
335 return;
336 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000337
John McCall60d7b3a2010-08-24 06:29:42 +0000338 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000339 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 if (MemberInit.isInvalid()) {
341 hadError = true;
342 return;
343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000344
Douglas Gregord6d37de2009-12-22 00:05:34 +0000345 if (hadError) {
346 // Do nothing
347 } else if (Init < NumInits) {
348 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000349 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000350 // Value-initialization requires a constructor call, so
351 // extend the initializer list to include the constructor
352 // call and make a note that we'll need to take another pass
353 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000354 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000355 RequiresSecondPass = true;
356 }
357 } else if (InitListExpr *InnerILE
358 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000359 FillInValueInitializations(MemberEntity, InnerILE,
360 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000361}
362
Douglas Gregor4c678342009-01-28 21:54:33 +0000363/// Recursively replaces NULL values within the given initializer list
364/// with expressions that perform value-initialization of the
365/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000366void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000367InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
368 InitListExpr *ILE,
369 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000370 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000371 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000372 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000373 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000374 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Ted Kremenek6217b802009-07-29 21:53:49 +0000376 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000377 const RecordDecl *RDecl = RType->getDecl();
378 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000379 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
380 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-04-20 22:23:05 +0000381 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
382 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
383 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
384 FieldEnd = RDecl->field_end();
385 Field != FieldEnd; ++Field) {
386 if (Field->hasInClassInitializer()) {
387 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
388 break;
389 }
390 }
391 } else {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000392 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000393 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
394 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000395 Field != FieldEnd; ++Field) {
396 if (Field->isUnnamedBitfield())
397 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000398
Douglas Gregord6d37de2009-12-22 00:05:34 +0000399 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000400 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000401
David Blaikie581deb32012-06-06 20:45:41 +0000402 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000403 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000404 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000405
Douglas Gregord6d37de2009-12-22 00:05:34 +0000406 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000407
Douglas Gregord6d37de2009-12-22 00:05:34 +0000408 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000409 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000410 break;
411 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000412 }
413
414 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000415 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000416
417 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000419 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000420 unsigned NumInits = ILE->getNumInits();
421 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000422 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000423 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000424 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
425 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000426 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000427 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000428 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000429 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000430 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000432 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000433 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000434 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000435
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000436
Douglas Gregor87fd7032009-02-02 17:43:21 +0000437 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000438 if (hadError)
439 return;
440
Anders Carlssond3d824d2010-01-23 04:34:47 +0000441 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
442 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000443 ElementEntity.setElementIndex(Init);
444
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000445 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
446 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000447 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
448 true);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000449 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000450 if (!InitSeq) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000451 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, ArrayRef<Expr *>());
Douglas Gregor87fd7032009-02-02 17:43:21 +0000452 hadError = true;
453 return;
454 }
455
John McCall60d7b3a2010-08-24 06:29:42 +0000456 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000457 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000458 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000459 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000460 return;
461 }
462
463 if (hadError) {
464 // Do nothing
465 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000466 // For arrays, just set the expression used for value-initialization
467 // of the "holes" in the array.
468 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
469 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
470 else
471 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000472 } else {
473 // For arrays, just set the expression used for value-initialization
474 // of the rest of elements and exit.
475 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
476 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
477 return;
478 }
479
Sebastian Redl7491c492011-06-05 13:59:11 +0000480 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000481 // Value-initialization requires a constructor call, so
482 // extend the initializer list to include the constructor
483 // call and make a note that we'll need to take another pass
484 // through the initializer list.
485 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
486 RequiresSecondPass = true;
487 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000488 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000489 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000490 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000491 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000492 }
493}
494
Chris Lattner68355a52009-01-29 05:10:57 +0000495
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000496InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000497 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000498 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000499 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000500 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000501
Eli Friedmanb85f7072008-05-19 19:16:24 +0000502 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000504 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000505 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000506 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000507 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000508 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000509
Sebastian Redl14b0c192011-09-24 17:48:00 +0000510 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000511 bool RequiresSecondPass = false;
512 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000513 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000514 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000515 RequiresSecondPass);
516 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000517}
518
519int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000520 // FIXME: use a proper constant
521 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000522 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000523 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000524 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
525 }
526 return maxElements;
527}
528
529int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000530 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000531 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000532 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000533 Field = structDecl->field_begin(),
534 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000535 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000536 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000537 ++InitializableMembers;
538 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000539 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000540 return std::min(InitializableMembers, 1);
541 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000542}
543
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000544void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000545 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000546 QualType T, unsigned &Index,
547 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000548 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000549 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Steve Naroff0cca7492008-05-01 22:18:59 +0000551 if (T->isArrayType())
552 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000553 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000554 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000555 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000556 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000557 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000558 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000559
Eli Friedman402256f2008-05-25 13:49:22 +0000560 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000561 if (!VerifyOnly)
562 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
563 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000564 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000565 hadError = true;
566 return;
567 }
568
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 // Build a structured initializer list corresponding to this subobject.
570 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000571 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
572 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000573 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000574 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000576
Douglas Gregor4c678342009-01-28 21:54:33 +0000577 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000578 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000579 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000580 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000581 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000582 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000583
584 if (VerifyOnly) {
585 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
586 hadError = true;
587 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000588 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000589
Sebastian Redlc2235182011-10-16 18:19:28 +0000590 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000591 // Update the structured sub-object initializer so that it's ending
592 // range corresponds with the end of the last initializer it used.
593 if (EndIndex < ParentIList->getNumInits()) {
594 SourceLocation EndLoc
595 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
596 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
597 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598
Sebastian Redlc2235182011-10-16 18:19:28 +0000599 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000600 if (T->isArrayType() || T->isRecordType()) {
601 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000602 AllowBraceElision ? diag::warn_missing_braces :
603 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000604 << StructuredSubobjectInitList->getSourceRange()
605 << FixItHint::CreateInsertion(
606 StructuredSubobjectInitList->getLocStart(), "{")
607 << FixItHint::CreateInsertion(
608 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000610 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000611 if (!AllowBraceElision)
612 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000613 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000614 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000615}
616
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000617void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000618 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000619 unsigned &Index,
620 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000621 unsigned &StructuredIndex,
622 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000623 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000624 if (!VerifyOnly) {
625 SyntacticToSemantic[IList] = StructuredList;
626 StructuredList->setSyntacticForm(IList);
627 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000628 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000629 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000630 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000631 QualType ExprTy = T;
632 if (!ExprTy->isArrayType())
633 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000634 IList->setType(ExprTy);
635 StructuredList->setType(ExprTy);
636 }
Eli Friedman638e1442008-05-25 13:22:35 +0000637 if (hadError)
638 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000639
Eli Friedman638e1442008-05-25 13:22:35 +0000640 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000641 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000642 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000643 if (SemaRef.getLangOpts().CPlusPlus ||
644 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000645 IList->getType()->isVectorType())) {
646 hadError = true;
647 }
648 return;
649 }
650
Eli Friedmane5408582009-05-29 20:20:05 +0000651 if (StructuredIndex == 1 &&
652 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000653 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000654 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000655 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000656 hadError = true;
657 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000658 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000659 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000660 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000661 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000662 // Don't complain for incomplete types, since we'll get an error
663 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000664 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000665 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000666 CurrentObjectType->isArrayType()? 0 :
667 CurrentObjectType->isVectorType()? 1 :
668 CurrentObjectType->isScalarType()? 2 :
669 CurrentObjectType->isUnionType()? 3 :
670 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000671
672 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000673 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000674 DK = diag::err_excess_initializers;
675 hadError = true;
676 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000677 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000678 DK = diag::err_excess_initializers;
679 hadError = true;
680 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000681
Chris Lattner08202542009-02-24 22:50:46 +0000682 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000683 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000684 }
685 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000686
Sebastian Redl14b0c192011-09-24 17:48:00 +0000687 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
688 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000689 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000690 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000691 << FixItHint::CreateRemoval(IList->getLocStart())
692 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000693}
694
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000695void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000696 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000697 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000698 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000699 unsigned &Index,
700 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000701 unsigned &StructuredIndex,
702 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000703 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
704 // Explicitly braced initializer for complex type can be real+imaginary
705 // parts.
706 CheckComplexType(Entity, IList, DeclType, Index,
707 StructuredList, StructuredIndex);
708 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000709 CheckScalarType(Entity, IList, DeclType, Index,
710 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000711 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000712 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000713 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000714 } else if (DeclType->isRecordType()) {
715 assert(DeclType->isAggregateType() &&
716 "non-aggregate records should be handed in CheckSubElementType");
717 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
718 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
719 SubobjectIsDesignatorContext, Index,
720 StructuredList, StructuredIndex,
721 TopLevelObject);
722 } else if (DeclType->isArrayType()) {
723 llvm::APSInt Zero(
724 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
725 false);
726 CheckArrayType(Entity, IList, DeclType, Zero,
727 SubobjectIsDesignatorContext, Index,
728 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000729 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
730 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000731 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000732 if (!VerifyOnly)
733 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
734 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000735 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000736 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000737 CheckReferenceType(Entity, IList, DeclType, Index,
738 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000739 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000740 if (!VerifyOnly)
741 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
742 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000743 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000744 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000745 if (!VerifyOnly)
746 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
747 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000748 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000749 }
750}
751
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000752void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000753 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000754 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000755 unsigned &Index,
756 InitListExpr *StructuredList,
757 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000758 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000759 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000760 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
761 unsigned newIndex = 0;
762 unsigned newStructuredIndex = 0;
763 InitListExpr *newStructuredList
764 = getStructuredSubobjectInit(IList, Index, ElemType,
765 StructuredList, StructuredIndex,
766 SubInitList->getSourceRange());
767 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
768 newStructuredList, newStructuredIndex);
769 ++StructuredIndex;
770 ++Index;
771 return;
772 }
773 assert(SemaRef.getLangOpts().CPlusPlus &&
774 "non-aggregate records are only possible in C++");
775 // C++ initialization is handled later.
776 }
777
778 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000779 return CheckScalarType(Entity, IList, ElemType, Index,
780 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000781 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000782 return CheckReferenceType(Entity, IList, ElemType, Index,
783 StructuredList, StructuredIndex);
784 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000785
John McCallfef8b342011-02-21 07:57:55 +0000786 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
787 // arrayType can be incomplete if we're initializing a flexible
788 // array member. There's nothing we can do with the completed
789 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000790
John McCallfef8b342011-02-21 07:57:55 +0000791 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000792 if (!VerifyOnly) {
793 CheckStringInit(Str, ElemType, arrayType, SemaRef);
794 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
795 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000796 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000797 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000798 }
John McCallfef8b342011-02-21 07:57:55 +0000799
800 // Fall through for subaggregate initialization.
801
David Blaikie4e4d0842012-03-11 07:00:24 +0000802 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000803 // C++ [dcl.init.aggr]p12:
804 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000805 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000806 // an initializer-list. If the initializer can initialize a
807 // member, the member is initialized. [...]
808
809 // FIXME: Better EqualLoc?
810 InitializationKind Kind =
811 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000812 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000813
814 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000815 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000816 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000817 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000818 if (Result.isInvalid())
819 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000820
Sebastian Redl14b0c192011-09-24 17:48:00 +0000821 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000822 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000823 }
John McCallfef8b342011-02-21 07:57:55 +0000824 ++Index;
825 return;
826 }
827
828 // Fall through for subaggregate initialization
829 } else {
830 // C99 6.7.8p13:
831 //
832 // The initializer for a structure or union object that has
833 // automatic storage duration shall be either an initializer
834 // list as described below, or a single expression that has
835 // compatible structure or union type. In the latter case, the
836 // initial value of the object, including unnamed members, is
837 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000838 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000839 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000840 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
841 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000842 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000843 if (ExprRes.isInvalid())
844 hadError = true;
845 else {
846 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000847 if (ExprRes.isInvalid())
848 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000849 }
850 UpdateStructuredListElement(StructuredList, StructuredIndex,
851 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000852 ++Index;
853 return;
854 }
John Wiegley429bb272011-04-08 18:41:53 +0000855 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000856 // Fall through for subaggregate initialization
857 }
858
859 // C++ [dcl.init.aggr]p12:
860 //
861 // [...] Otherwise, if the member is itself a non-empty
862 // subaggregate, brace elision is assumed and the initializer is
863 // considered for the initialization of the first member of
864 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000865 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000866 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000867 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
868 StructuredIndex);
869 ++StructuredIndex;
870 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000871 if (!VerifyOnly) {
872 // We cannot initialize this element, so let
873 // PerformCopyInitialization produce the appropriate diagnostic.
874 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
875 SemaRef.Owned(expr),
876 /*TopLevelOfInitList=*/true);
877 }
John McCallfef8b342011-02-21 07:57:55 +0000878 hadError = true;
879 ++Index;
880 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000881 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000882}
883
Eli Friedman0c706c22011-09-19 23:17:44 +0000884void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
885 InitListExpr *IList, QualType DeclType,
886 unsigned &Index,
887 InitListExpr *StructuredList,
888 unsigned &StructuredIndex) {
889 assert(Index == 0 && "Index in explicit init list must be zero");
890
891 // As an extension, clang supports complex initializers, which initialize
892 // a complex number component-wise. When an explicit initializer list for
893 // a complex number contains two two initializers, this extension kicks in:
894 // it exepcts the initializer list to contain two elements convertible to
895 // the element type of the complex type. The first element initializes
896 // the real part, and the second element intitializes the imaginary part.
897
898 if (IList->getNumInits() != 2)
899 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
900 StructuredIndex);
901
902 // This is an extension in C. (The builtin _Complex type does not exist
903 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000904 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000905 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
906 << IList->getSourceRange();
907
908 // Initialize the complex number.
909 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
910 InitializedEntity ElementEntity =
911 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
912
913 for (unsigned i = 0; i < 2; ++i) {
914 ElementEntity.setElementIndex(Index);
915 CheckSubElementType(ElementEntity, IList, elementType, Index,
916 StructuredList, StructuredIndex);
917 }
918}
919
920
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000921void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000922 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000923 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000924 InitListExpr *StructuredList,
925 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000926 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000927 if (!VerifyOnly)
928 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000929 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000930 diag::warn_cxx98_compat_empty_scalar_initializer :
931 diag::err_empty_scalar_initializer)
932 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +0000933 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +0000934 ++Index;
935 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000936 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000937 }
John McCallb934c2d2010-11-11 00:46:36 +0000938
939 Expr *expr = IList->getInit(Index);
940 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000941 if (!VerifyOnly)
942 SemaRef.Diag(SubIList->getLocStart(),
943 diag::warn_many_braces_around_scalar_init)
944 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000945
946 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
947 StructuredIndex);
948 return;
949 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000950 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000951 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000952 diag::err_designator_for_scalar_init)
953 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000954 hadError = true;
955 ++Index;
956 ++StructuredIndex;
957 return;
958 }
959
Sebastian Redl14b0c192011-09-24 17:48:00 +0000960 if (VerifyOnly) {
961 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
962 hadError = true;
963 ++Index;
964 return;
965 }
966
John McCallb934c2d2010-11-11 00:46:36 +0000967 ExprResult Result =
968 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000969 SemaRef.Owned(expr),
970 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000971
972 Expr *ResultExpr = 0;
973
974 if (Result.isInvalid())
975 hadError = true; // types weren't compatible.
976 else {
977 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000978
John McCallb934c2d2010-11-11 00:46:36 +0000979 if (ResultExpr != expr) {
980 // The type was promoted, update initializer list.
981 IList->setInit(Index, ResultExpr);
982 }
983 }
984 if (hadError)
985 ++StructuredIndex;
986 else
987 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
988 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000989}
990
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000991void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
992 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000993 unsigned &Index,
994 InitListExpr *StructuredList,
995 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000996 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000997 // FIXME: It would be wonderful if we could point at the actual member. In
998 // general, it would be useful to pass location information down the stack,
999 // so that we know the location (or decl) of the "current object" being
1000 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001001 if (!VerifyOnly)
1002 SemaRef.Diag(IList->getLocStart(),
1003 diag::err_init_reference_member_uninitialized)
1004 << DeclType
1005 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001006 hadError = true;
1007 ++Index;
1008 ++StructuredIndex;
1009 return;
1010 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001011
1012 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001013 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001014 if (!VerifyOnly)
1015 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1016 << DeclType << IList->getSourceRange();
1017 hadError = true;
1018 ++Index;
1019 ++StructuredIndex;
1020 return;
1021 }
1022
1023 if (VerifyOnly) {
1024 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1025 hadError = true;
1026 ++Index;
1027 return;
1028 }
1029
1030 ExprResult Result =
1031 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1032 SemaRef.Owned(expr),
1033 /*TopLevelOfInitList=*/true);
1034
1035 if (Result.isInvalid())
1036 hadError = true;
1037
1038 expr = Result.takeAs<Expr>();
1039 IList->setInit(Index, expr);
1040
1041 if (hadError)
1042 ++StructuredIndex;
1043 else
1044 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1045 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001046}
1047
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001048void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001049 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001050 unsigned &Index,
1051 InitListExpr *StructuredList,
1052 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001053 const VectorType *VT = DeclType->getAs<VectorType>();
1054 unsigned maxElements = VT->getNumElements();
1055 unsigned numEltsInit = 0;
1056 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001057
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001058 if (Index >= IList->getNumInits()) {
1059 // Make sure the element type can be value-initialized.
1060 if (VerifyOnly)
1061 CheckValueInitializable(
1062 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1063 return;
1064 }
1065
David Blaikie4e4d0842012-03-11 07:00:24 +00001066 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001067 // If the initializing element is a vector, try to copy-initialize
1068 // instead of breaking it apart (which is doomed to failure anyway).
1069 Expr *Init = IList->getInit(Index);
1070 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001071 if (VerifyOnly) {
1072 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1073 hadError = true;
1074 ++Index;
1075 return;
1076 }
1077
John McCall20e047a2010-10-30 00:11:39 +00001078 ExprResult Result =
1079 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001080 SemaRef.Owned(Init),
1081 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001082
1083 Expr *ResultExpr = 0;
1084 if (Result.isInvalid())
1085 hadError = true; // types weren't compatible.
1086 else {
1087 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001088
John McCall20e047a2010-10-30 00:11:39 +00001089 if (ResultExpr != Init) {
1090 // The type was promoted, update initializer list.
1091 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001092 }
1093 }
John McCall20e047a2010-10-30 00:11:39 +00001094 if (hadError)
1095 ++StructuredIndex;
1096 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001097 UpdateStructuredListElement(StructuredList, StructuredIndex,
1098 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001099 ++Index;
1100 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001101 }
Mike Stump1eb44332009-09-09 15:08:12 +00001102
John McCall20e047a2010-10-30 00:11:39 +00001103 InitializedEntity ElementEntity =
1104 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001105
John McCall20e047a2010-10-30 00:11:39 +00001106 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1107 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001108 if (Index >= IList->getNumInits()) {
1109 if (VerifyOnly)
1110 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001111 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001112 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001113
John McCall20e047a2010-10-30 00:11:39 +00001114 ElementEntity.setElementIndex(Index);
1115 CheckSubElementType(ElementEntity, IList, elementType, Index,
1116 StructuredList, StructuredIndex);
1117 }
1118 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001119 }
John McCall20e047a2010-10-30 00:11:39 +00001120
1121 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 // OpenCL initializers allows vectors to be constructed from vectors.
1125 for (unsigned i = 0; i < maxElements; ++i) {
1126 // Don't attempt to go past the end of the init list
1127 if (Index >= IList->getNumInits())
1128 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001129
John McCall20e047a2010-10-30 00:11:39 +00001130 ElementEntity.setElementIndex(Index);
1131
1132 QualType IType = IList->getInit(Index)->getType();
1133 if (!IType->isVectorType()) {
1134 CheckSubElementType(ElementEntity, IList, elementType, Index,
1135 StructuredList, StructuredIndex);
1136 ++numEltsInit;
1137 } else {
1138 QualType VecType;
1139 const VectorType *IVT = IType->getAs<VectorType>();
1140 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001141
John McCall20e047a2010-10-30 00:11:39 +00001142 if (IType->isExtVectorType())
1143 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1144 else
1145 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001146 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001147 CheckSubElementType(ElementEntity, IList, VecType, Index,
1148 StructuredList, StructuredIndex);
1149 numEltsInit += numIElts;
1150 }
1151 }
1152
1153 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001154 if (numEltsInit != maxElements) {
1155 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001156 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001157 diag::err_vector_incorrect_num_initializers)
1158 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1159 hadError = true;
1160 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001161}
1162
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001163void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001164 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001165 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001166 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001167 unsigned &Index,
1168 InitListExpr *StructuredList,
1169 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001170 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1171
Steve Naroff0cca7492008-05-01 22:18:59 +00001172 // Check for the special-case of initializing an array with a string.
1173 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001174 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001175 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001176 // We place the string literal directly into the resulting
1177 // initializer list. This is the only place where the structure
1178 // of the structured initializer list doesn't match exactly,
1179 // because doing so would involve allocating one character
1180 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001181 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001182 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001183 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1184 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1185 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001186 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001187 return;
1188 }
1189 }
John McCallce6c9b72011-02-21 07:22:22 +00001190 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001191 // Check for VLAs; in standard C it would be possible to check this
1192 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1193 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001194 if (!VerifyOnly)
1195 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1196 diag::err_variable_object_no_init)
1197 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001198 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001199 ++Index;
1200 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001201 return;
1202 }
1203
Douglas Gregor05c13a32009-01-22 00:58:24 +00001204 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001205 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1206 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001207 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001208 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001209 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001210 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001211 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001212 maxElementsKnown = true;
1213 }
1214
John McCallce6c9b72011-02-21 07:22:22 +00001215 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001216 while (Index < IList->getNumInits()) {
1217 Expr *Init = IList->getInit(Index);
1218 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001219 // If we're not the subobject that matches up with the '{' for
1220 // the designator, we shouldn't be handling the
1221 // designator. Return immediately.
1222 if (!SubobjectIsDesignatorContext)
1223 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001224
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001225 // Handle this designated initializer. elementIndex will be
1226 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001227 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001228 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001229 StructuredList, StructuredIndex, true,
1230 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001231 hadError = true;
1232 continue;
1233 }
1234
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001235 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001236 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001237 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001238 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001239 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001240
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001241 // If the array is of incomplete type, keep track of the number of
1242 // elements in the initializer.
1243 if (!maxElementsKnown && elementIndex > maxElements)
1244 maxElements = elementIndex;
1245
Douglas Gregor05c13a32009-01-22 00:58:24 +00001246 continue;
1247 }
1248
1249 // If we know the maximum number of elements, and we've already
1250 // hit it, stop consuming elements in the initializer list.
1251 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001252 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001253
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001254 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001255 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001256 Entity);
1257 // Check this element.
1258 CheckSubElementType(ElementEntity, IList, elementType, Index,
1259 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001260 ++elementIndex;
1261
1262 // If the array is of incomplete type, keep track of the number of
1263 // elements in the initializer.
1264 if (!maxElementsKnown && elementIndex > maxElements)
1265 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001266 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001267 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001268 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001269 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001270 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001271 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001272 // Sizing an array implicitly to zero is not allowed by ISO C,
1273 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001274 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001275 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001276 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001277
Mike Stump1eb44332009-09-09 15:08:12 +00001278 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001279 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001280 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001281 if (!hadError && VerifyOnly) {
1282 // Check if there are any members of the array that get value-initialized.
1283 // If so, check if doing that is possible.
1284 // FIXME: This needs to detect holes left by designated initializers too.
1285 if (maxElementsKnown && elementIndex < maxElements)
1286 CheckValueInitializable(InitializedEntity::InitializeElement(
1287 SemaRef.Context, 0, Entity));
1288 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001289}
1290
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001291bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1292 Expr *InitExpr,
1293 FieldDecl *Field,
1294 bool TopLevelObject) {
1295 // Handle GNU flexible array initializers.
1296 unsigned FlexArrayDiag;
1297 if (isa<InitListExpr>(InitExpr) &&
1298 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1299 // Empty flexible array init always allowed as an extension
1300 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001301 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001302 // Disallow flexible array init in C++; it is not required for gcc
1303 // compatibility, and it needs work to IRGen correctly in general.
1304 FlexArrayDiag = diag::err_flexible_array_init;
1305 } else if (!TopLevelObject) {
1306 // Disallow flexible array init on non-top-level object
1307 FlexArrayDiag = diag::err_flexible_array_init;
1308 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1309 // Disallow flexible array init on anything which is not a variable.
1310 FlexArrayDiag = diag::err_flexible_array_init;
1311 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1312 // Disallow flexible array init on local variables.
1313 FlexArrayDiag = diag::err_flexible_array_init;
1314 } else {
1315 // Allow other cases.
1316 FlexArrayDiag = diag::ext_flexible_array_init;
1317 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001318
1319 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001320 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001321 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001322 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001323 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1324 << Field;
1325 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001326
1327 return FlexArrayDiag != diag::ext_flexible_array_init;
1328}
1329
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001330void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001331 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001332 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001333 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001334 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001335 unsigned &Index,
1336 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001337 unsigned &StructuredIndex,
1338 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001339 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Eli Friedmanb85f7072008-05-19 19:16:24 +00001341 // If the record is invalid, some of it's members are invalid. To avoid
1342 // confusion, we forgo checking the intializer for the entire record.
1343 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001344 // Assume it was supposed to consume a single initializer.
1345 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001346 hadError = true;
1347 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001348 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001349
1350 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001351 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001352
1353 // If there's a default initializer, use it.
1354 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1355 if (VerifyOnly)
1356 return;
1357 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1358 Field != FieldEnd; ++Field) {
1359 if (Field->hasInClassInitializer()) {
1360 StructuredList->setInitializedFieldInUnion(*Field);
1361 // FIXME: Actually build a CXXDefaultInitExpr?
1362 return;
1363 }
1364 }
1365 }
1366
1367 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001368 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1369 Field != FieldEnd; ++Field) {
1370 if (Field->getDeclName()) {
1371 if (VerifyOnly)
1372 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001373 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001374 else
David Blaikie581deb32012-06-06 20:45:41 +00001375 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001376 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001377 }
1378 }
1379 return;
1380 }
1381
Douglas Gregor05c13a32009-01-22 00:58:24 +00001382 // If structDecl is a forward declaration, this loop won't do
1383 // anything except look at designated initializers; That's okay,
1384 // because an error should get printed out elsewhere. It might be
1385 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001386 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001387 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001388 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001389 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001390 while (Index < IList->getNumInits()) {
1391 Expr *Init = IList->getInit(Index);
1392
1393 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001394 // If we're not the subobject that matches up with the '{' for
1395 // the designator, we shouldn't be handling the
1396 // designator. Return immediately.
1397 if (!SubobjectIsDesignatorContext)
1398 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001399
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001400 // Handle this designated initializer. Field will be updated to
1401 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001402 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001403 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001404 StructuredList, StructuredIndex,
1405 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 hadError = true;
1407
Douglas Gregordfb5e592009-02-12 19:00:39 +00001408 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001409
1410 // Disable check for missing fields when designators are used.
1411 // This matches gcc behaviour.
1412 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001413 continue;
1414 }
1415
1416 if (Field == FieldEnd) {
1417 // We've run out of fields. We're done.
1418 break;
1419 }
1420
Douglas Gregordfb5e592009-02-12 19:00:39 +00001421 // We've already initialized a member of a union. We're done.
1422 if (InitializedSomething && DeclType->isUnionType())
1423 break;
1424
Douglas Gregor44b43212008-12-11 16:49:14 +00001425 // If we've hit the flexible array member at the end, we're done.
1426 if (Field->getType()->isIncompleteArrayType())
1427 break;
1428
Douglas Gregor0bb76892009-01-29 16:53:55 +00001429 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001430 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001431 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001432 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001433 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001434
Douglas Gregor54001c12011-06-29 21:51:31 +00001435 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001436 bool InvalidUse;
1437 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001438 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001439 else
David Blaikie581deb32012-06-06 20:45:41 +00001440 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001441 IList->getInit(Index)->getLocStart());
1442 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001443 ++Index;
1444 ++Field;
1445 hadError = true;
1446 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001447 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001448
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001449 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001450 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001451 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1452 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001453 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001454
Sebastian Redl14b0c192011-09-24 17:48:00 +00001455 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001456 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001457 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001458 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001459
1460 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001461 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001462
John McCall80639de2010-03-11 19:32:38 +00001463 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001464 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1465 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1466 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001467 // It is possible we have one or more unnamed bitfields remaining.
1468 // Find first (if any) named field and emit warning.
1469 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1470 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001471 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001472 SemaRef.Diag(IList->getSourceRange().getEnd(),
1473 diag::warn_missing_field_initializers) << it->getName();
1474 break;
1475 }
1476 }
1477 }
1478
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001479 // Check that any remaining fields can be value-initialized.
1480 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1481 !Field->getType()->isIncompleteArrayType()) {
1482 // FIXME: Should check for holes left by designated initializers too.
1483 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001484 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001485 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001486 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001487 }
1488 }
1489
Mike Stump1eb44332009-09-09 15:08:12 +00001490 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001491 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001492 return;
1493
David Blaikie581deb32012-06-06 20:45:41 +00001494 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001495 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001496 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001497 ++Index;
1498 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001499 }
1500
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001501 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001502 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001503
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001504 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001505 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001506 StructuredList, StructuredIndex);
1507 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001508 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001509 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001510}
Steve Naroff0cca7492008-05-01 22:18:59 +00001511
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001512/// \brief Expand a field designator that refers to a member of an
1513/// anonymous struct or union into a series of field designators that
1514/// refers to the field within the appropriate subobject.
1515///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001516static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001517 DesignatedInitExpr *DIE,
1518 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001519 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001520 typedef DesignatedInitExpr::Designator Designator;
1521
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001522 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001523 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001524 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1525 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1526 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001527 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001528 DIE->getDesignator(DesigIdx)->getDotLoc(),
1529 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1530 else
1531 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1532 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001533 assert(isa<FieldDecl>(*PI));
1534 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001535 }
1536
1537 // Expand the current designator into the set of replacement
1538 // designators, so we have a full subobject path down to where the
1539 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001540 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001541 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001542}
Mike Stump1eb44332009-09-09 15:08:12 +00001543
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001544/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001545/// corresponds to FieldName.
1546static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1547 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001548 if (!FieldName)
1549 return 0;
1550
Francois Picheta0e27f02010-12-22 03:46:10 +00001551 assert(AnonField->isAnonymousStructOrUnion());
1552 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001553 while (IndirectFieldDecl *IF =
1554 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001555 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001556 return IF;
1557 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001558 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001559 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001560}
1561
Sebastian Redl14b0c192011-09-24 17:48:00 +00001562static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1563 DesignatedInitExpr *DIE) {
1564 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1565 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1566 for (unsigned I = 0; I < NumIndexExprs; ++I)
1567 IndexExprs[I] = DIE->getSubExpr(I + 1);
1568 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001569 DIE->size(), IndexExprs,
1570 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001571 DIE->usesGNUSyntax(), DIE->getInit());
1572}
1573
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001574namespace {
1575
1576// Callback to only accept typo corrections that are for field members of
1577// the given struct or union.
1578class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1579 public:
1580 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1581 : Record(RD) {}
1582
1583 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1584 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1585 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1586 }
1587
1588 private:
1589 RecordDecl *Record;
1590};
1591
1592}
1593
Douglas Gregor05c13a32009-01-22 00:58:24 +00001594/// @brief Check the well-formedness of a C99 designated initializer.
1595///
1596/// Determines whether the designated initializer @p DIE, which
1597/// resides at the given @p Index within the initializer list @p
1598/// IList, is well-formed for a current object of type @p DeclType
1599/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001600/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001601/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001602///
1603/// @param IList The initializer list in which this designated
1604/// initializer occurs.
1605///
Douglas Gregor71199712009-04-15 04:56:10 +00001606/// @param DIE The designated initializer expression.
1607///
1608/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001609///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001610/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001611/// into which the designation in @p DIE should refer.
1612///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001613/// @param NextField If non-NULL and the first designator in @p DIE is
1614/// a field, this will be set to the field declaration corresponding
1615/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001616///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001617/// @param NextElementIndex If non-NULL and the first designator in @p
1618/// DIE is an array designator or GNU array-range designator, this
1619/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001620///
1621/// @param Index Index into @p IList where the designated initializer
1622/// @p DIE occurs.
1623///
Douglas Gregor4c678342009-01-28 21:54:33 +00001624/// @param StructuredList The initializer list expression that
1625/// describes all of the subobject initializers in the order they'll
1626/// actually be initialized.
1627///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001628/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001629bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001630InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001631 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001632 DesignatedInitExpr *DIE,
1633 unsigned DesigIdx,
1634 QualType &CurrentObjectType,
1635 RecordDecl::field_iterator *NextField,
1636 llvm::APSInt *NextElementIndex,
1637 unsigned &Index,
1638 InitListExpr *StructuredList,
1639 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001640 bool FinishSubobjectInit,
1641 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001642 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001643 // Check the actual initialization for the designated object type.
1644 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001645
1646 // Temporarily remove the designator expression from the
1647 // initializer list that the child calls see, so that we don't try
1648 // to re-process the designator.
1649 unsigned OldIndex = Index;
1650 IList->setInit(OldIndex, DIE->getInit());
1651
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001652 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001653 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001654
1655 // Restore the designated initializer expression in the syntactic
1656 // form of the initializer list.
1657 if (IList->getInit(OldIndex) != DIE->getInit())
1658 DIE->setInit(IList->getInit(OldIndex));
1659 IList->setInit(OldIndex, DIE);
1660
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001661 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001662 }
1663
Douglas Gregor71199712009-04-15 04:56:10 +00001664 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001665 bool IsFirstDesignator = (DesigIdx == 0);
1666 if (!VerifyOnly) {
1667 assert((IsFirstDesignator || StructuredList) &&
1668 "Need a non-designated initializer list to start from");
1669
1670 // Determine the structural initializer list that corresponds to the
1671 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001672 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001673 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1674 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001675 SourceRange(D->getLocStart(),
1676 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001677 assert(StructuredList && "Expected a structured initializer list");
1678 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001679
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001680 if (D->isFieldDesignator()) {
1681 // C99 6.7.8p7:
1682 //
1683 // If a designator has the form
1684 //
1685 // . identifier
1686 //
1687 // then the current object (defined below) shall have
1688 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001689 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001690 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001691 if (!RT) {
1692 SourceLocation Loc = D->getDotLoc();
1693 if (Loc.isInvalid())
1694 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001695 if (!VerifyOnly)
1696 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001697 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001698 ++Index;
1699 return true;
1700 }
1701
Douglas Gregor4c678342009-01-28 21:54:33 +00001702 // Note: we perform a linear search of the fields here, despite
1703 // the fact that we have a faster lookup method, because we always
1704 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001705 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001706 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001707 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001708 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001709 Field = RT->getDecl()->field_begin(),
1710 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001711 for (; Field != FieldEnd; ++Field) {
1712 if (Field->isUnnamedBitfield())
1713 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001714
Francois Picheta0e27f02010-12-22 03:46:10 +00001715 // If we find a field representing an anonymous field, look in the
1716 // IndirectFieldDecl that follow for the designated initializer.
1717 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1718 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001719 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001720 // In verify mode, don't modify the original.
1721 if (VerifyOnly)
1722 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001723 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1724 D = DIE->getDesignator(DesigIdx);
1725 break;
1726 }
1727 }
David Blaikie581deb32012-06-06 20:45:41 +00001728 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001729 break;
1730 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001731 break;
1732
1733 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001734 }
1735
Douglas Gregor4c678342009-01-28 21:54:33 +00001736 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001737 if (VerifyOnly) {
1738 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001739 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001740 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001741
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001742 // There was no normal field in the struct with the designated
1743 // name. Perform another lookup for this name, which may find
1744 // something that we can't designate (e.g., a member function),
1745 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001746 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001747 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001748 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001749 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001750 // Name lookup didn't find anything. Determine whether this
1751 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001752 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001753 TypoCorrection Corrected = SemaRef.CorrectTypo(
1754 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001755 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001756 RT->getDecl());
1757 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001758 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001759 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001760 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001761 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001762 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001763 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001764 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001765 << FieldName << CurrentObjectType << CorrectedQuotedStr
1766 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001767 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001768 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001769 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001770 } else {
1771 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1772 << FieldName << CurrentObjectType;
1773 ++Index;
1774 return true;
1775 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001776 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001778 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001780 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001781 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001782 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001783 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001784 ++Index;
1785 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001786 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001787
Francois Picheta0e27f02010-12-22 03:46:10 +00001788 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001789 // The replacement field comes from typo correction; find it
1790 // in the list of fields.
1791 FieldIndex = 0;
1792 Field = RT->getDecl()->field_begin();
1793 for (; Field != FieldEnd; ++Field) {
1794 if (Field->isUnnamedBitfield())
1795 continue;
1796
David Blaikie581deb32012-06-06 20:45:41 +00001797 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001798 Field->getIdentifier() == ReplacementField->getIdentifier())
1799 break;
1800
1801 ++FieldIndex;
1802 }
1803 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001804 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001805
1806 // All of the fields of a union are located at the same place in
1807 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001808 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001809 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001810 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001811 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001812 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001813
Douglas Gregor54001c12011-06-29 21:51:31 +00001814 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001815 bool InvalidUse;
1816 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001817 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001818 else
David Blaikie581deb32012-06-06 20:45:41 +00001819 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001820 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001821 ++Index;
1822 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001823 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001824
Sebastian Redl14b0c192011-09-24 17:48:00 +00001825 if (!VerifyOnly) {
1826 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001827 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Sebastian Redl14b0c192011-09-24 17:48:00 +00001829 // Make sure that our non-designated initializer list has space
1830 // for a subobject corresponding to this field.
1831 if (FieldIndex >= StructuredList->getNumInits())
1832 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1833 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001834
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001835 // This designator names a flexible array member.
1836 if (Field->getType()->isIncompleteArrayType()) {
1837 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001838 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001839 // We can't designate an object within the flexible array
1840 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001841 if (!VerifyOnly) {
1842 DesignatedInitExpr::Designator *NextD
1843 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001844 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001845 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001846 << SourceRange(NextD->getLocStart(),
1847 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001848 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001849 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001850 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001851 Invalid = true;
1852 }
1853
Chris Lattner9046c222010-10-10 17:49:49 +00001854 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1855 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001856 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001857 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001858 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001859 diag::err_flexible_array_init_needs_braces)
1860 << DIE->getInit()->getSourceRange();
1861 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001862 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001863 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001864 Invalid = true;
1865 }
1866
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001867 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001868 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001869 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001870 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001871
1872 if (Invalid) {
1873 ++Index;
1874 return true;
1875 }
1876
1877 // Initialize the array.
1878 bool prevHadError = hadError;
1879 unsigned newStructuredIndex = FieldIndex;
1880 unsigned OldIndex = Index;
1881 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001882
1883 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001884 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001885 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001886 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001887
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001888 IList->setInit(OldIndex, DIE);
1889 if (hadError && !prevHadError) {
1890 ++Field;
1891 ++FieldIndex;
1892 if (NextField)
1893 *NextField = Field;
1894 StructuredIndex = FieldIndex;
1895 return true;
1896 }
1897 } else {
1898 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001899 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001900 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001901
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001902 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001903 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001904 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1905 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001906 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001907 true, false))
1908 return true;
1909 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001910
1911 // Find the position of the next field to be initialized in this
1912 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001913 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001914 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001915
1916 // If this the first designator, our caller will continue checking
1917 // the rest of this struct/class/union subobject.
1918 if (IsFirstDesignator) {
1919 if (NextField)
1920 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001921 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001922 return false;
1923 }
1924
Douglas Gregor34e79462009-01-28 23:36:17 +00001925 if (!FinishSubobjectInit)
1926 return false;
1927
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001928 // We've already initialized something in the union; we're done.
1929 if (RT->getDecl()->isUnion())
1930 return hadError;
1931
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001932 // Check the remaining fields within this class/struct/union subobject.
1933 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001934
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001935 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001936 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001937 return hadError && !prevHadError;
1938 }
1939
1940 // C99 6.7.8p6:
1941 //
1942 // If a designator has the form
1943 //
1944 // [ constant-expression ]
1945 //
1946 // then the current object (defined below) shall have array
1947 // type and the expression shall be an integer constant
1948 // expression. If the array is of unknown size, any
1949 // nonnegative value is valid.
1950 //
1951 // Additionally, cope with the GNU extension that permits
1952 // designators of the form
1953 //
1954 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001955 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001956 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001957 if (!VerifyOnly)
1958 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1959 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001960 ++Index;
1961 return true;
1962 }
1963
1964 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001965 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1966 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001967 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001968 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001969 DesignatedEndIndex = DesignatedStartIndex;
1970 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001971 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001972
Mike Stump1eb44332009-09-09 15:08:12 +00001973 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001974 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001975 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001976 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001977 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001978
Chris Lattnere0fd8322011-02-19 22:28:58 +00001979 // Codegen can't handle evaluating array range designators that have side
1980 // effects, because we replicate the AST value for each initialized element.
1981 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1982 // elements with something that has a side effect, so codegen can emit an
1983 // "error unsupported" error instead of miscompiling the app.
1984 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001985 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001986 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001987 }
1988
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001989 if (isa<ConstantArrayType>(AT)) {
1990 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001991 DesignatedStartIndex
1992 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001993 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001994 DesignatedEndIndex
1995 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001996 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1997 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001998 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001999 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002000 diag::err_array_designator_too_large)
2001 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2002 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002003 ++Index;
2004 return true;
2005 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002006 } else {
2007 // Make sure the bit-widths and signedness match.
2008 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002009 DesignatedEndIndex
2010 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002011 else if (DesignatedStartIndex.getBitWidth() <
2012 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002013 DesignatedStartIndex
2014 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002015 DesignatedStartIndex.setIsUnsigned(true);
2016 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Douglas Gregor4c678342009-01-28 21:54:33 +00002019 // Make sure that our non-designated initializer list has space
2020 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002021 if (!VerifyOnly &&
2022 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002023 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002024 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002025
Douglas Gregor34e79462009-01-28 23:36:17 +00002026 // Repeatedly perform subobject initializations in the range
2027 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002028
Douglas Gregor34e79462009-01-28 23:36:17 +00002029 // Move to the next designator
2030 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2031 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002032
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002033 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002034 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002035
Douglas Gregor34e79462009-01-28 23:36:17 +00002036 while (DesignatedStartIndex <= DesignatedEndIndex) {
2037 // Recurse to check later designated subobjects.
2038 QualType ElementType = AT->getElementType();
2039 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002040
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002041 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002042 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2043 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002044 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002045 (DesignatedStartIndex == DesignatedEndIndex),
2046 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002047 return true;
2048
2049 // Move to the next index in the array that we'll be initializing.
2050 ++DesignatedStartIndex;
2051 ElementIndex = DesignatedStartIndex.getZExtValue();
2052 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002053
2054 // If this the first designator, our caller will continue checking
2055 // the rest of this array subobject.
2056 if (IsFirstDesignator) {
2057 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002058 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002059 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002060 return false;
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Douglas Gregor34e79462009-01-28 23:36:17 +00002063 if (!FinishSubobjectInit)
2064 return false;
2065
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002066 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002067 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002068 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002069 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002071 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002072}
2073
Douglas Gregor4c678342009-01-28 21:54:33 +00002074// Get the structured initializer list for a subobject of type
2075// @p CurrentObjectType.
2076InitListExpr *
2077InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2078 QualType CurrentObjectType,
2079 InitListExpr *StructuredList,
2080 unsigned StructuredIndex,
2081 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002082 if (VerifyOnly)
2083 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002084 Expr *ExistingInit = 0;
2085 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002086 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002087 else if (StructuredIndex < StructuredList->getNumInits())
2088 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Douglas Gregor4c678342009-01-28 21:54:33 +00002090 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2091 return Result;
2092
2093 if (ExistingInit) {
2094 // We are creating an initializer list that initializes the
2095 // subobjects of the current object, but there was already an
2096 // initialization that completely initialized the current
2097 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002098 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002099 // struct X { int a, b; };
2100 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002101 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002102 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2103 // designated initializer re-initializes the whole
2104 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002105 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002106 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002107 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002108 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002109 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002110 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002111 << ExistingInit->getSourceRange();
2112 }
2113
Mike Stump1eb44332009-09-09 15:08:12 +00002114 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002115 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002116 InitRange.getBegin(), MultiExprArg(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00002117 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002118
Eli Friedman5c89c392012-02-23 02:25:10 +00002119 QualType ResultType = CurrentObjectType;
2120 if (!ResultType->isArrayType())
2121 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2122 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002123
Douglas Gregorfa219202009-03-20 23:58:33 +00002124 // Pre-allocate storage for the structured initializer list.
2125 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002126 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002127 bool GotNumInits = false;
2128 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002129 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002130 GotNumInits = true;
2131 } else if (Index < IList->getNumInits()) {
2132 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002133 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002134 GotNumInits = true;
2135 }
Douglas Gregor08457732009-03-21 18:13:52 +00002136 }
2137
Mike Stump1eb44332009-09-09 15:08:12 +00002138 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002139 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2140 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2141 NumElements = CAType->getSize().getZExtValue();
2142 // Simple heuristic so that we don't allocate a very large
2143 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002144 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002145 NumElements = 0;
2146 }
John McCall183700f2009-09-21 23:43:11 +00002147 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002148 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002149 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002150 RecordDecl *RDecl = RType->getDecl();
2151 if (RDecl->isUnion())
2152 NumElements = 1;
2153 else
Mike Stump1eb44332009-09-09 15:08:12 +00002154 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002155 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002156 }
2157
Ted Kremenek709210f2010-04-13 23:39:13 +00002158 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002159
Douglas Gregor4c678342009-01-28 21:54:33 +00002160 // Link this new initializer list into the structured initializer
2161 // lists.
2162 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002163 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002164 else {
2165 Result->setSyntacticForm(IList);
2166 SyntacticToSemantic[IList] = Result;
2167 }
2168
2169 return Result;
2170}
2171
2172/// Update the initializer at index @p StructuredIndex within the
2173/// structured initializer list to the value @p expr.
2174void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2175 unsigned &StructuredIndex,
2176 Expr *expr) {
2177 // No structured initializer list to update
2178 if (!StructuredList)
2179 return;
2180
Ted Kremenek709210f2010-04-13 23:39:13 +00002181 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2182 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002183 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002184 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002185 diag::warn_initializer_overrides)
2186 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002187 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002188 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002189 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002190 << PrevInit->getSourceRange();
2191 }
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Douglas Gregor4c678342009-01-28 21:54:33 +00002193 ++StructuredIndex;
2194}
2195
Douglas Gregor05c13a32009-01-22 00:58:24 +00002196/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002197/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002198/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002199/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002200/// failure. Returns the index expression, possibly with an implicit cast
2201/// added, on success. If everything went okay, Value will receive the
2202/// value of the constant expression.
2203static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002204CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002205 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002206
2207 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002208 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2209 if (Result.isInvalid())
2210 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002211
Chris Lattner3bf68932009-04-25 21:59:05 +00002212 if (Value.isSigned() && Value.isNegative())
2213 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002214 << Value.toString(10) << Index->getSourceRange();
2215
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002216 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002217 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002218}
2219
John McCall60d7b3a2010-08-24 06:29:42 +00002220ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002221 SourceLocation Loc,
2222 bool GNUSyntax,
2223 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002224 typedef DesignatedInitExpr::Designator ASTDesignator;
2225
2226 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002227 SmallVector<ASTDesignator, 32> Designators;
2228 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002229
2230 // Build designators and check array designator expressions.
2231 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2232 const Designator &D = Desig.getDesignator(Idx);
2233 switch (D.getKind()) {
2234 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002235 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002236 D.getFieldLoc()));
2237 break;
2238
2239 case Designator::ArrayDesignator: {
2240 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2241 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002242 if (!Index->isTypeDependent() && !Index->isValueDependent())
2243 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2244 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002245 Invalid = true;
2246 else {
2247 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002248 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002249 D.getRBracketLoc()));
2250 InitExpressions.push_back(Index);
2251 }
2252 break;
2253 }
2254
2255 case Designator::ArrayRangeDesignator: {
2256 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2257 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2258 llvm::APSInt StartValue;
2259 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002260 bool StartDependent = StartIndex->isTypeDependent() ||
2261 StartIndex->isValueDependent();
2262 bool EndDependent = EndIndex->isTypeDependent() ||
2263 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002264 if (!StartDependent)
2265 StartIndex =
2266 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2267 if (!EndDependent)
2268 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2269
2270 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002271 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002272 else {
2273 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002274 if (StartDependent || EndDependent) {
2275 // Nothing to compute.
2276 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002277 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002278 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002279 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002280
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002281 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002282 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002283 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002284 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2285 Invalid = true;
2286 } else {
2287 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002288 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002289 D.getEllipsisLoc(),
2290 D.getRBracketLoc()));
2291 InitExpressions.push_back(StartIndex);
2292 InitExpressions.push_back(EndIndex);
2293 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002294 }
2295 break;
2296 }
2297 }
2298 }
2299
2300 if (Invalid || Init.isInvalid())
2301 return ExprError();
2302
2303 // Clear out the expressions within the designation.
2304 Desig.ClearExprs(*this);
2305
2306 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002307 = DesignatedInitExpr::Create(Context,
2308 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002309 InitExpressions, Loc, GNUSyntax,
2310 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002311
David Blaikie4e4d0842012-03-11 07:00:24 +00002312 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002313 Diag(DIE->getLocStart(), diag::ext_designated_init)
2314 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002315
Douglas Gregor05c13a32009-01-22 00:58:24 +00002316 return Owned(DIE);
2317}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002318
Douglas Gregor20093b42009-12-09 23:02:17 +00002319//===----------------------------------------------------------------------===//
2320// Initialization entity
2321//===----------------------------------------------------------------------===//
2322
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002323InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002324 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002325 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002326{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002327 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2328 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002329 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002330 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002331 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002332 Type = VT->getElementType();
2333 } else {
2334 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2335 assert(CT && "Unexpected type");
2336 Kind = EK_ComplexElement;
2337 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002338 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002339}
2340
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002341InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002342 CXXBaseSpecifier *Base,
2343 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002344{
2345 InitializedEntity Result;
2346 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002347 Result.Base = reinterpret_cast<uintptr_t>(Base);
2348 if (IsInheritedVirtualBase)
2349 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002350
Douglas Gregord6542d82009-12-22 15:35:07 +00002351 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002352 return Result;
2353}
2354
Douglas Gregor99a2e602009-12-16 01:38:02 +00002355DeclarationName InitializedEntity::getName() const {
2356 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002357 case EK_Parameter: {
2358 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2359 return (D ? D->getDeclName() : DeclarationName());
2360 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002361
2362 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002363 case EK_Member:
2364 return VariableOrMember->getDeclName();
2365
Douglas Gregor47736542012-02-15 16:57:26 +00002366 case EK_LambdaCapture:
2367 return Capture.Var->getDeclName();
2368
Douglas Gregor99a2e602009-12-16 01:38:02 +00002369 case EK_Result:
2370 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002371 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002372 case EK_Temporary:
2373 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002374 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002375 case EK_ArrayElement:
2376 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002377 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002378 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002379 return DeclarationName();
2380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002381
David Blaikie7530c032012-01-17 06:56:22 +00002382 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002383}
2384
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002385DeclaratorDecl *InitializedEntity::getDecl() const {
2386 switch (getKind()) {
2387 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002388 case EK_Member:
2389 return VariableOrMember;
2390
John McCallf85e1932011-06-15 23:02:42 +00002391 case EK_Parameter:
2392 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2393
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002394 case EK_Result:
2395 case EK_Exception:
2396 case EK_New:
2397 case EK_Temporary:
2398 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002399 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002400 case EK_ArrayElement:
2401 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002402 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002403 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002404 case EK_LambdaCapture:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002405 return 0;
2406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002407
David Blaikie7530c032012-01-17 06:56:22 +00002408 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002409}
2410
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002411bool InitializedEntity::allowsNRVO() const {
2412 switch (getKind()) {
2413 case EK_Result:
2414 case EK_Exception:
2415 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002416
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002417 case EK_Variable:
2418 case EK_Parameter:
2419 case EK_Member:
2420 case EK_New:
2421 case EK_Temporary:
2422 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002423 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002424 case EK_ArrayElement:
2425 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002426 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002427 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002428 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002429 break;
2430 }
2431
2432 return false;
2433}
2434
Douglas Gregor20093b42009-12-09 23:02:17 +00002435//===----------------------------------------------------------------------===//
2436// Initialization sequence
2437//===----------------------------------------------------------------------===//
2438
2439void InitializationSequence::Step::Destroy() {
2440 switch (Kind) {
2441 case SK_ResolveAddressOfOverloadedFunction:
2442 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002443 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002444 case SK_CastDerivedToBaseLValue:
2445 case SK_BindReference:
2446 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002447 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002448 case SK_UserConversion:
2449 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002450 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002451 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002452 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002453 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002454 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002455 case SK_UnwrapInitList:
2456 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002457 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002458 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002459 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002460 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002461 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002462 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002463 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002464 case SK_PassByIndirectCopyRestore:
2465 case SK_PassByIndirectRestore:
2466 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002467 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002468 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002469 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002470 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002471
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 case SK_ConversionSequence:
2473 delete ICS;
2474 }
2475}
2476
Douglas Gregorb70cf442010-03-26 20:14:36 +00002477bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002478 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002479}
2480
2481bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002482 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002483 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002484
Douglas Gregorb70cf442010-03-26 20:14:36 +00002485 switch (getFailureKind()) {
2486 case FK_TooManyInitsForReference:
2487 case FK_ArrayNeedsInitList:
2488 case FK_ArrayNeedsInitListOrStringLiteral:
2489 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2490 case FK_NonConstLValueReferenceBindingToTemporary:
2491 case FK_NonConstLValueReferenceBindingToUnrelated:
2492 case FK_RValueReferenceBindingToLValue:
2493 case FK_ReferenceInitDropsQualifiers:
2494 case FK_ReferenceInitFailed:
2495 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002496 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002497 case FK_TooManyInitsForScalar:
2498 case FK_ReferenceBindingToInitList:
2499 case FK_InitListBadDestinationType:
2500 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002501 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002502 case FK_ArrayTypeMismatch:
2503 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002504 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002505 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002506 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002507 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002508 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002509 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002510
Douglas Gregorb70cf442010-03-26 20:14:36 +00002511 case FK_ReferenceInitOverloadFailed:
2512 case FK_UserConversionOverloadFailed:
2513 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002514 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002515 return FailedOverloadResult == OR_Ambiguous;
2516 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002517
David Blaikie7530c032012-01-17 06:56:22 +00002518 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002519}
2520
Douglas Gregord6e44a32010-04-16 22:09:46 +00002521bool InitializationSequence::isConstructorInitialization() const {
2522 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2523}
2524
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002525void
2526InitializationSequence
2527::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2528 DeclAccessPair Found,
2529 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002530 Step S;
2531 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2532 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002533 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002534 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002535 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 Steps.push_back(S);
2537}
2538
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002539void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002540 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002541 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002542 switch (VK) {
2543 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2544 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2545 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002546 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002547 S.Type = BaseType;
2548 Steps.push_back(S);
2549}
2550
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002551void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002552 bool BindingTemporary) {
2553 Step S;
2554 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2555 S.Type = T;
2556 Steps.push_back(S);
2557}
2558
Douglas Gregor523d46a2010-04-18 07:40:54 +00002559void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2560 Step S;
2561 S.Kind = SK_ExtraneousCopyToTemporary;
2562 S.Type = T;
2563 Steps.push_back(S);
2564}
2565
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002566void
2567InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2568 DeclAccessPair FoundDecl,
2569 QualType T,
2570 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002571 Step S;
2572 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002573 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002574 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002575 S.Function.Function = Function;
2576 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002577 Steps.push_back(S);
2578}
2579
2580void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002581 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002582 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002583 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002584 switch (VK) {
2585 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002586 S.Kind = SK_QualificationConversionRValue;
2587 break;
John McCall5baba9d2010-08-25 10:28:54 +00002588 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002589 S.Kind = SK_QualificationConversionXValue;
2590 break;
John McCall5baba9d2010-08-25 10:28:54 +00002591 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002592 S.Kind = SK_QualificationConversionLValue;
2593 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002594 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002595 S.Type = Ty;
2596 Steps.push_back(S);
2597}
2598
Jordan Rose1fd1e282013-04-11 00:58:58 +00002599void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2600 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2601
2602 Step S;
2603 S.Kind = SK_LValueToRValue;
2604 S.Type = Ty;
2605 Steps.push_back(S);
2606}
2607
Douglas Gregor20093b42009-12-09 23:02:17 +00002608void InitializationSequence::AddConversionSequenceStep(
2609 const ImplicitConversionSequence &ICS,
2610 QualType T) {
2611 Step S;
2612 S.Kind = SK_ConversionSequence;
2613 S.Type = T;
2614 S.ICS = new ImplicitConversionSequence(ICS);
2615 Steps.push_back(S);
2616}
2617
Douglas Gregord87b61f2009-12-10 17:56:55 +00002618void InitializationSequence::AddListInitializationStep(QualType T) {
2619 Step S;
2620 S.Kind = SK_ListInitialization;
2621 S.Type = T;
2622 Steps.push_back(S);
2623}
2624
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002625void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002626InitializationSequence
2627::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2628 AccessSpecifier Access,
2629 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002630 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002631 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002632 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002633 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2634 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002635 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002636 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002637 S.Function.Function = Constructor;
2638 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002639 Steps.push_back(S);
2640}
2641
Douglas Gregor71d17402009-12-15 00:01:57 +00002642void InitializationSequence::AddZeroInitializationStep(QualType T) {
2643 Step S;
2644 S.Kind = SK_ZeroInitialization;
2645 S.Type = T;
2646 Steps.push_back(S);
2647}
2648
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002649void InitializationSequence::AddCAssignmentStep(QualType T) {
2650 Step S;
2651 S.Kind = SK_CAssignment;
2652 S.Type = T;
2653 Steps.push_back(S);
2654}
2655
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002656void InitializationSequence::AddStringInitStep(QualType T) {
2657 Step S;
2658 S.Kind = SK_StringInit;
2659 S.Type = T;
2660 Steps.push_back(S);
2661}
2662
Douglas Gregor569c3162010-08-07 11:51:51 +00002663void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2664 Step S;
2665 S.Kind = SK_ObjCObjectConversion;
2666 S.Type = T;
2667 Steps.push_back(S);
2668}
2669
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002670void InitializationSequence::AddArrayInitStep(QualType T) {
2671 Step S;
2672 S.Kind = SK_ArrayInit;
2673 S.Type = T;
2674 Steps.push_back(S);
2675}
2676
Richard Smith0f163e92012-02-15 22:38:09 +00002677void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2678 Step S;
2679 S.Kind = SK_ParenthesizedArrayInit;
2680 S.Type = T;
2681 Steps.push_back(S);
2682}
2683
John McCallf85e1932011-06-15 23:02:42 +00002684void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2685 bool shouldCopy) {
2686 Step s;
2687 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2688 : SK_PassByIndirectRestore);
2689 s.Type = type;
2690 Steps.push_back(s);
2691}
2692
2693void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2694 Step S;
2695 S.Kind = SK_ProduceObjCObject;
2696 S.Type = T;
2697 Steps.push_back(S);
2698}
2699
Sebastian Redl2b916b82012-01-17 22:49:42 +00002700void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2701 Step S;
2702 S.Kind = SK_StdInitializerList;
2703 S.Type = T;
2704 Steps.push_back(S);
2705}
2706
Guy Benyei21f18c42013-02-07 10:55:47 +00002707void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2708 Step S;
2709 S.Kind = SK_OCLSamplerInit;
2710 S.Type = T;
2711 Steps.push_back(S);
2712}
2713
Guy Benyeie6b9d802013-01-20 12:31:11 +00002714void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2715 Step S;
2716 S.Kind = SK_OCLZeroEvent;
2717 S.Type = T;
2718 Steps.push_back(S);
2719}
2720
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002721void InitializationSequence::RewrapReferenceInitList(QualType T,
2722 InitListExpr *Syntactic) {
2723 assert(Syntactic->getNumInits() == 1 &&
2724 "Can only rewrap trivial init lists.");
2725 Step S;
2726 S.Kind = SK_UnwrapInitList;
2727 S.Type = Syntactic->getInit(0)->getType();
2728 Steps.insert(Steps.begin(), S);
2729
2730 S.Kind = SK_RewrapInitList;
2731 S.Type = T;
2732 S.WrappingSyntacticList = Syntactic;
2733 Steps.push_back(S);
2734}
2735
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002736void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002737 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002738 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002739 this->Failure = Failure;
2740 this->FailedOverloadResult = Result;
2741}
2742
2743//===----------------------------------------------------------------------===//
2744// Attempt initialization
2745//===----------------------------------------------------------------------===//
2746
John McCallf85e1932011-06-15 23:02:42 +00002747static void MaybeProduceObjCObject(Sema &S,
2748 InitializationSequence &Sequence,
2749 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002750 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002751
2752 /// When initializing a parameter, produce the value if it's marked
2753 /// __attribute__((ns_consumed)).
2754 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2755 if (!Entity.isParameterConsumed())
2756 return;
2757
2758 assert(Entity.getType()->isObjCRetainableType() &&
2759 "consuming an object of unretainable type?");
2760 Sequence.AddProduceObjCObjectStep(Entity.getType());
2761
2762 /// When initializing a return value, if the return type is a
2763 /// retainable type, then returns need to immediately retain the
2764 /// object. If an autorelease is required, it will be done at the
2765 /// last instant.
2766 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2767 if (!Entity.getType()->isObjCRetainableType())
2768 return;
2769
2770 Sequence.AddProduceObjCObjectStep(Entity.getType());
2771 }
2772}
2773
Richard Smithf4bb8d02012-07-05 08:39:21 +00002774/// \brief When initializing from init list via constructor, handle
2775/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002776///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002777/// \return true if we have handled initialization of an object of type
2778/// std::initializer_list<T>, false otherwise.
2779static bool TryInitializerListConstruction(Sema &S,
2780 InitListExpr *List,
2781 QualType DestType,
2782 InitializationSequence &Sequence) {
2783 QualType E;
2784 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002785 return false;
2786
Richard Smithf4bb8d02012-07-05 08:39:21 +00002787 // Check that each individual element can be copy-constructed. But since we
2788 // have no place to store further information, we'll recalculate everything
2789 // later.
2790 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2791 S.Context.getConstantArrayType(E,
2792 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2793 List->getNumInits()),
2794 ArrayType::Normal, 0));
2795 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2796 0, HiddenArray);
2797 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2798 Element.setElementIndex(i);
2799 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2800 Sequence.SetFailed(
2801 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002802 return true;
2803 }
2804 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002805 Sequence.AddStdInitializerListConstructionStep(DestType);
2806 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002807}
2808
Sebastian Redl96715b22012-02-04 21:27:39 +00002809static OverloadingResult
2810ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002811 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002812 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002813 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002814 OverloadCandidateSet::iterator &Best,
2815 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002816 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002817 CandidateSet.clear();
2818
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002819 for (ArrayRef<NamedDecl *>::iterator
2820 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002821 NamedDecl *D = *Con;
2822 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2823 bool SuppressUserConversions = false;
2824
2825 // Find the constructor (which may be a template).
2826 CXXConstructorDecl *Constructor = 0;
2827 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2828 if (ConstructorTmpl)
2829 Constructor = cast<CXXConstructorDecl>(
2830 ConstructorTmpl->getTemplatedDecl());
2831 else {
2832 Constructor = cast<CXXConstructorDecl>(D);
2833
2834 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002835 // suppress user-defined conversions on the arguments. We do the same for
2836 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002837 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002838 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002839 SuppressUserConversions = true;
2840 }
2841
2842 if (!Constructor->isInvalidDecl() &&
2843 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002844 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002845 if (ConstructorTmpl)
2846 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002847 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002848 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002849 else {
2850 // C++ [over.match.copy]p1:
2851 // - When initializing a temporary to be bound to the first parameter
2852 // of a constructor that takes a reference to possibly cv-qualified
2853 // T as its first argument, called with a single argument in the
2854 // context of direct-initialization, explicit conversion functions
2855 // are also considered.
2856 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002857 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00002858 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002859 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002860 SuppressUserConversions,
2861 /*PartialOverloading=*/false,
2862 /*AllowExplicit=*/AllowExplicitConv);
2863 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002864 }
2865 }
2866
2867 // Perform overload resolution and return the result.
2868 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2869}
2870
Sebastian Redl10f04a62011-12-22 14:44:04 +00002871/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2872/// enumerates the constructors of the initialized entity and performs overload
2873/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002874/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002875/// class type.
2876static void TryConstructorInitialization(Sema &S,
2877 const InitializedEntity &Entity,
2878 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002879 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002880 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002881 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002882 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00002883 "InitListSyntax must come with a single initializer list argument.");
2884
Sebastian Redl10f04a62011-12-22 14:44:04 +00002885 // The type we're constructing needs to be complete.
2886 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002887 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002888 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002889 }
2890
2891 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2892 assert(DestRecordType && "Constructor initialization requires record type");
2893 CXXRecordDecl *DestRecordDecl
2894 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2895
Sebastian Redl96715b22012-02-04 21:27:39 +00002896 // Build the candidate set directly in the initialization sequence
2897 // structure, so that it will persist if we fail.
2898 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2899
2900 // Determine whether we are allowed to call explicit constructors or
2901 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002902 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002903 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002904
Sebastian Redl10f04a62011-12-22 14:44:04 +00002905 // - Otherwise, if T is a class type, constructors are considered. The
2906 // applicable constructors are enumerated, and the best one is chosen
2907 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00002908 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002909 // The container holding the constructors can under certain conditions
2910 // be changed while iterating (e.g. because of deserialization).
2911 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00002912 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00002913
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002914 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002915 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002916 bool AsInitializerList = false;
2917
2918 // C++11 [over.match.list]p1:
2919 // When objects of non-aggregate type T are list-initialized, overload
2920 // resolution selects the constructor in two phases:
2921 // - Initially, the candidate functions are the initializer-list
2922 // constructors of the class T and the argument list consists of the
2923 // initializer list as a single argument.
2924 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002925 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002926 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00002927
2928 // If the initializer list has no elements and T has a default constructor,
2929 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00002930 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002931 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002932 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00002933 CopyInitialization, AllowExplicit,
2934 /*OnlyListConstructor=*/true,
2935 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002936
2937 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002938 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002939 }
2940
2941 // C++11 [over.match.list]p1:
2942 // - If no viable initializer-list constructor is found, overload resolution
2943 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00002944 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002945 // elements of the initializer list.
2946 if (Result == OR_No_Viable_Function) {
2947 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002948 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002949 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002950 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002951 /*OnlyListConstructors=*/false,
2952 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002953 }
2954 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002955 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002956 InitializationSequence::FK_ListConstructorOverloadFailed :
2957 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002958 Result);
2959 return;
2960 }
2961
Richard Smithf4bb8d02012-07-05 08:39:21 +00002962 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002963 // If a program calls for the default initialization of an object
2964 // of a const-qualified type T, T shall be a class type with a
2965 // user-provided default constructor.
2966 if (Kind.getKind() == InitializationKind::IK_Default &&
2967 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00002968 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002969 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2970 return;
2971 }
2972
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002973 // C++11 [over.match.list]p1:
2974 // In copy-list-initialization, if an explicit constructor is chosen, the
2975 // initializer is ill-formed.
2976 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2977 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2978 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2979 return;
2980 }
2981
Sebastian Redl10f04a62011-12-22 14:44:04 +00002982 // Add the constructor initialization step. Any cv-qualification conversion is
2983 // subsumed by the initialization.
2984 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002985 Sequence.AddConstructorInitializationStep(CtorDecl,
2986 Best->FoundDecl.getAccess(),
2987 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002988 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002989}
2990
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002991static bool
2992ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2993 Expr *Initializer,
2994 QualType &SourceType,
2995 QualType &UnqualifiedSourceType,
2996 QualType UnqualifiedTargetType,
2997 InitializationSequence &Sequence) {
2998 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2999 S.Context.OverloadTy) {
3000 DeclAccessPair Found;
3001 bool HadMultipleCandidates = false;
3002 if (FunctionDecl *Fn
3003 = S.ResolveAddressOfOverloadedFunction(Initializer,
3004 UnqualifiedTargetType,
3005 false, Found,
3006 &HadMultipleCandidates)) {
3007 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3008 HadMultipleCandidates);
3009 SourceType = Fn->getType();
3010 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3011 } else if (!UnqualifiedTargetType->isRecordType()) {
3012 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3013 return true;
3014 }
3015 }
3016 return false;
3017}
3018
3019static void TryReferenceInitializationCore(Sema &S,
3020 const InitializedEntity &Entity,
3021 const InitializationKind &Kind,
3022 Expr *Initializer,
3023 QualType cv1T1, QualType T1,
3024 Qualifiers T1Quals,
3025 QualType cv2T2, QualType T2,
3026 Qualifiers T2Quals,
3027 InitializationSequence &Sequence);
3028
Richard Smithf4bb8d02012-07-05 08:39:21 +00003029static void TryValueInitialization(Sema &S,
3030 const InitializedEntity &Entity,
3031 const InitializationKind &Kind,
3032 InitializationSequence &Sequence,
3033 InitListExpr *InitList = 0);
3034
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003035static void TryListInitialization(Sema &S,
3036 const InitializedEntity &Entity,
3037 const InitializationKind &Kind,
3038 InitListExpr *InitList,
3039 InitializationSequence &Sequence);
3040
3041/// \brief Attempt list initialization of a reference.
3042static void TryReferenceListInitialization(Sema &S,
3043 const InitializedEntity &Entity,
3044 const InitializationKind &Kind,
3045 InitListExpr *InitList,
3046 InitializationSequence &Sequence)
3047{
3048 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003049 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003050 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3051 return;
3052 }
3053
3054 QualType DestType = Entity.getType();
3055 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3056 Qualifiers T1Quals;
3057 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3058
3059 // Reference initialization via an initializer list works thus:
3060 // If the initializer list consists of a single element that is
3061 // reference-related to the referenced type, bind directly to that element
3062 // (possibly creating temporaries).
3063 // Otherwise, initialize a temporary with the initializer list and
3064 // bind to that.
3065 if (InitList->getNumInits() == 1) {
3066 Expr *Initializer = InitList->getInit(0);
3067 QualType cv2T2 = Initializer->getType();
3068 Qualifiers T2Quals;
3069 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3070
3071 // If this fails, creating a temporary wouldn't work either.
3072 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3073 T1, Sequence))
3074 return;
3075
3076 SourceLocation DeclLoc = Initializer->getLocStart();
3077 bool dummy1, dummy2, dummy3;
3078 Sema::ReferenceCompareResult RefRelationship
3079 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3080 dummy2, dummy3);
3081 if (RefRelationship >= Sema::Ref_Related) {
3082 // Try to bind the reference here.
3083 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3084 T1Quals, cv2T2, T2, T2Quals, Sequence);
3085 if (Sequence)
3086 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3087 return;
3088 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003089
3090 // Update the initializer if we've resolved an overloaded function.
3091 if (Sequence.step_begin() != Sequence.step_end())
3092 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003093 }
3094
3095 // Not reference-related. Create a temporary and bind to that.
3096 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3097
3098 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3099 if (Sequence) {
3100 if (DestType->isRValueReferenceType() ||
3101 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3102 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3103 else
3104 Sequence.SetFailed(
3105 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3106 }
3107}
3108
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003109/// \brief Attempt list initialization (C++0x [dcl.init.list])
3110static void TryListInitialization(Sema &S,
3111 const InitializedEntity &Entity,
3112 const InitializationKind &Kind,
3113 InitListExpr *InitList,
3114 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003115 QualType DestType = Entity.getType();
3116
Sebastian Redl14b0c192011-09-24 17:48:00 +00003117 // C++ doesn't allow scalar initialization with more than one argument.
3118 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003119 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003120 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3121 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3122 return;
3123 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003124 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003125 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003126 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003127 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003128 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003129 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003130 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003131 return;
3132 }
3133
Richard Smithf4bb8d02012-07-05 08:39:21 +00003134 // C++11 [dcl.init.list]p3:
3135 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003136 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003137 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003138 // - Otherwise, if the initializer list has no elements and T is a
3139 // class type with a default constructor, the object is
3140 // value-initialized.
3141 if (InitList->getNumInits() == 0) {
3142 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003143 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003144 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3145 return;
3146 }
3147 }
3148
3149 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3150 // an initializer_list object constructed [...]
3151 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3152 return;
3153
3154 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003155 Expr *InitListAsExpr = InitList;
3156 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003157 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003158 } else
3159 Sequence.SetFailed(
3160 InitializationSequence::FK_InitListBadDestinationType);
3161 return;
3162 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003163 }
3164
Sebastian Redl14b0c192011-09-24 17:48:00 +00003165 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003166 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003167 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00003168 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003169 if (CheckInitList.HadError()) {
3170 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3171 return;
3172 }
3173
3174 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003175 Sequence.AddListInitializationStep(DestType);
3176}
Douglas Gregor20093b42009-12-09 23:02:17 +00003177
3178/// \brief Try a reference initialization that involves calling a conversion
3179/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003180static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3181 const InitializedEntity &Entity,
3182 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003183 Expr *Initializer,
3184 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003185 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003186 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003187 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3188 QualType T1 = cv1T1.getUnqualifiedType();
3189 QualType cv2T2 = Initializer->getType();
3190 QualType T2 = cv2T2.getUnqualifiedType();
3191
3192 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003193 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003194 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003195 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003196 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003197 ObjCConversion,
3198 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003199 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003200 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003201 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003202 (void)ObjCLifetimeConversion;
3203
Douglas Gregor20093b42009-12-09 23:02:17 +00003204 // Build the candidate set directly in the initialization sequence
3205 // structure, so that it will persist if we fail.
3206 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3207 CandidateSet.clear();
3208
3209 // Determine whether we are allowed to call explicit constructors or
3210 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003211 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003212 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3213
Douglas Gregor20093b42009-12-09 23:02:17 +00003214 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003215 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3216 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003217 // The type we're converting to is a class type. Enumerate its constructors
3218 // to see if there is a suitable conversion.
3219 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003220
David Blaikie3bc93e32012-12-19 00:45:41 +00003221 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003222 // The container holding the constructors can under certain conditions
3223 // be changed while iterating (e.g. because of deserialization).
3224 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003225 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003226 for (SmallVector<NamedDecl*, 16>::iterator
3227 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3228 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003229 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3230
Douglas Gregor20093b42009-12-09 23:02:17 +00003231 // Find the constructor (which may be a template).
3232 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003233 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003234 if (ConstructorTmpl)
3235 Constructor = cast<CXXConstructorDecl>(
3236 ConstructorTmpl->getTemplatedDecl());
3237 else
John McCall9aa472c2010-03-19 07:35:19 +00003238 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003239
Douglas Gregor20093b42009-12-09 23:02:17 +00003240 if (!Constructor->isInvalidDecl() &&
3241 Constructor->isConvertingConstructor(AllowExplicit)) {
3242 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003243 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003244 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003245 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003246 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003247 else
John McCall9aa472c2010-03-19 07:35:19 +00003248 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003249 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003250 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003251 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003252 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003253 }
John McCall572fc622010-08-17 07:23:57 +00003254 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3255 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003257 const RecordType *T2RecordType = 0;
3258 if ((T2RecordType = T2->getAs<RecordType>()) &&
3259 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003260 // The type we're converting from is a class type, enumerate its conversion
3261 // functions.
3262 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3263
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003264 std::pair<CXXRecordDecl::conversion_iterator,
3265 CXXRecordDecl::conversion_iterator>
3266 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3267 for (CXXRecordDecl::conversion_iterator
3268 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003269 NamedDecl *D = *I;
3270 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3271 if (isa<UsingShadowDecl>(D))
3272 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003273
Douglas Gregor20093b42009-12-09 23:02:17 +00003274 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3275 CXXConversionDecl *Conv;
3276 if (ConvTemplate)
3277 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3278 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003279 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003280
Douglas Gregor20093b42009-12-09 23:02:17 +00003281 // If the conversion function doesn't return a reference type,
3282 // it can't be considered for this conversion unless we're allowed to
3283 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003284 // FIXME: Do we need to make sure that we only consider conversion
3285 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003286 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003287 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003288 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3289 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003290 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003291 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003292 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003293 else
John McCall9aa472c2010-03-19 07:35:19 +00003294 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003295 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003296 }
3297 }
3298 }
John McCall572fc622010-08-17 07:23:57 +00003299 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3300 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003301
Douglas Gregor20093b42009-12-09 23:02:17 +00003302 SourceLocation DeclLoc = Initializer->getLocStart();
3303
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003305 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003306 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003307 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003309
Douglas Gregor20093b42009-12-09 23:02:17 +00003310 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003311 // This is the overload that will be used for this initialization step if we
3312 // use this initialization. Mark it as referenced.
3313 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003314
Eli Friedman03981012009-12-11 02:42:07 +00003315 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003316 if (isa<CXXConversionDecl>(Function))
3317 T2 = Function->getResultType();
3318 else
3319 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003320
3321 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003322 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003323 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003324 T2.getNonLValueExprType(S.Context),
3325 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003326
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003328 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003329 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003330 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003331 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003332 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003333 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003334
Douglas Gregor20093b42009-12-09 23:02:17 +00003335 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003336 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003337 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003338 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003339 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003340 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003341 NewDerivedToBase, NewObjCConversion,
3342 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003343 if (NewRefRelationship == Sema::Ref_Incompatible) {
3344 // If the type we've converted to is not reference-related to the
3345 // type we're looking for, then there is another conversion step
3346 // we need to perform to produce a temporary of the right type
3347 // that we'll be binding to.
3348 ImplicitConversionSequence ICS;
3349 ICS.setStandard();
3350 ICS.Standard = Best->FinalConversion;
3351 T2 = ICS.Standard.getToType(2);
3352 Sequence.AddConversionSequenceStep(ICS, T2);
3353 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003354 Sequence.AddDerivedToBaseCastStep(
3355 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003356 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003357 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003358 else if (NewObjCConversion)
3359 Sequence.AddObjCObjectConversionStep(
3360 S.Context.getQualifiedType(T1,
3361 T2.getNonReferenceType().getQualifiers()));
3362
Douglas Gregor20093b42009-12-09 23:02:17 +00003363 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003364 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365
Douglas Gregor20093b42009-12-09 23:02:17 +00003366 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3367 return OR_Success;
3368}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369
Richard Smith83da2e72011-10-19 16:55:56 +00003370static void CheckCXX98CompatAccessibleCopy(Sema &S,
3371 const InitializedEntity &Entity,
3372 Expr *CurInitExpr);
3373
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003374/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3375static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003376 const InitializedEntity &Entity,
3377 const InitializationKind &Kind,
3378 Expr *Initializer,
3379 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003380 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003381 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003382 Qualifiers T1Quals;
3383 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003384 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003385 Qualifiers T2Quals;
3386 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003387
Douglas Gregor20093b42009-12-09 23:02:17 +00003388 // If the initializer is the address of an overloaded function, try
3389 // to resolve the overloaded function. If all goes well, T2 is the
3390 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003391 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3392 T1, Sequence))
3393 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003394
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003395 // Delegate everything else to a subfunction.
3396 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3397 T1Quals, cv2T2, T2, T2Quals, Sequence);
3398}
3399
Jordan Rose1fd1e282013-04-11 00:58:58 +00003400/// Converts the target of reference initialization so that it has the
3401/// appropriate qualifiers and value kind.
3402///
3403/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3404/// \code
3405/// int x;
3406/// const int &r = x;
3407/// \endcode
3408///
3409/// In this case the reference is binding to a bitfield lvalue, which isn't
3410/// valid. Perform a load to create a lifetime-extended temporary instead.
3411/// \code
3412/// const int &r = someStruct.bitfield;
3413/// \endcode
3414static ExprValueKind
3415convertQualifiersAndValueKindIfNecessary(Sema &S,
3416 InitializationSequence &Sequence,
3417 Expr *Initializer,
3418 QualType cv1T1,
3419 Qualifiers T1Quals,
3420 Qualifiers T2Quals,
3421 bool IsLValueRef) {
3422 bool IsNonAddressableType = Initializer->getBitField() ||
3423 Initializer->refersToVectorElement();
3424
3425 if (IsNonAddressableType) {
3426 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3427 // lvalue reference to a non-volatile const type, or the reference shall be
3428 // an rvalue reference.
3429 //
3430 // If not, we can't make a temporary and bind to that. Give up and allow the
3431 // error to be diagnosed later.
3432 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3433 assert(Initializer->isGLValue());
3434 return Initializer->getValueKind();
3435 }
3436
3437 // Force a load so we can materialize a temporary.
3438 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3439 return VK_RValue;
3440 }
3441
3442 if (T1Quals != T2Quals) {
3443 Sequence.AddQualificationConversionStep(cv1T1,
3444 Initializer->getValueKind());
3445 }
3446
3447 return Initializer->getValueKind();
3448}
3449
3450
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003451/// \brief Reference initialization without resolving overloaded functions.
3452static void TryReferenceInitializationCore(Sema &S,
3453 const InitializedEntity &Entity,
3454 const InitializationKind &Kind,
3455 Expr *Initializer,
3456 QualType cv1T1, QualType T1,
3457 Qualifiers T1Quals,
3458 QualType cv2T2, QualType T2,
3459 Qualifiers T2Quals,
3460 InitializationSequence &Sequence) {
3461 QualType DestType = Entity.getType();
3462 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003463 // Compute some basic properties of the types and the initializer.
3464 bool isLValueRef = DestType->isLValueReferenceType();
3465 bool isRValueRef = !isLValueRef;
3466 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003467 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003468 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003469 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003470 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003471 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003472 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003473
Douglas Gregor20093b42009-12-09 23:02:17 +00003474 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003475 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003476 // "cv2 T2" as follows:
3477 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003479 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003480 // Note the analogous bullet points for rvlaue refs to functions. Because
3481 // there are no function rvalues in C++, rvalue refs to functions are treated
3482 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003483 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003484 bool T1Function = T1->isFunctionType();
3485 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003487 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003488 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003489 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003490 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003491 // reference-compatible with "cv2 T2," or
3492 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003493 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003494 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003495 // can occur. However, we do pay attention to whether it is a bit-field
3496 // to decide whether we're actually binding to a temporary created from
3497 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003498 if (DerivedToBase)
3499 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003501 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003502 else if (ObjCConversion)
3503 Sequence.AddObjCObjectConversionStep(
3504 S.Context.getQualifiedType(T1, T2Quals));
3505
Jordan Rose1fd1e282013-04-11 00:58:58 +00003506 ExprValueKind ValueKind =
3507 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3508 cv1T1, T1Quals, T2Quals,
3509 isLValueRef);
3510 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003511 return;
3512 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003513
3514 // - has a class type (i.e., T2 is a class type), where T1 is not
3515 // reference-related to T2, and can be implicitly converted to an
3516 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3517 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003518 // applicable conversion functions (13.3.1.6) and choosing the best
3519 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003520 // If we have an rvalue ref to function type here, the rhs must be
3521 // an rvalue.
3522 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3523 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003524 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003525 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003526 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003527 Sequence);
3528 if (ConvOvlResult == OR_Success)
3529 return;
John McCall1d318332010-01-12 00:44:57 +00003530 if (ConvOvlResult != OR_No_Viable_Function) {
3531 Sequence.SetOverloadFailure(
3532 InitializationSequence::FK_ReferenceInitOverloadFailed,
3533 ConvOvlResult);
3534 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003535 }
3536 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003537
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003538 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003540 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003541 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003542 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3543 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3544 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003545 Sequence.SetOverloadFailure(
3546 InitializationSequence::FK_ReferenceInitOverloadFailed,
3547 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003548 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003549 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003550 ? (RefRelationship == Sema::Ref_Related
3551 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3552 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3553 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003554
Douglas Gregor20093b42009-12-09 23:02:17 +00003555 return;
3556 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003557
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003558 // - If the initializer expression
3559 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3560 // "cv1 T1" is reference-compatible with "cv2 T2"
3561 // Note: functions are handled below.
3562 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003563 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003564 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003565 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003566 (InitCategory.isXValue() ||
3567 (InitCategory.isPRValue() && T2->isRecordType()) ||
3568 (InitCategory.isPRValue() && T2->isArrayType()))) {
3569 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3570 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003571 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3572 // compiler the freedom to perform a copy here or bind to the
3573 // object, while C++0x requires that we bind directly to the
3574 // object. Hence, we always bind to the object without making an
3575 // extra copy. However, in C++03 requires that we check for the
3576 // presence of a suitable copy constructor:
3577 //
3578 // The constructor that would be used to make the copy shall
3579 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003580 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003581 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003582 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003583 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003584 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003585
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003586 if (DerivedToBase)
3587 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3588 ValueKind);
3589 else if (ObjCConversion)
3590 Sequence.AddObjCObjectConversionStep(
3591 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003592
Jordan Rose1fd1e282013-04-11 00:58:58 +00003593 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3594 Initializer, cv1T1,
3595 T1Quals, T2Quals,
3596 isLValueRef);
3597
3598 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003599 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003600 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003601
3602 // - has a class type (i.e., T2 is a class type), where T1 is not
3603 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003604 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3605 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003606 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003607 if (RefRelationship == Sema::Ref_Incompatible) {
3608 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3609 Kind, Initializer,
3610 /*AllowRValues=*/true,
3611 Sequence);
3612 if (ConvOvlResult)
3613 Sequence.SetOverloadFailure(
3614 InitializationSequence::FK_ReferenceInitOverloadFailed,
3615 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003616
Douglas Gregor20093b42009-12-09 23:02:17 +00003617 return;
3618 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003619
Douglas Gregordefa32e2013-03-26 23:59:23 +00003620 if ((RefRelationship == Sema::Ref_Compatible ||
3621 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3622 isRValueRef && InitCategory.isLValue()) {
3623 Sequence.SetFailed(
3624 InitializationSequence::FK_RValueReferenceBindingToLValue);
3625 return;
3626 }
3627
Douglas Gregor20093b42009-12-09 23:02:17 +00003628 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3629 return;
3630 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003631
3632 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003633 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003634 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003635 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003636
Douglas Gregor20093b42009-12-09 23:02:17 +00003637 // Determine whether we are allowed to call explicit constructors or
3638 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003639 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003640
3641 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3642
John McCallf85e1932011-06-15 23:02:42 +00003643 ImplicitConversionSequence ICS
3644 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003645 /*SuppressUserConversions*/ false,
3646 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003647 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003648 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3649 /*AllowObjCWritebackConversion=*/false);
3650
3651 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003652 // FIXME: Use the conversion function set stored in ICS to turn
3653 // this into an overloading ambiguity diagnostic. However, we need
3654 // to keep that set as an OverloadCandidateSet rather than as some
3655 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003656 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3657 Sequence.SetOverloadFailure(
3658 InitializationSequence::FK_ReferenceInitOverloadFailed,
3659 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003660 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3661 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003662 else
3663 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003664 return;
John McCallf85e1932011-06-15 23:02:42 +00003665 } else {
3666 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003667 }
3668
3669 // [...] If T1 is reference-related to T2, cv1 must be the
3670 // same cv-qualification as, or greater cv-qualification
3671 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003672 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3673 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003674 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003675 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003676 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3677 return;
3678 }
3679
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003680 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003681 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003682 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003683 InitCategory.isLValue()) {
3684 Sequence.SetFailed(
3685 InitializationSequence::FK_RValueReferenceBindingToLValue);
3686 return;
3687 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003688
Douglas Gregor20093b42009-12-09 23:02:17 +00003689 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3690 return;
3691}
3692
3693/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694/// (C++ [dcl.init.string], C99 6.7.8).
3695static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003696 const InitializedEntity &Entity,
3697 const InitializationKind &Kind,
3698 Expr *Initializer,
3699 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003700 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003701}
3702
Douglas Gregor71d17402009-12-15 00:01:57 +00003703/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003705 const InitializedEntity &Entity,
3706 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003707 InitializationSequence &Sequence,
3708 InitListExpr *InitList) {
3709 assert((!InitList || InitList->getNumInits() == 0) &&
3710 "Shouldn't use value-init for non-empty init lists");
3711
Richard Smith1d0c9a82012-02-14 21:14:13 +00003712 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003713 //
3714 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003715 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003716
Douglas Gregor71d17402009-12-15 00:01:57 +00003717 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003718 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003719
Douglas Gregor71d17402009-12-15 00:01:57 +00003720 if (const RecordType *RT = T->getAs<RecordType>()) {
3721 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003722 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003723 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003724 // C++98:
3725 // -- if T is a class type (clause 9) with a user-declared constructor
3726 // (12.1), then the default constructor for T is called (and the
3727 // initialization is ill-formed if T has no accessible default
3728 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003729 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003730 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003731 } else {
3732 // C++11:
3733 // -- if T is a class type (clause 9) with either no default constructor
3734 // (12.1 [class.ctor]) or a default constructor that is user-provided
3735 // or deleted, then the object is default-initialized;
3736 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3737 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003738 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003740
Richard Smith1d0c9a82012-02-14 21:14:13 +00003741 // -- if T is a (possibly cv-qualified) non-union class type without a
3742 // user-provided or deleted default constructor, then the object is
3743 // zero-initialized and, if T has a non-trivial default constructor,
3744 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003745 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3746 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003747 if (NeedZeroInitialization)
3748 Sequence.AddZeroInitializationStep(Entity.getType());
3749
Richard Smithd5bc8672012-12-08 02:01:17 +00003750 // C++03:
3751 // -- if T is a non-union class type without a user-declared constructor,
3752 // then every non-static data member and base class component of T is
3753 // value-initialized;
3754 // [...] A program that calls for [...] value-initialization of an
3755 // entity of reference type is ill-formed.
3756 //
3757 // C++11 doesn't need this handling, because value-initialization does not
3758 // occur recursively there, and the implicit default constructor is
3759 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003760 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003761 ClassDecl->hasUninitializedReferenceMember()) {
3762 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3763 return;
3764 }
3765
Richard Smithf4bb8d02012-07-05 08:39:21 +00003766 // If this is list-value-initialization, pass the empty init list on when
3767 // building the constructor call. This affects the semantics of a few
3768 // things (such as whether an explicit default constructor can be called).
3769 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003770 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003771 bool InitListSyntax = InitList;
3772
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003773 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3774 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003775 }
3776 }
3777
Douglas Gregord6542d82009-12-22 15:35:07 +00003778 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003779}
3780
Douglas Gregor99a2e602009-12-16 01:38:02 +00003781/// \brief Attempt default initialization (C++ [dcl.init]p6).
3782static void TryDefaultInitialization(Sema &S,
3783 const InitializedEntity &Entity,
3784 const InitializationKind &Kind,
3785 InitializationSequence &Sequence) {
3786 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003787
Douglas Gregor99a2e602009-12-16 01:38:02 +00003788 // C++ [dcl.init]p6:
3789 // To default-initialize an object of type T means:
3790 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003791 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3792
Douglas Gregor99a2e602009-12-16 01:38:02 +00003793 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3794 // constructor for T is called (and the initialization is ill-formed if
3795 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003796 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003797 TryConstructorInitialization(S, Entity, Kind, MultiExprArg(), DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003798 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003799 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003800
Douglas Gregor99a2e602009-12-16 01:38:02 +00003801 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003802
Douglas Gregor99a2e602009-12-16 01:38:02 +00003803 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003804 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003805 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003806 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003807 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003808 return;
3809 }
3810
3811 // If the destination type has a lifetime property, zero-initialize it.
3812 if (DestType.getQualifiers().hasObjCLifetime()) {
3813 Sequence.AddZeroInitializationStep(Entity.getType());
3814 return;
3815 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003816}
3817
Douglas Gregor20093b42009-12-09 23:02:17 +00003818/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3819/// which enumerates all conversion functions and performs overload resolution
3820/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003821static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003822 const InitializedEntity &Entity,
3823 const InitializationKind &Kind,
3824 Expr *Initializer,
3825 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003826 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003827 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3828 QualType SourceType = Initializer->getType();
3829 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3830 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003831
Douglas Gregor4a520a22009-12-14 17:27:33 +00003832 // Build the candidate set directly in the initialization sequence
3833 // structure, so that it will persist if we fail.
3834 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3835 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003836
Douglas Gregor4a520a22009-12-14 17:27:33 +00003837 // Determine whether we are allowed to call explicit constructors or
3838 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003839 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003840
Douglas Gregor4a520a22009-12-14 17:27:33 +00003841 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3842 // The type we're converting to is a class type. Enumerate its constructors
3843 // to see if there is a suitable conversion.
3844 CXXRecordDecl *DestRecordDecl
3845 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003847 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003848 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00003849 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003850 // The container holding the constructors can under certain conditions
3851 // be changed while iterating. To be safe we copy the lookup results
3852 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003853 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003854 for (SmallVector<NamedDecl*, 8>::iterator
3855 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003856 Con != ConEnd; ++Con) {
3857 NamedDecl *D = *Con;
3858 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003859
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003860 // Find the constructor (which may be a template).
3861 CXXConstructorDecl *Constructor = 0;
3862 FunctionTemplateDecl *ConstructorTmpl
3863 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003864 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003865 Constructor = cast<CXXConstructorDecl>(
3866 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003867 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003868 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003869
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003870 if (!Constructor->isInvalidDecl() &&
3871 Constructor->isConvertingConstructor(AllowExplicit)) {
3872 if (ConstructorTmpl)
3873 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3874 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003875 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003876 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003877 else
3878 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003879 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003880 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003881 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003882 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003883 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003884 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003885
3886 SourceLocation DeclLoc = Initializer->getLocStart();
3887
Douglas Gregor4a520a22009-12-14 17:27:33 +00003888 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3889 // The type we're converting from is a class type, enumerate its conversion
3890 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003891
Eli Friedman33c2da92009-12-20 22:12:03 +00003892 // We can only enumerate the conversion functions for a complete type; if
3893 // the type isn't complete, simply skip this step.
3894 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3895 CXXRecordDecl *SourceRecordDecl
3896 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003897
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003898 std::pair<CXXRecordDecl::conversion_iterator,
3899 CXXRecordDecl::conversion_iterator>
3900 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3901 for (CXXRecordDecl::conversion_iterator
3902 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003903 NamedDecl *D = *I;
3904 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3905 if (isa<UsingShadowDecl>(D))
3906 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003907
Eli Friedman33c2da92009-12-20 22:12:03 +00003908 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3909 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003910 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003911 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003912 else
John McCall32daa422010-03-31 01:36:47 +00003913 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003914
Eli Friedman33c2da92009-12-20 22:12:03 +00003915 if (AllowExplicit || !Conv->isExplicit()) {
3916 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003917 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003918 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003919 CandidateSet);
3920 else
John McCall9aa472c2010-03-19 07:35:19 +00003921 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003922 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003923 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003924 }
3925 }
3926 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003927
3928 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003929 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003930 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003931 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003932 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003933 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003934 Result);
3935 return;
3936 }
John McCall1d318332010-01-12 00:44:57 +00003937
Douglas Gregor4a520a22009-12-14 17:27:33 +00003938 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003939 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003940 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003941
Douglas Gregor4a520a22009-12-14 17:27:33 +00003942 if (isa<CXXConstructorDecl>(Function)) {
3943 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003944 // subsumed by the initialization. Per DR5, the created temporary is of the
3945 // cv-unqualified type of the destination.
3946 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3947 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003948 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003949 return;
3950 }
3951
3952 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003953 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003954 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003955 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003956 // the resulting temporary object (possible to create an object of
3957 // a base class type). That copy is not a separate conversion, so
3958 // we just make a note of the actual destination type (possibly a
3959 // base class of the type returned by the conversion function) and
3960 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003961 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3962 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003963 return;
3964 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003965
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003966 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3967 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003968
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003969 // If the conversion following the call to the conversion function
3970 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003971 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3972 Best->FinalConversion.Third) {
3973 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003974 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003975 ICS.Standard = Best->FinalConversion;
3976 Sequence.AddConversionSequenceStep(ICS, DestType);
3977 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003978}
3979
John McCallf85e1932011-06-15 23:02:42 +00003980/// The non-zero enum values here are indexes into diagnostic alternatives.
3981enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3982
3983/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003984static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003985 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00003986 // Skip parens.
3987 e = e->IgnoreParens();
3988
3989 // Skip address-of nodes.
3990 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3991 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003992 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
3993 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00003994
3995 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003996 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3997 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003998 case CK_Dependent:
3999 case CK_BitCast:
4000 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004001 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004002 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004003
4004 case CK_ArrayToPointerDecay:
4005 return IIK_nonscalar;
4006
4007 case CK_NullToPointer:
4008 return IIK_okay;
4009
4010 default:
4011 break;
4012 }
4013
4014 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004015 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004016 // set isWeakAccess to true, to mean that there will be an implicit
4017 // load which requires a cleanup.
4018 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4019 isWeakAccess = true;
4020
John McCallc03fa492011-06-27 23:59:58 +00004021 if (!isAddressOf) return IIK_nonlocal;
4022
John McCallf4b88a42012-03-10 09:33:50 +00004023 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4024 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004025
4026 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004027
4028 // If we have a conditional operator, check both sides.
4029 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004030 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4031 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004032 return iik;
4033
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004034 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004035
4036 // These are never scalar.
4037 } else if (isa<ArraySubscriptExpr>(e)) {
4038 return IIK_nonscalar;
4039
4040 // Otherwise, it needs to be a null pointer constant.
4041 } else {
4042 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4043 ? IIK_okay : IIK_nonlocal);
4044 }
4045
4046 return IIK_nonlocal;
4047}
4048
4049/// Check whether the given expression is a valid operand for an
4050/// indirect copy/restore.
4051static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4052 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004053 bool isWeakAccess = false;
4054 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4055 // If isWeakAccess to true, there will be an implicit
4056 // load which requires a cleanup.
4057 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4058 S.ExprNeedsCleanups = true;
4059
John McCallf85e1932011-06-15 23:02:42 +00004060 if (iik == IIK_okay) return;
4061
4062 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4063 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4064 << src->getSourceRange();
4065}
4066
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004067/// \brief Determine whether we have compatible array types for the
4068/// purposes of GNU by-copy array initialization.
4069static bool hasCompatibleArrayTypes(ASTContext &Context,
4070 const ArrayType *Dest,
4071 const ArrayType *Source) {
4072 // If the source and destination array types are equivalent, we're
4073 // done.
4074 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4075 return true;
4076
4077 // Make sure that the element types are the same.
4078 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4079 return false;
4080
4081 // The only mismatch we allow is when the destination is an
4082 // incomplete array type and the source is a constant array type.
4083 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4084}
4085
John McCallf85e1932011-06-15 23:02:42 +00004086static bool tryObjCWritebackConversion(Sema &S,
4087 InitializationSequence &Sequence,
4088 const InitializedEntity &Entity,
4089 Expr *Initializer) {
4090 bool ArrayDecay = false;
4091 QualType ArgType = Initializer->getType();
4092 QualType ArgPointee;
4093 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4094 ArrayDecay = true;
4095 ArgPointee = ArgArrayType->getElementType();
4096 ArgType = S.Context.getPointerType(ArgPointee);
4097 }
4098
4099 // Handle write-back conversion.
4100 QualType ConvertedArgType;
4101 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4102 ConvertedArgType))
4103 return false;
4104
4105 // We should copy unless we're passing to an argument explicitly
4106 // marked 'out'.
4107 bool ShouldCopy = true;
4108 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4109 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4110
4111 // Do we need an lvalue conversion?
4112 if (ArrayDecay || Initializer->isGLValue()) {
4113 ImplicitConversionSequence ICS;
4114 ICS.setStandard();
4115 ICS.Standard.setAsIdentityConversion();
4116
4117 QualType ResultType;
4118 if (ArrayDecay) {
4119 ICS.Standard.First = ICK_Array_To_Pointer;
4120 ResultType = S.Context.getPointerType(ArgPointee);
4121 } else {
4122 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4123 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4124 }
4125
4126 Sequence.AddConversionSequenceStep(ICS, ResultType);
4127 }
4128
4129 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4130 return true;
4131}
4132
Guy Benyei21f18c42013-02-07 10:55:47 +00004133static bool TryOCLSamplerInitialization(Sema &S,
4134 InitializationSequence &Sequence,
4135 QualType DestType,
4136 Expr *Initializer) {
4137 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4138 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4139 return false;
4140
4141 Sequence.AddOCLSamplerInitStep(DestType);
4142 return true;
4143}
4144
Guy Benyeie6b9d802013-01-20 12:31:11 +00004145//
4146// OpenCL 1.2 spec, s6.12.10
4147//
4148// The event argument can also be used to associate the
4149// async_work_group_copy with a previous async copy allowing
4150// an event to be shared by multiple async copies; otherwise
4151// event should be zero.
4152//
4153static bool TryOCLZeroEventInitialization(Sema &S,
4154 InitializationSequence &Sequence,
4155 QualType DestType,
4156 Expr *Initializer) {
4157 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4158 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4159 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4160 return false;
4161
4162 Sequence.AddOCLZeroEventStep(DestType);
4163 return true;
4164}
4165
Douglas Gregor20093b42009-12-09 23:02:17 +00004166InitializationSequence::InitializationSequence(Sema &S,
4167 const InitializedEntity &Entity,
4168 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004169 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004170 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004171 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004172
John McCall76da55d2013-04-16 07:28:30 +00004173 // Eliminate non-overload placeholder types in the arguments. We
4174 // need to do this before checking whether types are dependent
4175 // because lowering a pseudo-object expression might well give us
4176 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004177 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004178 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4179 // FIXME: should we be doing this here?
4180 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4181 if (result.isInvalid()) {
4182 SetFailed(FK_PlaceholderType);
4183 return;
4184 }
4185 Args[I] = result.take();
4186 }
4187
Douglas Gregor20093b42009-12-09 23:02:17 +00004188 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004189 // The semantics of initializers are as follows. The destination type is
4190 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004191 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004192 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004193 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004194 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004195
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004196 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004197 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004198 SequenceKind = DependentSequence;
4199 return;
4200 }
4201
Sebastian Redl7491c492011-06-05 13:59:11 +00004202 // Almost everything is a normal sequence.
4203 setSequenceKind(NormalSequence);
4204
Douglas Gregor20093b42009-12-09 23:02:17 +00004205 QualType SourceType;
4206 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004207 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004208 Initializer = Args[0];
4209 if (!isa<InitListExpr>(Initializer))
4210 SourceType = Initializer->getType();
4211 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004212
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004213 // - If the initializer is a (non-parenthesized) braced-init-list, the
4214 // object is list-initialized (8.5.4).
4215 if (Kind.getKind() != InitializationKind::IK_Direct) {
4216 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4217 TryListInitialization(S, Entity, Kind, InitList, *this);
4218 return;
4219 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004220 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004221
Douglas Gregor20093b42009-12-09 23:02:17 +00004222 // - If the destination type is a reference type, see 8.5.3.
4223 if (DestType->isReferenceType()) {
4224 // C++0x [dcl.init.ref]p1:
4225 // A variable declared to be a T& or T&&, that is, "reference to type T"
4226 // (8.3.2), shall be initialized by an object, or function, of type T or
4227 // by an object that can be converted into a T.
4228 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004229 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004230 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004231 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004232 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004233 return;
4234 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004235
Douglas Gregor20093b42009-12-09 23:02:17 +00004236 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004237 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004238 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004239 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004240 return;
4241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004242
Douglas Gregor99a2e602009-12-16 01:38:02 +00004243 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004244 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004245 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004246 return;
4247 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004248
John McCallce6c9b72011-02-21 07:22:22 +00004249 // - If the destination type is an array of characters, an array of
4250 // char16_t, an array of char32_t, or an array of wchar_t, and the
4251 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004252 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004253 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004254 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004255 if (Initializer && isa<VariableArrayType>(DestAT)) {
4256 SetFailed(FK_VariableLengthArrayHasInitializer);
4257 return;
4258 }
4259
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004260 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004261 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004262 return;
4263 }
4264
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004265 // Note: as an GNU C extension, we allow initialization of an
4266 // array from a compound literal that creates an array of the same
4267 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004268 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004269 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4270 Initializer->getType()->isArrayType()) {
4271 const ArrayType *SourceAT
4272 = Context.getAsArrayType(Initializer->getType());
4273 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004274 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004275 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004276 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004277 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004278 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004279 }
Richard Smith0f163e92012-02-15 22:38:09 +00004280 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004281 // Note: as a GNU C++ extension, we allow list-initialization of a
4282 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004283 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004284 Entity.getKind() == InitializedEntity::EK_Member &&
4285 Initializer && isa<InitListExpr>(Initializer)) {
4286 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4287 *this);
4288 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004289 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004290 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004291 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004292 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004293
Douglas Gregor20093b42009-12-09 23:02:17 +00004294 return;
4295 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004296
John McCallf85e1932011-06-15 23:02:42 +00004297 // Determine whether we should consider writeback conversions for
4298 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004299 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004300 Entity.getKind() == InitializedEntity::EK_Parameter;
4301
4302 // We're at the end of the line for C: it's either a write-back conversion
4303 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004304 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004305 // If allowed, check whether this is an Objective-C writeback conversion.
4306 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004307 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004308 return;
4309 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004310
4311 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4312 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004313
4314 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4315 return;
4316
John McCallf85e1932011-06-15 23:02:42 +00004317 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004318 AddCAssignmentStep(DestType);
4319 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004320 return;
4321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004322
David Blaikie4e4d0842012-03-11 07:00:24 +00004323 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004324
Douglas Gregor20093b42009-12-09 23:02:17 +00004325 // - If the destination type is a (possibly cv-qualified) class type:
4326 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327 // - If the initialization is direct-initialization, or if it is
4328 // copy-initialization where the cv-unqualified version of the
4329 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004330 // class of the destination, constructors are considered. [...]
4331 if (Kind.getKind() == InitializationKind::IK_Direct ||
4332 (Kind.getKind() == InitializationKind::IK_Copy &&
4333 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4334 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004335 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004336 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004337 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004338 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004339 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004340 // used) to a derived class thereof are enumerated as described in
4341 // 13.3.1.4, and the best one is chosen through overload resolution
4342 // (13.3).
4343 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004344 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004345 return;
4346 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004347
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004348 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004349 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004350 return;
4351 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004352 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004353
4354 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004355 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004356 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004357 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4358 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004359 return;
4360 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004361
Douglas Gregor20093b42009-12-09 23:02:17 +00004362 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004363 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004364 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004365 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004366 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004367
4368 ImplicitConversionSequence ICS
4369 = S.TryImplicitConversion(Initializer, Entity.getType(),
4370 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004371 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004372 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004373 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4374 allowObjCWritebackConversion);
4375
4376 if (ICS.isStandard() &&
4377 ICS.Standard.Second == ICK_Writeback_Conversion) {
4378 // Objective-C ARC writeback conversion.
4379
4380 // We should copy unless we're passing to an argument explicitly
4381 // marked 'out'.
4382 bool ShouldCopy = true;
4383 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4384 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4385
4386 // If there was an lvalue adjustment, add it as a separate conversion.
4387 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4388 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4389 ImplicitConversionSequence LvalueICS;
4390 LvalueICS.setStandard();
4391 LvalueICS.Standard.setAsIdentityConversion();
4392 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4393 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004394 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004395 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004396
4397 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004398 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004399 DeclAccessPair dap;
4400 if (Initializer->getType() == Context.OverloadTy &&
4401 !S.ResolveAddressOfOverloadedFunction(Initializer
4402 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004403 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004404 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004405 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004406 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004407 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004408
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004409 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004410 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004411}
4412
4413InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004414 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004415 StepEnd = Steps.end();
4416 Step != StepEnd; ++Step)
4417 Step->Destroy();
4418}
4419
4420//===----------------------------------------------------------------------===//
4421// Perform initialization
4422//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004423static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004424getAssignmentAction(const InitializedEntity &Entity) {
4425 switch(Entity.getKind()) {
4426 case InitializedEntity::EK_Variable:
4427 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004428 case InitializedEntity::EK_Exception:
4429 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004430 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004431 return Sema::AA_Initializing;
4432
4433 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004435 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4436 return Sema::AA_Sending;
4437
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004438 return Sema::AA_Passing;
4439
4440 case InitializedEntity::EK_Result:
4441 return Sema::AA_Returning;
4442
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004443 case InitializedEntity::EK_Temporary:
4444 // FIXME: Can we tell apart casting vs. converting?
4445 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004447 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004448 case InitializedEntity::EK_ArrayElement:
4449 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004450 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004451 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004452 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004453 return Sema::AA_Initializing;
4454 }
4455
David Blaikie7530c032012-01-17 06:56:22 +00004456 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004457}
4458
Richard Smith774d8b42013-01-08 00:08:23 +00004459/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004460/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004461static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004462 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004463 case InitializedEntity::EK_ArrayElement:
4464 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004465 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004466 case InitializedEntity::EK_New:
4467 case InitializedEntity::EK_Variable:
4468 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004469 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004470 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004471 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004472 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004473 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004474 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004475 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004476
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004477 case InitializedEntity::EK_Parameter:
4478 case InitializedEntity::EK_Temporary:
4479 return true;
4480 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004481
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004482 llvm_unreachable("missed an InitializedEntity kind?");
4483}
4484
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004485/// \brief Whether the given entity, when initialized with an object
4486/// created for that initialization, requires destruction.
4487static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4488 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004489 case InitializedEntity::EK_Result:
4490 case InitializedEntity::EK_New:
4491 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004492 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004493 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004494 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004495 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004496 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004497 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004498
Richard Smith774d8b42013-01-08 00:08:23 +00004499 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004500 case InitializedEntity::EK_Variable:
4501 case InitializedEntity::EK_Parameter:
4502 case InitializedEntity::EK_Temporary:
4503 case InitializedEntity::EK_ArrayElement:
4504 case InitializedEntity::EK_Exception:
4505 return true;
4506 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004507
4508 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004509}
4510
Richard Smith83da2e72011-10-19 16:55:56 +00004511/// \brief Look for copy and move constructors and constructor templates, for
4512/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4513static void LookupCopyAndMoveConstructors(Sema &S,
4514 OverloadCandidateSet &CandidateSet,
4515 CXXRecordDecl *Class,
4516 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004517 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004518 // The container holding the constructors can under certain conditions
4519 // be changed while iterating (e.g. because of deserialization).
4520 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004521 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004522 for (SmallVector<NamedDecl*, 16>::iterator
4523 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4524 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004525 CXXConstructorDecl *Constructor = 0;
4526
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004527 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004528 // Handle copy/moveconstructors, only.
4529 if (!Constructor || Constructor->isInvalidDecl() ||
4530 !Constructor->isCopyOrMoveConstructor() ||
4531 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4532 continue;
4533
4534 DeclAccessPair FoundDecl
4535 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4536 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004537 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004538 continue;
4539 }
4540
4541 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004542 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004543 if (ConstructorTmpl->isInvalidDecl())
4544 continue;
4545
4546 Constructor = cast<CXXConstructorDecl>(
4547 ConstructorTmpl->getTemplatedDecl());
4548 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4549 continue;
4550
4551 // FIXME: Do we need to limit this to copy-constructor-like
4552 // candidates?
4553 DeclAccessPair FoundDecl
4554 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4555 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004556 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004557 }
4558}
4559
4560/// \brief Get the location at which initialization diagnostics should appear.
4561static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4562 Expr *Initializer) {
4563 switch (Entity.getKind()) {
4564 case InitializedEntity::EK_Result:
4565 return Entity.getReturnLoc();
4566
4567 case InitializedEntity::EK_Exception:
4568 return Entity.getThrowLoc();
4569
4570 case InitializedEntity::EK_Variable:
4571 return Entity.getDecl()->getLocation();
4572
Douglas Gregor47736542012-02-15 16:57:26 +00004573 case InitializedEntity::EK_LambdaCapture:
4574 return Entity.getCaptureLoc();
4575
Richard Smith83da2e72011-10-19 16:55:56 +00004576 case InitializedEntity::EK_ArrayElement:
4577 case InitializedEntity::EK_Member:
4578 case InitializedEntity::EK_Parameter:
4579 case InitializedEntity::EK_Temporary:
4580 case InitializedEntity::EK_New:
4581 case InitializedEntity::EK_Base:
4582 case InitializedEntity::EK_Delegating:
4583 case InitializedEntity::EK_VectorElement:
4584 case InitializedEntity::EK_ComplexElement:
4585 case InitializedEntity::EK_BlockElement:
4586 return Initializer->getLocStart();
4587 }
4588 llvm_unreachable("missed an InitializedEntity kind?");
4589}
4590
Douglas Gregor523d46a2010-04-18 07:40:54 +00004591/// \brief Make a (potentially elidable) temporary copy of the object
4592/// provided by the given initializer by calling the appropriate copy
4593/// constructor.
4594///
4595/// \param S The Sema object used for type-checking.
4596///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004597/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004598/// the type of the initializer expression or a superclass thereof.
4599///
James Dennett1dfbd922012-06-14 21:40:34 +00004600/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004601///
4602/// \param CurInit The initializer expression.
4603///
4604/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4605/// is permitted in C++03 (but not C++0x) when binding a reference to
4606/// an rvalue.
4607///
4608/// \returns An expression that copies the initializer expression into
4609/// a temporary object, or an error expression if a copy could not be
4610/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004611static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004612 QualType T,
4613 const InitializedEntity &Entity,
4614 ExprResult CurInit,
4615 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004616 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004617 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004618 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004619 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004620 Class = cast<CXXRecordDecl>(Record->getDecl());
4621 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004622 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004623
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004624 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004625 // When certain criteria are met, an implementation is allowed to
4626 // omit the copy/move construction of a class object, even if the
4627 // copy/move constructor and/or destructor for the object have
4628 // side effects. [...]
4629 // - when a temporary class object that has not been bound to a
4630 // reference (12.2) would be copied/moved to a class object
4631 // with the same cv-unqualified type, the copy/move operation
4632 // can be omitted by constructing the temporary object
4633 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004635 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004636 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004637 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004638 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004639 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004640 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004641
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004642 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004643 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004644 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004645
Douglas Gregorcc15f012011-01-21 19:38:21 +00004646 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004647 // Only consider constructors and constructor templates. Per
4648 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4649 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004650 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004651 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004652
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004653 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4654
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004655 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004656 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004657 case OR_Success:
4658 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004660 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004661 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4662 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4663 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004664 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004665 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004666 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004667 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004668 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004669 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004670
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004671 case OR_Ambiguous:
4672 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004673 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004674 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004675 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004676 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004678 case OR_Deleted:
4679 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004680 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004681 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004682 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004683 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004684 }
4685
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004686 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004687 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004688 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004689
Anders Carlsson9a68a672010-04-21 18:47:17 +00004690 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004691 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004692
4693 if (IsExtraneousCopy) {
4694 // If this is a totally extraneous copy for C++03 reference
4695 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004696 // expression. We don't generate an (elided) copy operation here
4697 // because doing so would require us to pass down a flag to avoid
4698 // infinite recursion, where each step adds another extraneous,
4699 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004700
Douglas Gregor2559a702010-04-18 07:57:34 +00004701 // Instantiate the default arguments of any extra parameters in
4702 // the selected copy constructor, as if we were going to create a
4703 // proper call to the copy constructor.
4704 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4705 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4706 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004707 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004708 break;
4709
4710 // Build the default argument expression; we don't actually care
4711 // if this succeeds or not, because this routine will complain
4712 // if there was a problem.
4713 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4714 }
4715
Douglas Gregor523d46a2010-04-18 07:40:54 +00004716 return S.Owned(CurInitExpr);
4717 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004718
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004719 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004720 // constructor call (we might have derived-to-base conversions, or
4721 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004722 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004723 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004724
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004725 // Actually perform the constructor call.
4726 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004727 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004728 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004729 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004730 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004731 CXXConstructExpr::CK_Complete,
4732 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004733
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004734 // If we're supposed to bind temporaries, do so.
4735 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4736 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004737 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004738}
Douglas Gregor20093b42009-12-09 23:02:17 +00004739
Richard Smith83da2e72011-10-19 16:55:56 +00004740/// \brief Check whether elidable copy construction for binding a reference to
4741/// a temporary would have succeeded if we were building in C++98 mode, for
4742/// -Wc++98-compat.
4743static void CheckCXX98CompatAccessibleCopy(Sema &S,
4744 const InitializedEntity &Entity,
4745 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004746 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004747
4748 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4749 if (!Record)
4750 return;
4751
4752 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4753 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4754 == DiagnosticsEngine::Ignored)
4755 return;
4756
4757 // Find constructors which would have been considered.
4758 OverloadCandidateSet CandidateSet(Loc);
4759 LookupCopyAndMoveConstructors(
4760 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4761
4762 // Perform overload resolution.
4763 OverloadCandidateSet::iterator Best;
4764 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4765
4766 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4767 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4768 << CurInitExpr->getSourceRange();
4769
4770 switch (OR) {
4771 case OR_Success:
4772 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004773 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004774 // FIXME: Check default arguments as far as that's possible.
4775 break;
4776
4777 case OR_No_Viable_Function:
4778 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004779 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004780 break;
4781
4782 case OR_Ambiguous:
4783 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004784 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004785 break;
4786
4787 case OR_Deleted:
4788 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004789 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004790 break;
4791 }
4792}
4793
Douglas Gregora41a8c52010-04-22 00:20:18 +00004794void InitializationSequence::PrintInitLocationNote(Sema &S,
4795 const InitializedEntity &Entity) {
4796 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4797 if (Entity.getDecl()->getLocation().isInvalid())
4798 return;
4799
4800 if (Entity.getDecl()->getDeclName())
4801 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4802 << Entity.getDecl()->getDeclName();
4803 else
4804 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4805 }
4806}
4807
Sebastian Redl3b802322011-07-14 19:07:55 +00004808static bool isReferenceBinding(const InitializationSequence::Step &s) {
4809 return s.Kind == InitializationSequence::SK_BindReference ||
4810 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4811}
4812
Sebastian Redl10f04a62011-12-22 14:44:04 +00004813static ExprResult
4814PerformConstructorInitialization(Sema &S,
4815 const InitializedEntity &Entity,
4816 const InitializationKind &Kind,
4817 MultiExprArg Args,
4818 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00004819 bool &ConstructorInitRequiresZeroInit,
4820 bool IsListInitialization) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004821 unsigned NumArgs = Args.size();
4822 CXXConstructorDecl *Constructor
4823 = cast<CXXConstructorDecl>(Step.Function.Function);
4824 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4825
4826 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004827 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004828 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4829 ? Kind.getEqualLoc()
4830 : Kind.getLocation();
4831
4832 if (Kind.getKind() == InitializationKind::IK_Default) {
4833 // Force even a trivial, implicit default constructor to be
4834 // semantically checked. We do this explicitly because we don't build
4835 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004836 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004837 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004838 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004839 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4840 }
4841
4842 ExprResult CurInit = S.Owned((Expr *)0);
4843
Douglas Gregored878af2012-02-24 23:56:31 +00004844 // C++ [over.match.copy]p1:
4845 // - When initializing a temporary to be bound to the first parameter
4846 // of a constructor that takes a reference to possibly cv-qualified
4847 // T as its first argument, called with a single argument in the
4848 // context of direct-initialization, explicit conversion functions
4849 // are also considered.
4850 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4851 Args.size() == 1 &&
4852 Constructor->isCopyOrMoveConstructor();
4853
Sebastian Redl10f04a62011-12-22 14:44:04 +00004854 // Determine the arguments required to actually perform the constructor
4855 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004856 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004857 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004858 AllowExplicitConv,
4859 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004860 return ExprError();
4861
4862
4863 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Sebastian Redl188158d2012-03-08 21:05:45 +00004864 (Kind.getKind() == InitializationKind::IK_DirectList ||
4865 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4866 (Kind.getKind() == InitializationKind::IK_Direct ||
4867 Kind.getKind() == InitializationKind::IK_Value)))) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004868 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004869 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00004870 if (S.DiagnoseUseOfDecl(Constructor, Loc))
4871 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004872
4873 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4874 if (!TSInfo)
4875 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004876 SourceRange ParenRange;
4877 if (Kind.getKind() != InitializationKind::IK_DirectList)
4878 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004879
Richard Smithc83c2302012-12-19 01:39:02 +00004880 CurInit = S.Owned(
4881 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4882 TSInfo, ConstructorArgs,
4883 ParenRange, IsListInitialization,
4884 HadMultipleCandidates,
4885 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00004886 } else {
4887 CXXConstructExpr::ConstructionKind ConstructKind =
4888 CXXConstructExpr::CK_Complete;
4889
4890 if (Entity.getKind() == InitializedEntity::EK_Base) {
4891 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4892 CXXConstructExpr::CK_VirtualBase :
4893 CXXConstructExpr::CK_NonVirtualBase;
4894 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4895 ConstructKind = CXXConstructExpr::CK_Delegating;
4896 }
4897
4898 // Only get the parenthesis range if it is a direct construction.
4899 SourceRange parenRange =
4900 Kind.getKind() == InitializationKind::IK_Direct ?
4901 Kind.getParenRange() : SourceRange();
4902
4903 // If the entity allows NRVO, mark the construction as elidable
4904 // unconditionally.
4905 if (Entity.allowsNRVO())
4906 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4907 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004908 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004909 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004910 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004911 ConstructorInitRequiresZeroInit,
4912 ConstructKind,
4913 parenRange);
4914 else
4915 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4916 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004917 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004918 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004919 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004920 ConstructorInitRequiresZeroInit,
4921 ConstructKind,
4922 parenRange);
4923 }
4924 if (CurInit.isInvalid())
4925 return ExprError();
4926
4927 // Only check access if all of that succeeded.
4928 S.CheckConstructorAccess(Loc, Constructor, Entity,
4929 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00004930 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
4931 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004932
4933 if (shouldBindAsTemporary(Entity))
4934 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4935
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004936 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004937}
4938
Richard Smith36d02af2012-06-04 22:27:30 +00004939/// Determine whether the specified InitializedEntity definitely has a lifetime
4940/// longer than the current full-expression. Conservatively returns false if
4941/// it's unclear.
4942static bool
4943InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4944 const InitializedEntity *Top = &Entity;
4945 while (Top->getParent())
4946 Top = Top->getParent();
4947
4948 switch (Top->getKind()) {
4949 case InitializedEntity::EK_Variable:
4950 case InitializedEntity::EK_Result:
4951 case InitializedEntity::EK_Exception:
4952 case InitializedEntity::EK_Member:
4953 case InitializedEntity::EK_New:
4954 case InitializedEntity::EK_Base:
4955 case InitializedEntity::EK_Delegating:
4956 return true;
4957
4958 case InitializedEntity::EK_ArrayElement:
4959 case InitializedEntity::EK_VectorElement:
4960 case InitializedEntity::EK_BlockElement:
4961 case InitializedEntity::EK_ComplexElement:
4962 // Could not determine what the full initialization is. Assume it might not
4963 // outlive the full-expression.
4964 return false;
4965
4966 case InitializedEntity::EK_Parameter:
4967 case InitializedEntity::EK_Temporary:
4968 case InitializedEntity::EK_LambdaCapture:
4969 // The entity being initialized might not outlive the full-expression.
4970 return false;
4971 }
4972
4973 llvm_unreachable("unknown entity kind");
4974}
4975
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004976ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004977InitializationSequence::Perform(Sema &S,
4978 const InitializedEntity &Entity,
4979 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004980 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004981 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004982 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004983 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00004984 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004985 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004986
Sebastian Redl7491c492011-06-05 13:59:11 +00004987 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004988 // If the declaration is a non-dependent, incomplete array type
4989 // that has an initializer, then its type will be completed once
4990 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004991 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004992 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004993 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004994 if (const IncompleteArrayType *ArrayT
4995 = S.Context.getAsIncompleteArrayType(DeclType)) {
4996 // FIXME: We don't currently have the ability to accurately
4997 // compute the length of an initializer list without
4998 // performing full type-checking of the initializer list
4999 // (since we have to determine where braces are implicitly
5000 // introduced and such). So, we fall back to making the array
5001 // type a dependently-sized array type with no specified
5002 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005003 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005004 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005005
Douglas Gregord87b61f2009-12-10 17:56:55 +00005006 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005007 if (DeclaratorDecl *DD = Entity.getDecl()) {
5008 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5009 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005010 if (IncompleteArrayTypeLoc ArrayLoc =
5011 TL.getAs<IncompleteArrayTypeLoc>())
5012 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005013 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005014 }
5015
5016 *ResultType
5017 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5018 /*NumElts=*/0,
5019 ArrayT->getSizeModifier(),
5020 ArrayT->getIndexTypeCVRQualifiers(),
5021 Brackets);
5022 }
5023
5024 }
5025 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005026 if (Kind.getKind() == InitializationKind::IK_Direct &&
5027 !Kind.isExplicitCast()) {
5028 // Rebuild the ParenListExpr.
5029 SourceRange ParenRange = Kind.getParenRange();
5030 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005031 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005032 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005033 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005034 Kind.isExplicitCast() ||
5035 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005036 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005037 }
5038
Sebastian Redl7491c492011-06-05 13:59:11 +00005039 // No steps means no initialization.
5040 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005041 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005042
Richard Smith80ad52f2013-01-02 11:42:31 +00005043 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005044 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00005045 Entity.getKind() != InitializedEntity::EK_Parameter) {
5046 // Produce a C++98 compatibility warning if we are initializing a reference
5047 // from an initializer list. For parameters, we produce a better warning
5048 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005049 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005050 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5051 << Init->getSourceRange();
5052 }
5053
Richard Smith36d02af2012-06-04 22:27:30 +00005054 // Diagnose cases where we initialize a pointer to an array temporary, and the
5055 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005056 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005057 Entity.getType()->isPointerType() &&
5058 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005059 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005060 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5061 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5062 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5063 << Init->getSourceRange();
5064 }
5065
Douglas Gregord6542d82009-12-22 15:35:07 +00005066 QualType DestType = Entity.getType().getNonReferenceType();
5067 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005068 // the same as Entity.getDecl()->getType() in cases involving type merging,
5069 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005070 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005071 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005072 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005073
John McCall60d7b3a2010-08-24 06:29:42 +00005074 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005075
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005076 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005077 // grab the only argument out the Args and place it into the "current"
5078 // initializer.
5079 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005080 case SK_ResolveAddressOfOverloadedFunction:
5081 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005082 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005083 case SK_CastDerivedToBaseLValue:
5084 case SK_BindReference:
5085 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005086 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005087 case SK_UserConversion:
5088 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005089 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005090 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005091 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005092 case SK_ConversionSequence:
5093 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005094 case SK_UnwrapInitList:
5095 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005096 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005097 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005098 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005099 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005100 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005101 case SK_PassByIndirectCopyRestore:
5102 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005103 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005104 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005105 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005106 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005107 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005108 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005109 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005110 break;
John McCallf6a16482010-12-04 03:47:34 +00005111 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005112
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005113 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005114 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005115 case SK_ZeroInitialization:
5116 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005117 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005118
5119 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005120 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005121 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005122 for (step_iterator Step = step_begin(), StepEnd = step_end();
5123 Step != StepEnd; ++Step) {
5124 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005125 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005126
John Wiegley429bb272011-04-08 18:41:53 +00005127 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005128
Douglas Gregor20093b42009-12-09 23:02:17 +00005129 switch (Step->Kind) {
5130 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005131 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005132 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005133 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005134 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5135 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005136 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005137 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005138 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005139 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005140
Douglas Gregor20093b42009-12-09 23:02:17 +00005141 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005142 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005143 case SK_CastDerivedToBaseLValue: {
5144 // We have a derived-to-base cast that produces either an rvalue or an
5145 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005146
John McCallf871d0c2010-08-07 06:22:56 +00005147 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005148
Douglas Gregor20093b42009-12-09 23:02:17 +00005149 // Casts to inaccessible base classes are allowed with C-style casts.
5150 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5151 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005152 CurInit.get()->getLocStart(),
5153 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005154 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005155 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005156
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005157 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5158 QualType T = SourceType;
5159 if (const PointerType *Pointer = T->getAs<PointerType>())
5160 T = Pointer->getPointeeType();
5161 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005162 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005163 cast<CXXRecordDecl>(RecordTy->getDecl()));
5164 }
5165
John McCall5baba9d2010-08-25 10:28:54 +00005166 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005167 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005168 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005169 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005170 VK_XValue :
5171 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005172 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5173 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005174 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005175 CurInit.get(),
5176 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005177 break;
5178 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005179
Douglas Gregor20093b42009-12-09 23:02:17 +00005180 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00005181 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005182 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
5183 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005184 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005185 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00005186 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00005187 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00005188 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005189 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005190
John Wiegley429bb272011-04-08 18:41:53 +00005191 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005192 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005193 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5194 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005195 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005196 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005197 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005198 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005199
Douglas Gregor20093b42009-12-09 23:02:17 +00005200 // Reference binding does not have any corresponding ASTs.
5201
5202 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005203 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005204 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005205
Douglas Gregor20093b42009-12-09 23:02:17 +00005206 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005207
Douglas Gregor20093b42009-12-09 23:02:17 +00005208 case SK_BindReferenceToTemporary:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005209 // Make sure the "temporary" is actually an rvalue.
5210 assert(CurInit.get()->isRValue() && "not a temporary");
5211
Douglas Gregor20093b42009-12-09 23:02:17 +00005212 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005213 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005214 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005215
Douglas Gregor03e80032011-06-21 17:03:29 +00005216 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005217 CurInit = new (S.Context) MaterializeTemporaryExpr(
5218 Entity.getType().getNonReferenceType(),
5219 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005220 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005221
5222 // If we're binding to an Objective-C object that has lifetime, we
5223 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005224 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005225 CurInit.get()->getType()->isObjCLifetimeType())
5226 S.ExprNeedsCleanups = true;
5227
Douglas Gregor20093b42009-12-09 23:02:17 +00005228 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005229
Douglas Gregor523d46a2010-04-18 07:40:54 +00005230 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005231 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005232 /*IsExtraneousCopy=*/true);
5233 break;
5234
Douglas Gregor20093b42009-12-09 23:02:17 +00005235 case SK_UserConversion: {
5236 // We have a user-defined conversion that invokes either a constructor
5237 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005238 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005239 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005240 FunctionDecl *Fn = Step->Function.Function;
5241 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005242 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005243 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005244 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005245 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005246 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005247 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005248 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005249
Douglas Gregor20093b42009-12-09 23:02:17 +00005250 // Determine the arguments required to actually perform the constructor
5251 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005252 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005253 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005254 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005255 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005256 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005257
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005258 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005259 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005260 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005261 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005262 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005263 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005264 CXXConstructExpr::CK_Complete,
5265 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005266 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005267 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005268
Anders Carlsson9a68a672010-04-21 18:47:17 +00005269 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005270 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005271 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5272 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005273
John McCall2de56d12010-08-25 11:45:40 +00005274 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005275 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5276 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5277 S.IsDerivedFrom(SourceType, Class))
5278 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005279
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005280 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005281 } else {
5282 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005283 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005284 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005285 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005286 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5287 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005288
5289 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005290 // derived-to-base conversion? I believe the answer is "no", because
5291 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005292 ExprResult CurInitExprRes =
5293 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5294 FoundFn, Conversion);
5295 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005296 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005297 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005298
Douglas Gregor20093b42009-12-09 23:02:17 +00005299 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005300 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5301 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005302 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005303 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005304
John McCall2de56d12010-08-25 11:45:40 +00005305 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005306
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005307 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005308 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005309
Sebastian Redl3b802322011-07-14 19:07:55 +00005310 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005311 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5312
5313 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005314 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005315 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005316 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005317 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005318 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005319 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005320 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005321 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5322 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005323 }
5324 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005325
John McCallf871d0c2010-08-07 06:22:56 +00005326 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005327 CurInit.get()->getType(),
5328 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005329 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005330 if (MaybeBindToTemp)
5331 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005332 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005333 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005334 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005335 break;
5336 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005337
Douglas Gregor20093b42009-12-09 23:02:17 +00005338 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005339 case SK_QualificationConversionXValue:
5340 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005341 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005342 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005343 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005344 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005345 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005346 VK_XValue :
5347 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005348 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005349 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005350 }
5351
Jordan Rose1fd1e282013-04-11 00:58:58 +00005352 case SK_LValueToRValue: {
5353 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5354 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5355 CK_LValueToRValue,
5356 CurInit.take(),
5357 /*BasePath=*/0,
5358 VK_RValue));
5359 break;
5360 }
5361
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005362 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005363 Sema::CheckedConversionKind CCK
5364 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5365 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005366 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005367 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005368 ExprResult CurInitExprRes =
5369 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005370 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005371 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005372 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005373 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005374 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005375 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005376
Douglas Gregord87b61f2009-12-10 17:56:55 +00005377 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005378 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005379 // Hack: We must pass *ResultType if available in order to set the type
5380 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5381 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5382 // temporary, not a reference, so we should pass Ty.
5383 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5384 // Since this step is never used for a reference directly, we explicitly
5385 // unwrap references here and rewrap them afterwards.
5386 // We also need to create a InitializeTemporary entity for this.
5387 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005388 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005389 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005390 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5391 InitListChecker PerformInitList(S, InitEntity,
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005392 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005393 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00005394 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005395 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005396 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005397
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005398 if (ResultType) {
5399 if ((*ResultType)->isRValueReferenceType())
5400 Ty = S.Context.getRValueReferenceType(Ty);
5401 else if ((*ResultType)->isLValueReferenceType())
5402 Ty = S.Context.getLValueReferenceType(Ty,
5403 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5404 *ResultType = Ty;
5405 }
5406
5407 InitListExpr *StructuredInitList =
5408 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005409 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005410 CurInit = shouldBindAsTemporary(InitEntity)
5411 ? S.MaybeBindToTemporary(StructuredInitList)
5412 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005413 break;
5414 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005415
Sebastian Redl10f04a62011-12-22 14:44:04 +00005416 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005417 // When an initializer list is passed for a parameter of type "reference
5418 // to object", we don't get an EK_Temporary entity, but instead an
5419 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005420 // FIXME: This is a hack. What we really should do is create a user
5421 // conversion step for this case, but this makes it considerably more
5422 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005423 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5424 Entity.getType().getNonReferenceType());
5425 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005426 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005427 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005428 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5429 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005430 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005431 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5432 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005433 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005434 ConstructorInitRequiresZeroInit,
5435 /*IsListInitialization*/ true);
Sebastian Redl10f04a62011-12-22 14:44:04 +00005436 break;
5437 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005438
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005439 case SK_UnwrapInitList:
5440 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5441 break;
5442
5443 case SK_RewrapInitList: {
5444 Expr *E = CurInit.take();
5445 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5446 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005447 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005448 ILE->setSyntacticForm(Syntactic);
5449 ILE->setType(E->getType());
5450 ILE->setValueKind(E->getValueKind());
5451 CurInit = S.Owned(ILE);
5452 break;
5453 }
5454
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005455 case SK_ConstructorInitialization: {
5456 // When an initializer list is passed for a parameter of type "reference
5457 // to object", we don't get an EK_Temporary entity, but instead an
5458 // EK_Parameter entity with reference type.
5459 // FIXME: This is a hack. What we really should do is create a user
5460 // conversion step for this case, but this makes it considerably more
5461 // complicated. For now, this will do.
5462 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5463 Entity.getType().getNonReferenceType());
5464 bool UseTemporary = Entity.getType()->isReferenceType();
5465 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5466 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005467 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005468 ConstructorInitRequiresZeroInit,
5469 /*IsListInitialization*/ false);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005470 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005471 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005472
Douglas Gregor71d17402009-12-15 00:01:57 +00005473 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005474 step_iterator NextStep = Step;
5475 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005476 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005477 (NextStep->Kind == SK_ConstructorInitialization ||
5478 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005479 // The need for zero-initialization is recorded directly into
5480 // the call to the object's constructor within the next step.
5481 ConstructorInitRequiresZeroInit = true;
5482 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005483 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005484 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005485 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5486 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005487 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005488 Kind.getRange().getBegin());
5489
5490 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5491 TSInfo->getType().getNonLValueExprType(S.Context),
5492 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005493 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005494 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005495 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005496 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005497 break;
5498 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005499
5500 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005501 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005502 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005503 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005504 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5505 if (Result.isInvalid())
5506 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005507 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005508
5509 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005510 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005511 if (ConvTy != Sema::Compatible &&
5512 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005513 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005514 == Sema::Compatible)
5515 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005516 if (CurInitExprRes.isInvalid())
5517 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005518 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005519
Douglas Gregora41a8c52010-04-22 00:20:18 +00005520 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005521 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5522 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005523 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005524 getAssignmentAction(Entity),
5525 &Complained)) {
5526 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005527 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005528 } else if (Complained)
5529 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005530 break;
5531 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005532
5533 case SK_StringInit: {
5534 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005535 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005536 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005537 break;
5538 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005539
5540 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005541 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005542 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005543 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005544 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005545
5546 case SK_ArrayInit:
5547 // Okay: we checked everything before creating this step. Note that
5548 // this is a GNU extension.
5549 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005550 << Step->Type << CurInit.get()->getType()
5551 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005552
5553 // If the destination type is an incomplete array type, update the
5554 // type accordingly.
5555 if (ResultType) {
5556 if (const IncompleteArrayType *IncompleteDest
5557 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5558 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005559 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005560 *ResultType = S.Context.getConstantArrayType(
5561 IncompleteDest->getElementType(),
5562 ConstantSource->getSize(),
5563 ArrayType::Normal, 0);
5564 }
5565 }
5566 }
John McCallf85e1932011-06-15 23:02:42 +00005567 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005568
Richard Smith0f163e92012-02-15 22:38:09 +00005569 case SK_ParenthesizedArrayInit:
5570 // Okay: we checked everything before creating this step. Note that
5571 // this is a GNU extension.
5572 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5573 << CurInit.get()->getSourceRange();
5574 break;
5575
John McCallf85e1932011-06-15 23:02:42 +00005576 case SK_PassByIndirectCopyRestore:
5577 case SK_PassByIndirectRestore:
5578 checkIndirectCopyRestoreSource(S, CurInit.get());
5579 CurInit = S.Owned(new (S.Context)
5580 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5581 Step->Kind == SK_PassByIndirectCopyRestore));
5582 break;
5583
5584 case SK_ProduceObjCObject:
5585 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005586 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005587 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005588 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005589
5590 case SK_StdInitializerList: {
5591 QualType Dest = Step->Type;
5592 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00005593 bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005594 (void)Success;
5595 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005596
5597 // If the element type has a destructor, check it.
5598 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5599 if (!RD->hasIrrelevantDestructor()) {
5600 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5601 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5602 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5603 S.PDiag(diag::err_access_dtor_temp) << E);
Richard Smith82f145d2013-05-04 06:44:46 +00005604 if (S.DiagnoseUseOfDecl(Destructor, Kind.getLocation()))
5605 return ExprError();
Sebastian Redl28357452012-03-05 19:35:43 +00005606 }
5607 }
5608 }
5609
Sebastian Redl2b916b82012-01-17 22:49:42 +00005610 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005611 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5612 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005613 unsigned NumInits = ILE->getNumInits();
5614 SmallVector<Expr*, 16> Converted(NumInits);
5615 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5616 S.Context.getConstantArrayType(E,
5617 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5618 NumInits),
5619 ArrayType::Normal, 0));
5620 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5621 0, HiddenArray);
5622 for (unsigned i = 0; i < NumInits; ++i) {
5623 Element.setElementIndex(i);
5624 ExprResult Init = S.Owned(ILE->getInit(i));
Richard Smitha4dc51b2013-02-05 05:52:24 +00005625 ExprResult Res = S.PerformCopyInitialization(
5626 Element, Init.get()->getExprLoc(), Init,
5627 /*TopLevelOfInitList=*/ true);
Sebastian Redl2b916b82012-01-17 22:49:42 +00005628 assert(!Res.isInvalid() && "Result changed since try phase.");
5629 Converted[i] = Res.take();
5630 }
5631 InitListExpr *Semantic = new (S.Context)
5632 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005633 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005634 Semantic->setSyntacticForm(ILE);
5635 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005636 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005637 CurInit = S.Owned(Semantic);
5638 break;
5639 }
Guy Benyei21f18c42013-02-07 10:55:47 +00005640 case SK_OCLSamplerInit: {
5641 assert(Step->Type->isSamplerT() &&
5642 "Sampler initialization on non sampler type.");
5643
5644 QualType SourceType = CurInit.get()->getType();
5645 InitializedEntity::EntityKind EntityKind = Entity.getKind();
5646
5647 if (EntityKind == InitializedEntity::EK_Parameter) {
5648 if (!SourceType->isSamplerT())
5649 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5650 << SourceType;
5651 } else if (EntityKind != InitializedEntity::EK_Variable) {
5652 llvm_unreachable("Invalid EntityKind!");
5653 }
5654
5655 break;
5656 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00005657 case SK_OCLZeroEvent: {
5658 assert(Step->Type->isEventT() &&
5659 "Event initialization on non event type.");
5660
5661 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5662 CK_ZeroToOCLEvent,
5663 CurInit.get()->getValueKind());
5664 break;
5665 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005666 }
5667 }
John McCall15d7d122010-11-11 03:21:53 +00005668
5669 // Diagnose non-fatal problems with the completed initialization.
5670 if (Entity.getKind() == InitializedEntity::EK_Member &&
5671 cast<FieldDecl>(Entity.getDecl())->isBitField())
5672 S.CheckBitFieldInitialization(Kind.getLocation(),
5673 cast<FieldDecl>(Entity.getDecl()),
5674 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005675
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005676 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005677}
5678
Richard Smithd5bc8672012-12-08 02:01:17 +00005679/// Somewhere within T there is an uninitialized reference subobject.
5680/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00005681static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5682 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005683 if (T->isReferenceType()) {
5684 S.Diag(Loc, diag::err_reference_without_init)
5685 << T.getNonReferenceType();
5686 return true;
5687 }
5688
5689 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5690 if (!RD || !RD->hasUninitializedReferenceMember())
5691 return false;
5692
5693 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5694 FE = RD->field_end(); FI != FE; ++FI) {
5695 if (FI->isUnnamedBitfield())
5696 continue;
5697
5698 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5699 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5700 return true;
5701 }
5702 }
5703
5704 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5705 BE = RD->bases_end();
5706 BI != BE; ++BI) {
5707 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5708 S.Diag(Loc, diag::note_value_initialization_here) << RD;
5709 return true;
5710 }
5711 }
5712
5713 return false;
5714}
5715
5716
Douglas Gregor20093b42009-12-09 23:02:17 +00005717//===----------------------------------------------------------------------===//
5718// Diagnose initialization failures
5719//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00005720
5721/// Emit notes associated with an initialization that failed due to a
5722/// "simple" conversion failure.
5723static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5724 Expr *op) {
5725 QualType destType = entity.getType();
5726 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5727 op->getType()->isObjCObjectPointerType()) {
5728
5729 // Emit a possible note about the conversion failing because the
5730 // operand is a message send with a related result type.
5731 S.EmitRelatedResultTypeNote(op);
5732
5733 // Emit a possible note about a return failing because we're
5734 // expecting a related result type.
5735 if (entity.getKind() == InitializedEntity::EK_Result)
5736 S.EmitRelatedResultTypeNoteForReturn(destType);
5737 }
5738}
5739
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005740bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005741 const InitializedEntity &Entity,
5742 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005743 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005744 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005745 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005746
Douglas Gregord6542d82009-12-22 15:35:07 +00005747 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005748 switch (Failure) {
5749 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005750 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005751 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00005752 // Dig out the reference subobject which is uninitialized and diagnose it.
5753 // If this is value-initialization, this could be nested some way within
5754 // the target type.
5755 assert(Kind.getKind() == InitializationKind::IK_Value ||
5756 DestType->isReferenceType());
5757 bool Diagnosed =
5758 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5759 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5760 (void)Diagnosed;
5761 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005762 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005763 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005764 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005765
Douglas Gregor20093b42009-12-09 23:02:17 +00005766 case FK_ArrayNeedsInitList:
5767 case FK_ArrayNeedsInitListOrStringLiteral:
5768 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5769 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5770 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005771
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005772 case FK_ArrayTypeMismatch:
5773 case FK_NonConstantArrayInit:
5774 S.Diag(Kind.getLocation(),
5775 (Failure == FK_ArrayTypeMismatch
5776 ? diag::err_array_init_different_type
5777 : diag::err_array_init_non_constant_array))
5778 << DestType.getNonReferenceType()
5779 << Args[0]->getType()
5780 << Args[0]->getSourceRange();
5781 break;
5782
John McCall73076432012-01-05 00:13:19 +00005783 case FK_VariableLengthArrayHasInitializer:
5784 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5785 << Args[0]->getSourceRange();
5786 break;
5787
John McCall6bb80172010-03-30 21:47:33 +00005788 case FK_AddressOfOverloadFailed: {
5789 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005790 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005791 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005792 true,
5793 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005794 break;
John McCall6bb80172010-03-30 21:47:33 +00005795 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005796
Douglas Gregor20093b42009-12-09 23:02:17 +00005797 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005798 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005799 switch (FailedOverloadResult) {
5800 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005801 if (Failure == FK_UserConversionOverloadFailed)
5802 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5803 << Args[0]->getType() << DestType
5804 << Args[0]->getSourceRange();
5805 else
5806 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5807 << DestType << Args[0]->getType()
5808 << Args[0]->getSourceRange();
5809
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005810 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
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 OR_No_Viable_Function:
5814 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5815 << Args[0]->getType() << DestType.getNonReferenceType()
5816 << Args[0]->getSourceRange();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005817 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00005818 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005819
Douglas Gregor20093b42009-12-09 23:02:17 +00005820 case OR_Deleted: {
5821 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5822 << Args[0]->getType() << DestType.getNonReferenceType()
5823 << Args[0]->getSourceRange();
5824 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005825 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005826 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5827 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005828 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005829 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005830 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005831 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005832 }
5833 break;
5834 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005835
Douglas Gregor20093b42009-12-09 23:02:17 +00005836 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005837 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005838 }
5839 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005840
Douglas Gregor20093b42009-12-09 23:02:17 +00005841 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005842 if (isa<InitListExpr>(Args[0])) {
5843 S.Diag(Kind.getLocation(),
5844 diag::err_lvalue_reference_bind_to_initlist)
5845 << DestType.getNonReferenceType().isVolatileQualified()
5846 << DestType.getNonReferenceType()
5847 << Args[0]->getSourceRange();
5848 break;
5849 }
5850 // Intentional fallthrough
5851
Douglas Gregor20093b42009-12-09 23:02:17 +00005852 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005853 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005854 Failure == FK_NonConstLValueReferenceBindingToTemporary
5855 ? diag::err_lvalue_reference_bind_to_temporary
5856 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005857 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005858 << DestType.getNonReferenceType()
5859 << Args[0]->getType()
5860 << Args[0]->getSourceRange();
5861 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005862
Douglas Gregor20093b42009-12-09 23:02:17 +00005863 case FK_RValueReferenceBindingToLValue:
5864 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005865 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005866 << Args[0]->getSourceRange();
5867 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005868
Douglas Gregor20093b42009-12-09 23:02:17 +00005869 case FK_ReferenceInitDropsQualifiers:
5870 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5871 << DestType.getNonReferenceType()
5872 << Args[0]->getType()
5873 << Args[0]->getSourceRange();
5874 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005875
Douglas Gregor20093b42009-12-09 23:02:17 +00005876 case FK_ReferenceInitFailed:
5877 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5878 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005879 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005880 << Args[0]->getType()
5881 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00005882 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005883 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005884
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005885 case FK_ConversionFailed: {
5886 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005887 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005888 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005889 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005890 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005891 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005892 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005893 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5894 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00005895 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005896 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005897 }
John Wiegley429bb272011-04-08 18:41:53 +00005898
5899 case FK_ConversionFromPropertyFailed:
5900 // No-op. This error has already been reported.
5901 break;
5902
Douglas Gregord87b61f2009-12-10 17:56:55 +00005903 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005904 SourceRange R;
5905
5906 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005907 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005908 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005909 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005910 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005911
Douglas Gregor19311e72010-09-08 21:40:08 +00005912 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5913 if (Kind.isCStyleOrFunctionalCast())
5914 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5915 << R;
5916 else
5917 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5918 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005919 break;
5920 }
5921
5922 case FK_ReferenceBindingToInitList:
5923 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5924 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5925 break;
5926
5927 case FK_InitListBadDestinationType:
5928 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5929 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5930 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005931
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005932 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005933 case FK_ConstructorOverloadFailed: {
5934 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005935 if (Args.size())
5936 ArgsRange = SourceRange(Args.front()->getLocStart(),
5937 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005938
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005939 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005940 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005941 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005942 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005943 }
5944
Douglas Gregor51c56d62009-12-14 20:49:26 +00005945 // FIXME: Using "DestType" for the entity we're printing is probably
5946 // bad.
5947 switch (FailedOverloadResult) {
5948 case OR_Ambiguous:
5949 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5950 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005951 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005952 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005953
Douglas Gregor51c56d62009-12-14 20:49:26 +00005954 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005955 if (Kind.getKind() == InitializationKind::IK_Default &&
5956 (Entity.getKind() == InitializedEntity::EK_Base ||
5957 Entity.getKind() == InitializedEntity::EK_Member) &&
5958 isa<CXXConstructorDecl>(S.CurContext)) {
5959 // This is implicit default initialization of a member or
5960 // base within a constructor. If no viable function was
5961 // found, notify the user that she needs to explicitly
5962 // initialize this base/member.
5963 CXXConstructorDecl *Constructor
5964 = cast<CXXConstructorDecl>(S.CurContext);
5965 if (Entity.getKind() == InitializedEntity::EK_Base) {
5966 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00005967 << (Constructor->getInheritedConstructor() ? 2 :
5968 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005969 << S.Context.getTypeDeclType(Constructor->getParent())
5970 << /*base=*/0
5971 << Entity.getType();
5972
5973 RecordDecl *BaseDecl
5974 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5975 ->getDecl();
5976 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5977 << S.Context.getTagDeclType(BaseDecl);
5978 } else {
5979 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00005980 << (Constructor->getInheritedConstructor() ? 2 :
5981 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005982 << S.Context.getTypeDeclType(Constructor->getParent())
5983 << /*member=*/1
5984 << Entity.getName();
5985 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5986
5987 if (const RecordType *Record
5988 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005989 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005990 diag::note_previous_decl)
5991 << S.Context.getTagDeclType(Record->getDecl());
5992 }
5993 break;
5994 }
5995
Douglas Gregor51c56d62009-12-14 20:49:26 +00005996 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5997 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005998 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, 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_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006002 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006003 OverloadingResult Ovl
6004 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006005 if (Ovl != OR_Deleted) {
6006 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6007 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006008 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006009 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006010 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006011
6012 // If this is a defaulted or implicitly-declared function, then
6013 // it was implicitly deleted. Make it clear that the deletion was
6014 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006015 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006016 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006017 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006018 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006019 else
6020 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6021 << true << DestType << ArgsRange;
6022
6023 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006024 break;
6025 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006026
Douglas Gregor51c56d62009-12-14 20:49:26 +00006027 case OR_Success:
6028 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006029 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006030 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006031 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006032
Douglas Gregor99a2e602009-12-16 01:38:02 +00006033 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006034 if (Entity.getKind() == InitializedEntity::EK_Member &&
6035 isa<CXXConstructorDecl>(S.CurContext)) {
6036 // This is implicit default-initialization of a const member in
6037 // a constructor. Complain that it needs to be explicitly
6038 // initialized.
6039 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6040 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006041 << (Constructor->getInheritedConstructor() ? 2 :
6042 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006043 << S.Context.getTypeDeclType(Constructor->getParent())
6044 << /*const=*/1
6045 << Entity.getName();
6046 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6047 << Entity.getName();
6048 } else {
6049 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6050 << DestType << (bool)DestType->getAs<RecordType>();
6051 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006052 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006053
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006054 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006055 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006056 diag::err_init_incomplete_type);
6057 break;
6058
Sebastian Redl14b0c192011-09-24 17:48:00 +00006059 case FK_ListInitializationFailed: {
6060 // Run the init list checker again to emit diagnostics.
6061 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6062 QualType DestType = Entity.getType();
6063 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00006064 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00006065 Kind.getKind() != InitializationKind::IK_DirectList ||
Richard Smith80ad52f2013-01-02 11:42:31 +00006066 !S.getLangOpts().CPlusPlus11);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006067 assert(DiagnoseInitList.HadError() &&
6068 "Inconsistent init list check result.");
6069 break;
6070 }
John McCall5acb0c92011-10-17 18:40:02 +00006071
6072 case FK_PlaceholderType: {
6073 // FIXME: Already diagnosed!
6074 break;
6075 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006076
6077 case FK_InitListElementCopyFailure: {
6078 // Try to perform all copies again.
6079 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6080 unsigned NumInits = InitList->getNumInits();
6081 QualType DestType = Entity.getType();
6082 QualType E;
Douglas Gregor6c5aaed2013-03-25 23:47:01 +00006083 bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
Sebastian Redl2b916b82012-01-17 22:49:42 +00006084 (void)Success;
6085 assert(Success && "Where did the std::initializer_list go?");
6086 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6087 S.Context.getConstantArrayType(E,
6088 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6089 NumInits),
6090 ArrayType::Normal, 0));
6091 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6092 0, HiddenArray);
6093 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6094 // where the init list type is wrong, e.g.
6095 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6096 // FIXME: Emit a note if we hit the limit?
6097 int ErrorCount = 0;
6098 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6099 Element.setElementIndex(i);
6100 ExprResult Init = S.Owned(InitList->getInit(i));
6101 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6102 .isInvalid())
6103 ++ErrorCount;
6104 }
6105 break;
6106 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006107
6108 case FK_ExplicitConstructor: {
6109 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6110 << Args[0]->getSourceRange();
6111 OverloadCandidateSet::iterator Best;
6112 OverloadingResult Ovl
6113 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006114 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006115 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6116 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6117 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6118 break;
6119 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006120 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006121
Douglas Gregora41a8c52010-04-22 00:20:18 +00006122 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006123 return true;
6124}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006125
Chris Lattner5f9e2722011-07-23 10:55:15 +00006126void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006127 switch (SequenceKind) {
6128 case FailedSequence: {
6129 OS << "Failed sequence: ";
6130 switch (Failure) {
6131 case FK_TooManyInitsForReference:
6132 OS << "too many initializers for reference";
6133 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006134
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006135 case FK_ArrayNeedsInitList:
6136 OS << "array requires initializer list";
6137 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006138
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006139 case FK_ArrayNeedsInitListOrStringLiteral:
6140 OS << "array requires initializer list or string literal";
6141 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006142
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006143 case FK_ArrayTypeMismatch:
6144 OS << "array type mismatch";
6145 break;
6146
6147 case FK_NonConstantArrayInit:
6148 OS << "non-constant array initializer";
6149 break;
6150
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006151 case FK_AddressOfOverloadFailed:
6152 OS << "address of overloaded function failed";
6153 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006154
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006155 case FK_ReferenceInitOverloadFailed:
6156 OS << "overload resolution for reference initialization failed";
6157 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006158
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006159 case FK_NonConstLValueReferenceBindingToTemporary:
6160 OS << "non-const lvalue reference bound to temporary";
6161 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006162
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006163 case FK_NonConstLValueReferenceBindingToUnrelated:
6164 OS << "non-const lvalue reference bound to unrelated type";
6165 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006166
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006167 case FK_RValueReferenceBindingToLValue:
6168 OS << "rvalue reference bound to an lvalue";
6169 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006170
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006171 case FK_ReferenceInitDropsQualifiers:
6172 OS << "reference initialization drops qualifiers";
6173 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006174
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006175 case FK_ReferenceInitFailed:
6176 OS << "reference initialization failed";
6177 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006178
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006179 case FK_ConversionFailed:
6180 OS << "conversion failed";
6181 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006182
John Wiegley429bb272011-04-08 18:41:53 +00006183 case FK_ConversionFromPropertyFailed:
6184 OS << "conversion from property failed";
6185 break;
6186
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006187 case FK_TooManyInitsForScalar:
6188 OS << "too many initializers for scalar";
6189 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006190
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006191 case FK_ReferenceBindingToInitList:
6192 OS << "referencing binding to initializer list";
6193 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006194
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006195 case FK_InitListBadDestinationType:
6196 OS << "initializer list for non-aggregate, non-scalar type";
6197 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006198
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006199 case FK_UserConversionOverloadFailed:
6200 OS << "overloading failed for user-defined conversion";
6201 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006202
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006203 case FK_ConstructorOverloadFailed:
6204 OS << "constructor overloading failed";
6205 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006206
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006207 case FK_DefaultInitOfConst:
6208 OS << "default initialization of a const variable";
6209 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006210
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006211 case FK_Incomplete:
6212 OS << "initialization of incomplete type";
6213 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006214
6215 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006216 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006217 break;
6218
John McCall73076432012-01-05 00:13:19 +00006219 case FK_VariableLengthArrayHasInitializer:
6220 OS << "variable length array has an initializer";
6221 break;
6222
John McCall5acb0c92011-10-17 18:40:02 +00006223 case FK_PlaceholderType:
6224 OS << "initializer expression isn't contextually valid";
6225 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006226
6227 case FK_ListConstructorOverloadFailed:
6228 OS << "list constructor overloading failed";
6229 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006230
6231 case FK_InitListElementCopyFailure:
6232 OS << "copy construction of initializer list element failed";
6233 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006234
6235 case FK_ExplicitConstructor:
6236 OS << "list copy initialization chose explicit constructor";
6237 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006238 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006239 OS << '\n';
6240 return;
6241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006242
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006243 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006244 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006245 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006246
Sebastian Redl7491c492011-06-05 13:59:11 +00006247 case NormalSequence:
6248 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006249 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006250 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006251
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006252 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6253 if (S != step_begin()) {
6254 OS << " -> ";
6255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006256
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006257 switch (S->Kind) {
6258 case SK_ResolveAddressOfOverloadedFunction:
6259 OS << "resolve address of overloaded function";
6260 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006261
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006262 case SK_CastDerivedToBaseRValue:
6263 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6264 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006265
Sebastian Redl906082e2010-07-20 04:20:21 +00006266 case SK_CastDerivedToBaseXValue:
6267 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6268 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006269
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006270 case SK_CastDerivedToBaseLValue:
6271 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6272 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006273
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006274 case SK_BindReference:
6275 OS << "bind reference to lvalue";
6276 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006277
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006278 case SK_BindReferenceToTemporary:
6279 OS << "bind reference to a temporary";
6280 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006281
Douglas Gregor523d46a2010-04-18 07:40:54 +00006282 case SK_ExtraneousCopyToTemporary:
6283 OS << "extraneous C++03 copy to temporary";
6284 break;
6285
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006286 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006287 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006288 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006289
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006290 case SK_QualificationConversionRValue:
6291 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006292 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006293
Sebastian Redl906082e2010-07-20 04:20:21 +00006294 case SK_QualificationConversionXValue:
6295 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006296 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006297
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006298 case SK_QualificationConversionLValue:
6299 OS << "qualification conversion (lvalue)";
6300 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006301
Jordan Rose1fd1e282013-04-11 00:58:58 +00006302 case SK_LValueToRValue:
6303 OS << "load (lvalue to rvalue)";
6304 break;
6305
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006306 case SK_ConversionSequence:
6307 OS << "implicit conversion sequence (";
6308 S->ICS->DebugPrint(); // FIXME: use OS
6309 OS << ")";
6310 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006311
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006312 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006313 OS << "list aggregate initialization";
6314 break;
6315
6316 case SK_ListConstructorCall:
6317 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006318 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006319
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006320 case SK_UnwrapInitList:
6321 OS << "unwrap reference initializer list";
6322 break;
6323
6324 case SK_RewrapInitList:
6325 OS << "rewrap reference initializer list";
6326 break;
6327
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006328 case SK_ConstructorInitialization:
6329 OS << "constructor initialization";
6330 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006331
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006332 case SK_ZeroInitialization:
6333 OS << "zero initialization";
6334 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006335
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006336 case SK_CAssignment:
6337 OS << "C assignment";
6338 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006339
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006340 case SK_StringInit:
6341 OS << "string initialization";
6342 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006343
6344 case SK_ObjCObjectConversion:
6345 OS << "Objective-C object conversion";
6346 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006347
6348 case SK_ArrayInit:
6349 OS << "array initialization";
6350 break;
John McCallf85e1932011-06-15 23:02:42 +00006351
Richard Smith0f163e92012-02-15 22:38:09 +00006352 case SK_ParenthesizedArrayInit:
6353 OS << "parenthesized array initialization";
6354 break;
6355
John McCallf85e1932011-06-15 23:02:42 +00006356 case SK_PassByIndirectCopyRestore:
6357 OS << "pass by indirect copy and restore";
6358 break;
6359
6360 case SK_PassByIndirectRestore:
6361 OS << "pass by indirect restore";
6362 break;
6363
6364 case SK_ProduceObjCObject:
6365 OS << "Objective-C object retension";
6366 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006367
6368 case SK_StdInitializerList:
6369 OS << "std::initializer_list from initializer list";
6370 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006371
Guy Benyei21f18c42013-02-07 10:55:47 +00006372 case SK_OCLSamplerInit:
6373 OS << "OpenCL sampler_t from integer constant";
6374 break;
6375
Guy Benyeie6b9d802013-01-20 12:31:11 +00006376 case SK_OCLZeroEvent:
6377 OS << "OpenCL event_t from zero";
6378 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006379 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006380
6381 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006382 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006383
6384 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006385}
6386
6387void InitializationSequence::dump() const {
6388 dump(llvm::errs());
6389}
6390
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006391static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6392 QualType EntityType,
6393 const Expr *PreInit,
6394 const Expr *PostInit) {
6395 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6396 return;
6397
6398 // A narrowing conversion can only appear as the final implicit conversion in
6399 // an initialization sequence.
6400 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6401 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6402 return;
6403
6404 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6405 const StandardConversionSequence *SCS = 0;
6406 switch (ICS.getKind()) {
6407 case ImplicitConversionSequence::StandardConversion:
6408 SCS = &ICS.Standard;
6409 break;
6410 case ImplicitConversionSequence::UserDefinedConversion:
6411 SCS = &ICS.UserDefined.After;
6412 break;
6413 case ImplicitConversionSequence::AmbiguousConversion:
6414 case ImplicitConversionSequence::EllipsisConversion:
6415 case ImplicitConversionSequence::BadConversion:
6416 return;
6417 }
6418
6419 // Determine the type prior to the narrowing conversion. If a conversion
6420 // operator was used, this may be different from both the type of the entity
6421 // and of the pre-initialization expression.
6422 QualType PreNarrowingType = PreInit->getType();
6423 if (Seq.step_begin() + 1 != Seq.step_end())
6424 PreNarrowingType = Seq.step_end()[-2].Type;
6425
6426 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6427 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006428 QualType ConstantType;
6429 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6430 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006431 case NK_Not_Narrowing:
6432 // No narrowing occurred.
6433 return;
6434
6435 case NK_Type_Narrowing:
6436 // This was a floating-to-integer conversion, which is always considered a
6437 // narrowing conversion even if the value is a constant and can be
6438 // represented exactly as an integer.
6439 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006440 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006441 diag::warn_init_list_type_narrowing
6442 : S.isSFINAEContext()?
6443 diag::err_init_list_type_narrowing_sfinae
6444 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006445 << PostInit->getSourceRange()
6446 << PreNarrowingType.getLocalUnqualifiedType()
6447 << EntityType.getLocalUnqualifiedType();
6448 break;
6449
6450 case NK_Constant_Narrowing:
6451 // A constant value was narrowed.
6452 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006453 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006454 diag::warn_init_list_constant_narrowing
6455 : S.isSFINAEContext()?
6456 diag::err_init_list_constant_narrowing_sfinae
6457 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006458 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006459 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006460 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006461 break;
6462
6463 case NK_Variable_Narrowing:
6464 // A variable's value may have been narrowed.
6465 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006466 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006467 diag::warn_init_list_variable_narrowing
6468 : S.isSFINAEContext()?
6469 diag::err_init_list_variable_narrowing_sfinae
6470 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006471 << PostInit->getSourceRange()
6472 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006473 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006474 break;
6475 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006476
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006477 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006478 llvm::raw_svector_ostream OS(StaticCast);
6479 OS << "static_cast<";
6480 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6481 // It's important to use the typedef's name if there is one so that the
6482 // fixit doesn't break code using types like int64_t.
6483 //
6484 // FIXME: This will break if the typedef requires qualification. But
6485 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006486 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006487 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006488 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006489 else {
6490 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6491 // with a broken cast.
6492 return;
6493 }
6494 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006495 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6496 << PostInit->getSourceRange()
6497 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006498 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006499 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006500}
6501
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006502//===----------------------------------------------------------------------===//
6503// Initialization helper functions
6504//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006505bool
6506Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6507 ExprResult Init) {
6508 if (Init.isInvalid())
6509 return false;
6510
6511 Expr *InitE = Init.get();
6512 assert(InitE && "No initialization expression");
6513
Douglas Gregor3c394c52012-07-31 22:15:04 +00006514 InitializationKind Kind
6515 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006516 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006517 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006518}
6519
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006520ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006521Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6522 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006523 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006524 bool TopLevelOfInitList,
6525 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006526 if (Init.isInvalid())
6527 return ExprError();
6528
John McCall15d7d122010-11-11 03:21:53 +00006529 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006530 assert(InitE && "No initialization expression?");
6531
6532 if (EqualLoc.isInvalid())
6533 EqualLoc = InitE->getLocStart();
6534
6535 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006536 EqualLoc,
6537 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006538 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006539 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006540
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006541 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006542
6543 if (!Result.isInvalid() && TopLevelOfInitList)
6544 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6545 InitE, Result.get());
6546
6547 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006548}